memory.py
3.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""Memory 包装层 — 封装 ConversationHistory 的消息存取和压缩。"""
from __future__ import annotations
import logging
from typing import Any, List, Optional
from agentscope.message import Msg
from app.infrastructure.session_store import SessionStore
logger = logging.getLogger(__name__)
class SessionMemory:
"""管理单个 session 的消息历史,提供 Memory API(add / get_messages / compress)。"""
def __init__(
self,
session_id: str,
store: SessionStore,
max_rounds: int = 20,
) -> None:
self.session_id = session_id
self._store = store
self.max_rounds = max_rounds
def _load(self) -> List[dict[str, Any]]:
existing = self._store.get(self.session_id)
if not existing:
return []
return list(existing.get("conversation_history") or [])
def add(self, role: str, content: str | list[dict], name: Optional[str] = None) -> None:
existing = self._store.get(self.session_id)
if not existing:
return
history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
msg = Msg(
name=name or role,
content=content,
role=role,
)
history.append(msg.to_dict())
existing["conversation_history"] = history
self._store.set(self.session_id, existing)
logger.info(
"[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),
)
return popped
def get_messages(
self,
max_rounds: Optional[int] = None,
include_summary: bool = True,
) -> list[dict[str, Any]]:
"""
Return messages suitable for model injection.
Auto-applies summarize_truncation: when exceeding max_rounds, compresses early messages into a summary.
"""
history = self._load()
limit = max_rounds if max_rounds is not None else self.max_rounds
if len(history) <= limit * 2:
return history
# summarize_truncation: compress early messages
overflow = history[:-(limit * 2)]
recent = history[-(limit * 2):]
result = []
if include_summary and overflow:
summary = self._summarize(overflow)
summary_msg = Msg("system", f"[早期对话摘要] {summary}", "system")
result.append(summary_msg.to_dict())
result.extend(recent)
return result
def _summarize(self, messages: list[dict[str, Any]]) -> str:
"""Simple summary: extract key content from user queries."""
parts = []
for m in messages:
if m.get("role") == "user" and m.get("content"):
text = m["content"][:100]
parts.append(text)
return ";".join(parts[-5:]) if parts else "(无关键内容)"
def mark(self, label: str) -> None:
"""Insert a checkpoint marker in conversation history."""
self.add("system", f"[MARK: {label}]")