memory.py 2.85 KB
"""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}]")