Commit d5096480 by sunqi02 Committed by 胡悦

refactor: unify SessionMemory storage to AgentScope Msg.to_dict() format

- add() uses Msg.to_dict() internally, content supports str | list[dict]
- rename agent_code param to name, mapping to Msg.name
- add remove_last() for conditional cleanup
- fix summary truncation to use standard format
- drop redundant agent_id/intent fields

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 79d72209
...@@ -4,10 +4,12 @@ from __future__ import annotations ...@@ -4,10 +4,12 @@ from __future__ import annotations
import logging import logging
from typing import Any, List, Optional from typing import Any, List, Optional
logger = logging.getLogger(__name__) from agentscope.message import Msg
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
logger = logging.getLogger(__name__)
class SessionMemory: class SessionMemory:
"""管理单个 session 的消息历史,提供 Memory API(add / get_messages / compress)。""" """管理单个 session 的消息历史,提供 Memory API(add / get_messages / compress)。"""
...@@ -28,26 +30,41 @@ class SessionMemory: ...@@ -28,26 +30,41 @@ class SessionMemory:
return [] return []
return list(existing.get("conversation_history") or []) return list(existing.get("conversation_history") or [])
def add(self, role: str, content: str, agent_code: Optional[str] = None) -> None: def add(self, role: str, content: str | list[dict], name: Optional[str] = None) -> None:
existing = self._store.get(self.session_id) existing = self._store.get(self.session_id)
if not existing: if not existing:
return return
history: list[dict[str, Any]] = list(existing.get("conversation_history") or []) history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
from app.infrastructure.time import china_now msg = Msg(
history.append({ name=name or role,
"role": role, content=content,
"content": content, role=role,
"agent_code": agent_code, )
"agent_id": None, history.append(msg.to_dict())
"intent": None,
"timestamp": china_now().isoformat(),
})
existing["conversation_history"] = history existing["conversation_history"] = history
self._store.set(self.session_id, existing) self._store.set(self.session_id, existing)
logger.info( logger.info(
"[SessionMemory] session=%s add role=%s → conversation_history 长度=%d", "[SessionMemory] session=%s add role=%s name=%s → conversation_history 长度=%d",
self.session_id, role, name or role, len(history),
)
def remove_last(self, role: Optional[str] = None) -> Optional[dict]:
"""移除 conversation_history 最后一条(可限定 role),返回被移除的消息。"""
history = self._load()
if not history:
return None
if role is not None and history[-1].get("role") != role:
return None
popped = history.pop()
data = self._store.get(self.session_id)
if data:
data["conversation_history"] = history
self._store.set(self.session_id, data)
logger.info(
"[SessionMemory] session=%s remove_last role_filter=%s → conversation_history 长度=%d",
self.session_id, role, len(history), self.session_id, role, len(history),
) )
return popped
def get_messages( def get_messages(
self, self,
...@@ -71,7 +88,8 @@ class SessionMemory: ...@@ -71,7 +88,8 @@ class SessionMemory:
result = [] result = []
if include_summary and overflow: if include_summary and overflow:
summary = self._summarize(overflow) summary = self._summarize(overflow)
result.append({"role": "system", "content": f"[早期对话摘要] {summary}"}) summary_msg = Msg("system", f"[早期对话摘要] {summary}", "system")
result.append(summary_msg.to_dict())
result.extend(recent) result.extend(recent)
return result return result
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!