memory.py
2.85 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
"""Memory 包装层 — 封装 ConversationHistory 的消息存取和压缩。"""
from __future__ import annotations
from typing import Any, List, Optional
from app.infrastructure.session_store import SessionStore
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, agent_code: 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 [])
from datetime import datetime, timezone
history.append({
"role": role,
"content": content,
"agent_code": agent_code,
"agent_id": None,
"intent": None,
"timestamp": datetime.now(timezone.utc).isoformat(),
})
existing["conversation_history"] = history
self._store.set(self.session_id, existing)
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)
result.append({"role": "system", "content": f"[早期对话摘要] {summary}"})
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}]")