| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- """
- agentpaas.engine.memory_store — Persistent cross-run agent memory.
- Implements a simplified version of the Letta 3-layer memory model:
- Layer 1 — Core Memory (always in context):
- Small structured dict: persona, user facts, task context.
- Stored in {data_dir}/core_memory.json.
- Layer 2 — Recall Memory (recent interactions):
- Append-only JSONL log of (run_id, input, output, timestamp).
- Stored in {data_dir}/recall_log.jsonl.
- Bounded to last MAX_RECALL entries to control size.
- Layer 3 — Archival Memory (searchable long-term store):
- Delegated to the Knowledge Base system (BM25 indexes).
- This module only handles layers 1-2.
- Usage in _execute_agent:
- ctx.memory = load_memory(agent_dir) # before term.apply()
- save_memory(agent_dir, ctx.memory, run_id, input_text, str(result))
- """
- from __future__ import annotations
- import json
- import os
- from pathlib import Path
- from typing import Any, Dict
- MAX_RECALL = 50 # keep last N run summaries in recall log
- def _memory_dir(agent_dir: str) -> Path:
- """Return the memory sub-directory for an agent, creating it if needed."""
- p = Path(agent_dir) / "memory"
- p.mkdir(parents=True, exist_ok=True)
- return p
- def load_memory(agent_dir: str) -> Dict[str, Any]:
- """Load Core Memory dict from {agent_dir}/memory/core_memory.json.
- Returns an empty dict if the file does not exist yet.
- The dict is injected into ctx.memory before term execution so that
- Memory(agent, store) terms can read/write it within the run.
- """
- if not agent_dir:
- return {}
- core_file = _memory_dir(agent_dir) / "core_memory.json"
- if not core_file.exists():
- return {}
- try:
- return json.loads(core_file.read_text(encoding="utf-8"))
- except Exception:
- return {}
- def save_memory(
- agent_dir: str,
- memory: Dict[str, Any],
- run_id: str = "",
- input_text: str = "",
- output_text: str = "",
- ) -> None:
- """Persist Core Memory and append a Recall entry.
- Args:
- agent_dir: Agent / instance directory.
- memory: ctx.memory dict after run completion.
- run_id: Run identifier for recall log.
- input_text: User input (truncated to 500 chars in recall).
- output_text: Agent output (truncated to 500 chars in recall).
- """
- if not agent_dir:
- return
- mem_dir = _memory_dir(agent_dir)
- # ── Layer 1: save Core Memory ────────────────────────────────
- try:
- core_file = mem_dir / "core_memory.json"
- tmp = core_file.with_suffix(".json.tmp")
- tmp.write_text(
- json.dumps(memory, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
- tmp.replace(core_file)
- except Exception:
- pass
- # ── Layer 2: append Recall log ───────────────────────────────
- if not run_id:
- return
- try:
- from agentpaas.db.models import now_utc
- entry = json.dumps({
- "run_id": run_id,
- "input": input_text[:500],
- "output": output_text[:500],
- "ts": now_utc(),
- }, ensure_ascii=False)
- recall_file = mem_dir / "recall_log.jsonl"
- existing_lines: list[str] = []
- if recall_file.exists():
- existing_lines = recall_file.read_text(encoding="utf-8").splitlines()
- # Trim to MAX_RECALL - 1, then append new entry
- trimmed = existing_lines[-(MAX_RECALL - 1):] + [entry]
- recall_file.write_text("\n".join(trimmed) + "\n", encoding="utf-8")
- except Exception:
- pass
- def load_recall_summary(agent_dir: str, n: int = 5) -> str:
- """Return the last N recall entries as a readable string for prompt injection.
- Example output:
- [上次对话]
- Run run_abc: Q: ... A: ...
- Run run_xyz: Q: ... A: ...
- """
- if not agent_dir:
- return ""
- recall_file = _memory_dir(agent_dir) / "recall_log.jsonl"
- if not recall_file.exists():
- return ""
- try:
- lines = recall_file.read_text(encoding="utf-8").splitlines()
- recent = lines[-n:] if len(lines) >= n else lines
- entries = []
- for line in recent:
- try:
- d = json.loads(line)
- entries.append(
- f"Run {d.get('run_id','?')} ({d.get('ts','?')[:10]}): "
- f"Q: {d.get('input','')[:100]} A: {d.get('output','')[:100]}"
- )
- except Exception:
- pass
- if not entries:
- return ""
- return "[近期对话记录]\n" + "\n".join(entries)
- except Exception:
- return ""
|