安全公告 — 恶意 litellm 版本 1.82.7 与 1.82.8 已从 PyPI 移除(存在 API 密钥外泄风险)。请卸载、轮换已暴露凭据,并升级至安全版本(如 1.82.9+)。运行 pip show litellm 以确认。 PyPI · README

记忆

AgenticX 记忆系统。

AgenticX 中的记忆

概述

智能体需要稳定的身份、对过往工作的回忆,以及有界的上下文窗口。AgenticX 结合了 文件型工作区记忆会话 scratchpad、每轮结束后的 自动事实抽取、注入 Meta-Agent 系统提示的 混合检索、可选的 Mem0 后端,以及长对话上的 LLM 辅助上下文压缩

这些机制共同构成近似分层的记忆栈:必须始终成立的内容(身份)、最近发生的事(情节)、可泛化的知识(语义)、本轮模型可见的内容(工作集)、跨会话保留的内容(长期文件与存储),以及落在用户磁盘工作区内的范围化记忆。


记忆层级(六层模型)

下表将经典认知式层级映射到 AgenticX 的具体实现。各层为 概念性 划分;多项能力在实现上会有重叠。

LayerRoleAgenticX realization
Core memoryStable role, name, non-negotiable factsIDENTITY.md, SOUL.md, avatar/session system prompts, Meta-Agent identity blocks
Episodic memoryWhat was said and done in conversationschat_history / persisted messages.json, tool traces in history
Semantic memoryReusable knowledge, not tied to one chatCurated MEMORY.md, optional Mem0 / knowledge components, indexed chunks in WorkspaceMemoryStore
Short-term / working memoryScratch space for the current taskPer-session scratchpad dict, scratchpad_write / scratchpad_read tools, recent message window
Long-term memoryCross-session persistenceMEMORY.md (manual + auto-append), SQLite session store for scratchpad, optional Mem0
Workspace memoryProject- and user-scoped files under ~/.agenticx/workspaceUSER.md, daily memory/<YYYY-MM-DD>.md, directory layout per avatar/project

!!! note "索引与原始文件"

混合搜索(WorkspaceMemoryStore)会索引 MEMORY.mdIDENTITY.mdUSER.mdSOUL.md 以及工作区下全部 memory/*.md。保持这些文件简洁可提升召回质量。


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 摘要。
python
1# Reference constants (agenticx/runtime/hooks/memory_hook.py)
2MIN_CHAT_TURNS = 3 # requires len(chat_history) >= MIN_CHAT_TURNS * 2
3MAX_FACTS_PER_SESSION = 8

!!! warning "语言启发式"

事实模式针对 中文 请求关键词及中英文完成标记。其他语言的对话可能抽取较少或为空,需扩展启发式后才改善。


工作区记忆

目录结构(`~/.agenticx/workspace/`)

PathPurpose
IDENTITY.mdWho the agent is; stable persona
USER.mdUser profile, preferences
SOUL.mdDeeper style / values / tone
MEMORY.mdLong-form durable notes; receives optional auto-extracted sections
memory/<YYYY-MM-DD>.mdDaily session-fact log from MemoryHook

分身/群聊等额外会话产物可并存;搜索索引 明确拉取四个根 markdown 文件及 memory/*.md

自动召回:`_build_memory_recall_context`

定义于 agenticx/runtime/prompts/meta_agent.py。构建 Meta-Agent 系统提示时:

  1. 最近五条 用户消息收集文本(每条最多 200 字符)。
  2. 构建查询字符串(最多 500 字符)。
  3. 调用 WorkspaceMemoryStore.search_sync(..., limit=5, mode="hybrid")
  4. 注入 `## 相关历史记忆(自动召回)` 节,片段总量约 500 字符上限。

若无用户消息或无命中,则省略该节。

!!! tip "召回质量"

大规模编辑 markdown 后运行或调度 WorkspaceMemoryStore.index_workspace_sync(workspace_dir),以便 FTS 与混合排序看到最新内容。


Mem0 集成

Mem0 为 可选。通过附带 memory 依赖的 extra 安装:

bash
1pip install "agenticx[memory]"

运行时,依赖就绪时 `agenticx.memory` 暴露 `Mem0` / 异步变体;`agenticx/integrations/mem0/` 下的集成支持多种向量存储与配置。当你需要 托管的长期语义记忆(add/search API,托管或本地)而非或辅以基于文件的 MEMORY.md 时使用 Mem0。

!!! note "与 MemoryHook 分离"

MemoryHook 在工作区下写 markdown。Mem0 是独立数据平面;若既要文件日志又要向量搜索,可同时接入。


会话 scratchpad

每个 `StudioSession` 携带通过 SQLite 持久化的 `scratchpad` 字典(agenticx/memory/session_store.py)。除 scratchpad_write 的用户/智能体键外,运行时使用保留模式:

Key patternPurpose
subagent_result::<id>Summary text after a subagent / delegation completes
delegation_result::<id>Same pipeline writes delegation outcomes for Meta-Agent follow-up
session_factsIncremental 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

ParameterDefaultBehavior
threshold_messages20Compact if message count exceeds this
threshold_chars48000Or if sum of content string lengths exceeds this
retain_recent_messages8Oldest portion is summarized; these tail messages stay verbatim

流程:

  1. 拆分为 前缀(待压缩)与 后缀(保留)。
  2. 用中文压缩指令调用运行时 LLM(temperature 0max_tokens 400)。
  3. 用带 `[compacted]` 前缀的单一 system 消息与摘要替换前缀。
  4. 失败时回退为拼接的短片段。

强制下限:threshold_messages >= 8threshold_chars >= 4000retain_recent_messages >= 4

!!! note "配置面"

默认值固定于 AgentRuntime.__init__ContextCompactor(llm),无 YAML 覆盖)。自定义部署可按需构造带预配置 ContextCompactorAgentRuntime


记忆相关配置

ItemWhereDescription
memory.backend~/.agenticx/config.yamlDeclared in docs for pluggable memory backends (sqlite, redis, postgresql, etc.)
memory.path~/.agenticx/config.yamlWorkspace root for memory features
AGX_WORKSPACE_ROOTEnvironmentFallback workspace directory for MemoryHook when session.workspace_dir is unset
MIN_CHAT_TURNSCode constantMemoryHook gate: needs len(chat_history) >= MIN_CHAT_TURNS * 2
MAX_FACTS_PER_SESSIONCode constantCap on heuristic facts per on_agent_end
WorkspaceMemoryStore DBDefault path~/.agenticx/memory/main.sqlite (DEFAULT_WORKSPACE_MEMORY_DB)
ContextCompactor thresholdsCode defaults20 messages / 48000 chars trigger; retain 8 messages
yaml
1# ~/.agenticx/config.yaml (illustrative memory block)
2memory:
3 backend: sqlite
4 path: ~/.agenticx/workspace

另见

  • [配置](/docs/getting-started/configuration) — 全局 config.yaml 与环境变量
  • 架构 — 运行时高层概览