记忆
AgenticX 记忆系统。
AgenticX 中的记忆
记忆用来保住身份、近期工作和有界窗口。Near 主路径是工作区文件(MEMORY.md、memory/*.md)加会话 `messages.json`,再召回注入 Meta 系统提示。Mem0 等是库后端,不是桌面默认。
实践案例:写下偏好,下一轮就能用
场景。 希望 Meta 记住你的称呼,并避开某种排版习惯。
- 把事实写进
~/.agenticx/workspace/MEMORY.md或memory/*.md(设置里的用户偏好也会经_build_user_profile_block()注入)。 - 同一 Meta 会话再开一轮。系统提示应带上
_build_memory_recall_context的召回块。 - 长对话可能压缩:旧历史变成一条摘要 system。文件里的事实即使 transcript 被压过也应还在。
你会看到。 工作区面板高亮 MEMORY.md。下一轮回答直接用称呼,不用你再重复。会话标题保持已落盘的中文标题,而不是裸 session_id。

这些机制共同构成近似分层的记忆栈:必须始终成立的内容(身份)、最近发生的事(情节)、可泛化的知识(语义)、本轮模型可见的内容(工作集)、跨会话保留的内容(长期文件与存储),以及落在用户磁盘工作区内的范围化记忆。
记忆层级(六层模型)
下表将经典认知式层级映射到 AgenticX 的具体实现。各层为 概念性 划分;多项能力在实现上会有重叠。
| Layer | Role | AgenticX realization |
|---|---|---|
| Core memory | Stable role, name, non-negotiable facts | IDENTITY.md, SOUL.md, avatar/session system prompts, Meta-Agent identity blocks |
| Episodic memory | What was said and done in conversations | chat_history / persisted messages.json, tool traces in history |
| Semantic memory | Reusable knowledge, not tied to one chat | Curated MEMORY.md, optional Mem0 / knowledge components, indexed chunks in WorkspaceMemoryStore |
| Short-term / working memory | Scratch space for the current task | Per-session scratchpad dict, scratchpad_write / scratchpad_read tools, recent message window |
| Long-term memory | Cross-session persistence | MEMORY.md (manual + auto-append), SQLite session store for scratchpad, optional Mem0 |
| Workspace memory | Project- and user-scoped files under ~/.agenticx/workspace | USER.md, daily memory/<YYYY-MM-DD>.md, directory layout per avatar/project |
MemoryHook
MemoryHook 是注册在 AgentRuntime 上的 AgentHook,`priority=-10`,因此在 run_on_agent_end 遍历注册表时,会在数值优先级更高的钩子 之后 运行。
触发时机
- 一轮对话结束后调用 `on_agent_end`。
- 读取
session.chat_history。若len(chat_history) < MIN_CHAT_TURNS * 2则立即返回。默认MIN_CHAT_TURNS = 3→ 至少需要 六条聊天记录。 - 工作区目录:
session.workspace_dir,否则AGX_WORKSPACE_ROOT,再否则用户主目录。
抽取与上限
- 仅启发式(无额外 LLM 调用):扫描 最近 20 条 消息中的中文用户请求线索与助手完成线索,输出如
- 用户请求:/- 完成事项:的 bullet 行。 - 输出上限为 `MAX_FACTS_PER_SESSION`(8) 条事实。
持久化
- 向工作区 `memory/<today>.md` 追加带日期的块。若现有日文件加新块将超过 8000 字符则跳过追加。
- 若 `MEMORY.md` 存在且不足 4000 字符,追加
## Auto-extracted节,最多 四条 事实。
Scratchpad
- 将事实合并进
session.scratchpad["session_facts"](以换行拼接)。
`_maybe_compact_daily`
- 若当日
memory/<YYYY-MM-DD>.md超过 2000 字符则重写:保留标题,按 前 80 字符(大小写折叠)去重 bullet 行,保留首次出现。这是 确定性去重,不是 LLM 摘要。
1# Reference constants (agenticx/runtime/hooks/memory_hook.py)2MIN_CHAT_TURNS = 3 # requires len(chat_history) >= MIN_CHAT_TURNS * 23MAX_FACTS_PER_SESSION = 8
工作区记忆
目录结构(`~/.agenticx/workspace/`)
| Path | Purpose |
|---|---|
IDENTITY.md | Who the agent is; stable persona |
USER.md | User profile, preferences |
SOUL.md | Deeper style / values / tone |
MEMORY.md | Long-form durable notes; receives optional auto-extracted sections |
memory/<YYYY-MM-DD>.md | Daily session-fact log from MemoryHook |
分身/群聊等额外会话产物可并存;搜索索引 明确拉取四个根 markdown 文件及 memory/*.md。
自动召回:`_build_memory_recall_context`
定义于 agenticx/runtime/prompts/meta_agent.py。构建 Meta-Agent 系统提示时:
- 从 最近五条 用户消息收集文本(每条最多 200 字符)。
- 构建查询字符串(最多 500 字符)。
- 调用
WorkspaceMemoryStore.search_sync(..., limit=5, mode="hybrid")。 - 注入
## 相关历史记忆(自动召回)节,片段总量约 500 字符上限。
若无用户消息或无命中,则省略该节。
Mem0 集成
Mem0 为 可选。通过附带 memory 依赖的 extra 安装:
1pip install "agenticx[memory]"
运行时,依赖就绪时 agenticx.memory 暴露 Mem0 / 异步变体;agenticx/integrations/mem0/ 下的集成支持多种向量存储与配置。当你需要 托管的长期语义记忆(add/search API,托管或本地)而非或辅以基于文件的 MEMORY.md 时使用 Mem0。
会话 scratchpad
每个 StudioSession 携带通过 SQLite 持久化的 `scratchpad` 字典(agenticx/memory/session_store.py)。除 scratchpad_write 的用户/智能体键外,运行时使用保留模式:
| Key pattern | Purpose |
|---|---|
subagent_result::<id> | Summary text after a subagent / delegation completes |
delegation_result::<id> | Same pipeline writes delegation outcomes for Meta-Agent follow-up |
session_facts | Incremental lines from MemoryHook |
__pending_subagent_summaries__ | Queue of pending subagent reports (internal) |
__taskspace_hint__ / __taskspace_label_hint__ | Taskspace path hints from tools |
Meta-Agent 构建上下文时,在注册表行缺失时会读取 subagent_result::* 作为「历史子智能体结果」。
上下文压缩(`ContextCompactor`)
每轮开始前,AgentRuntime 对 已清洗 的 agent_messages 运行 ContextCompactor.maybe_compact。
| Parameter | Default | Behavior |
|---|---|---|
threshold_messages | 20 | Compact if message count exceeds this |
threshold_chars | 48000 | Or if sum of content string lengths exceeds this |
retain_recent_messages | 8 | Oldest portion is summarized; these tail messages stay verbatim |
流程:
- 拆分为 前缀(待压缩)与 后缀(保留)。
- 用中文压缩指令调用运行时 LLM(temperature
0,max_tokens400)。 - 用带
[compacted]前缀的单一 system 消息与摘要替换前缀。 - 失败时回退为拼接的短片段。
强制下限:threshold_messages >= 8、threshold_chars >= 4000、retain_recent_messages >= 4。
记忆相关配置
| Item | Where | Description |
|---|---|---|
memory.backend | ~/.agenticx/config.yaml | Declared in docs for pluggable memory backends (sqlite, redis, postgresql, etc.) |
memory.path | ~/.agenticx/config.yaml | Workspace root for memory features |
AGX_WORKSPACE_ROOT | Environment | Fallback workspace directory for MemoryHook when session.workspace_dir is unset |
MIN_CHAT_TURNS | Code constant | MemoryHook gate: needs len(chat_history) >= MIN_CHAT_TURNS * 2 |
MAX_FACTS_PER_SESSION | Code constant | Cap on heuristic facts per on_agent_end |
WorkspaceMemoryStore DB | Default path | ~/.agenticx/memory/main.sqlite (DEFAULT_WORKSPACE_MEMORY_DB) |
ContextCompactor thresholds | Code defaults | 20 messages / 48000 chars trigger; retain 8 messages |
1# ~/.agenticx/config.yaml (illustrative memory block)2memory:3 backend: sqlite4 path: ~/.agenticx/workspace