Commit 1cf6119c by sunqi02

feat(layer4): add Memory wrapper with summarize_truncation

Introduce SessionMemory as a clean Memory API wrapping SessionStore,
providing message add/get with summarization when conversation exceeds
max_rounds. Integrate into AgentHub.process_message to replace direct
SessionService calls for message read/write. Add ensure_active_session
to SessionService for session lifecycle management.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 65cb8408
......@@ -7,6 +7,7 @@ from app.config.loader import ConfigLoader
from app.service.session_service import SessionService
from agentscope.tool import Toolkit
from app.hooks.post_reply import PostReplyHook
from app.service.memory import SessionMemory
from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg
......@@ -220,7 +221,13 @@ class AgentHub:
channel=channel
)
messages = self.session_service.get_session_messages(session.id)
memory = SessionMemory(
session_id=session_id,
store=self.session_service.store,
max_rounds=20,
)
messages = memory.get_messages(max_rounds=10)
# Determine target agent and routing reason
if mentioned_agent_code and mentioned_agent_code in self.agents:
......@@ -265,20 +272,9 @@ class AgentHub:
tools=tool_schemas if tool_schemas else None,
)
# Store messages (session.id = session_id 字符串)
self.session_service.add_message(
session_id=session.id,
role="user",
content=user_query,
agent_code=mentioned_agent_code or "main"
)
self.session_service.add_message(
session_id=session.id,
role="assistant",
content=response_content,
agent_code=target_agent
)
# Store messages via SessionMemory
memory.add("user", user_query, agent_code=mentioned_agent_code or "main")
memory.add("assistant", response_content, agent_code=target_agent)
if target_agent != "main":
self.session_service.update_current_agent(session.id, target_agent)
......
"""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}]")
......@@ -360,3 +360,25 @@ class SessionService:
def get_session_by_uuid(self, session_id: str) -> Optional[SessionInfo]:
"""按 UUID 获取会话(= get_session 的别名,语义一致)。"""
return self.get_session(session_id)
def ensure_active_session(self, session_id: str, user_id: str, channel: str, room_id: str = "") -> None:
"""Ensure session exists in KV store (create if not found, refresh TTL if exists)."""
existing = self.store.get(session_id)
if existing:
self.store.refresh_ttl(session_id)
return
now = _utcnow()
current_agent_id = self._default_agent_id()
payload = {
"session_id": session_id,
"user_id": user_id,
"channel": channel,
"room_id": room_id,
"current_agent_id": current_agent_id,
"current_agent_code": None,
"conversation_history": [],
"context_entities": {},
"created_at": now.isoformat(),
"updated_at": now.isoformat(),
}
self.store.set(session_id, payload)
"""SessionMemory unit tests — message add/get/truncation/mark."""
import pytest
from datetime import datetime, timezone
from app.service.memory import SessionMemory
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
@pytest.fixture
def store():
clear_default_store_for_tests()
return SessionStore()
@pytest.fixture
def active_session(store):
session_id = "test_session_001"
store.set(session_id, {
"session_id": session_id,
"user_id": "u1",
"channel": "test",
"current_agent_id": 101,
"conversation_history": [
{"role": "user", "content": "你好", "agent_code": "main",
"agent_id": None, "intent": None, "timestamp": datetime.now(timezone.utc).isoformat()},
{"role": "assistant", "content": "你好!有什么可以帮助你的?", "agent_code": "main",
"agent_id": 101, "intent": None, "timestamp": datetime.now(timezone.utc).isoformat()},
],
"context_entities": {},
"created_at": datetime.now(timezone.utc).isoformat(),
"updated_at": datetime.now(timezone.utc).isoformat(),
})
return session_id
class TestSessionMemory:
def test_get_messages_returns_history(self, store, active_session):
memory = SessionMemory(active_session, store)
msgs = memory.get_messages()
assert len(msgs) == 2
assert msgs[0]["content"] == "你好"
def test_add_appends_message(self, store, active_session):
memory = SessionMemory(active_session, store)
memory.add("user", "天气怎么样?")
msgs = memory.get_messages()
assert len(msgs) == 3
assert msgs[-1]["content"] == "天气怎么样?"
def test_truncation_with_many_messages(self, store, active_session):
# Insert 50 messages (total 52 with the 2 seeded) via memory.add()
memory = SessionMemory(active_session, store, max_rounds=5)
for i in range(50):
memory.add("user", f"msg {i}", agent_code="main")
msgs = memory.get_messages()
# Should contain summary + at most 10 recent messages (5 rounds × 2)
assert len(msgs) <= 11 # 1 summary + 10 msgs
# First message should be the summary
assert "早期对话摘要" in msgs[0]["content"]
def test_mark_inserts_checkpoint(self, store, active_session):
memory = SessionMemory(active_session, store)
memory.mark("checkpoint_1")
msgs = memory.get_messages()
assert any("[MARK: checkpoint_1]" in m.get("content", "") for m in msgs)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!