Files
beaver_project/app-instance/backend/beaver/memory/curated/snapshot.py

53 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""curated memory 的冻结快照工具。
这个文件很小,但职责非常关键:它把“长期记忆的 live state”和“当前会话注入 prompt
时使用的 frozen snapshot”明确分开。
设计目的:
1. 让调用侧显式意识到system prompt 使用的是一份冻结视图
2. 避免后续 engine/context builder 直接偷读 live store破坏 frozen snapshot 语义
3. 给 prompt 组装层一个简单、稳定、可测试的数据结构
"""
from __future__ import annotations
from dataclasses import dataclass
from .store import MemoryStore
@dataclass(frozen=True, slots=True)
class MemorySnapshot:
"""当前 session 使用的冻结记忆快照。
这里不是 memory store 本体,而是“给 prompt builder 的只读投影”。
一旦 capture 完成,这个对象就代表本 session 的注入视图,不应在会话中途被修改。
"""
memory_block: str | None
user_block: str | None
def as_prompt_sections(self) -> list[str]:
"""按稳定顺序返回可直接拼接进 prompt 的 section 列表。
顺序固定为:
1. user profile
2. agent memory
这样后续 context builder 的输出更稳定,测试也更容易写。
"""
return [section for section in (self.user_block, self.memory_block) if section]
def capture_memory_snapshot(store: MemoryStore) -> MemorySnapshot:
"""从 `MemoryStore` 提取当前 session 的 frozen snapshot。
前提是 `store.load_from_disk()` 已经在 session 启动时调用过,否则拿到的只是空快照。
"""
return MemorySnapshot(
memory_block=store.format_for_system_prompt("memory"),
user_block=store.format_for_system_prompt("user"),
)