一个 Memory,一棵 scope 树:写的时候选层,读的时候往下找
本课目录
One Memory class, a filesystem-like scope tree, LLM-chosen placement on write, prefix-subtree recall on read — and how that differs from edges' code-directory memory.
本课唯一目标:读完后,你能讲清楚三件事——
- CrewAI 的 Unified Memory 是什么、有哪四种用法;
- 写路径(
remember→ 省略 scope 时由 LLM 给出suggested_scope→ consolidation)与读路径(recall→ scope 前缀子树 + 复合打分); - 它和你自己的 edges 目录记忆(代码目录树里的
.memory/、祖先并集读、就近层写)到底哪里像、哪里不像。
1. 一个类取代四种记忆
官方 Memory · Overview 第一句:CrewAI 提供 unified memory system——用一个 Memory 类,取代过去分开的 short-term、long-term、entity、external 四种记忆类型。
保存时由 LLM 分析内容(推断 scope、categories、importance);召回时做自适应深度(adaptive-depth)检索,按语义 + 时近 + 重要度的复合分排序。
四种用法
| 用法 | 怎么开 | 官方说它会做什么 |
|---|---|---|
| Standalone | memory = Memory() | 脚本 / notebook 里当知识库用,不需要 Agent 或 Crew |
| With Crews | Crew(..., memory=True) 或传入 Memory(...) 实例 | 每个 Task 之后自动从输出里抽取事实并存储;每个 Task 之前Agent 召回相关上下文注入 prompt;所有 Agent 共享 crew 的记忆(除非某 Agent 自带) |
| With Agents | Agent(..., memory=memory.scope("/agent/researcher")) | 给某个 Agent 一个私有子树视图;不设则用 crew 共享记忆 |
| With Flows | 每个 Flow 自带(自动创建默认 Memory()) | 在任意 flow 方法里用 self.remember() / self.recall() / self.extract_memories() |
from crewai import Memory
memory = Memory()
# Store -- the LLM infers scope, categories, and importance
memory.remember("We decided to use PostgreSQL for the user database.")
# Retrieve -- results ranked by composite score (semantic + recency + importance)
matches = memory.recall("What database did we choose?")
# Forget
memory.forget(scope="/project/old")
# Explore the self-organized scope tree
print(memory.tree())
2. scope:像文件系统的一棵路径树
What Scopes Are:记忆被组织成一棵层级 scope 树,“similar to a filesystem”,每个 scope 是 /、/project/alpha、/agent/researcher/findings 这样的路径。
关键是:这些路径是抽象命名空间(按实体 / 关注点命名,官方推荐 /{entity_type}/{identifier}、深度 2–3 层),和磁盘上的代码目录没有任何绑定(Best Practices for Scope Design)。
- MemoryScope:
memory.scope("/agent/researcher")把所有读写限制在一个子树里,可再.subscope("project-alpha")收窄; - MemorySlice:
memory.slice(scopes=[...], read_only=True)一次跨几个不相邻的分支召回;只读 slice 调remember会抛PermissionError(Memory Slices)。
3. 写路径:remember → suggested_scope → consolidation
remember(content, scope=None, categories=None, importance=None, ...):三个字段都可省;省了就交给 LLM(源码签名还有metadata、source、private等,见 unified_memory.py)。- scope inference:官方原话 “the LLM analyzes the content and the existing scope tree, then suggests the best placement. If no existing scope fits, it creates a new one.” 源码里这个字段叫
suggested_scope,描述为 “Best matching existing scope or new path”(analyze.py · MemoryAnalysis)。LLM 失败时退回默认 scope/、importance0.5(Failure Behavior)。 extract_memories(content):把一段原始文本(如 task 输出)拆成若干条独立陈述,避免存成“一大坨”;Crew 的自动抽取就是这么做的(LLM Analysis Layer)。- consolidation(合并整理):保存前查找相似旧记录,相似度超过
consolidation_threshold(默认0.85)时,LLM 对旧记录决定keep/update/delete,并决定新内容是否insert_new。
memory = Memory()
# LLM infers scope from content
memory.remember("We chose PostgreSQL for the user database.")
# -> might be placed under /project/decisions or /engineering/database
# You can also specify scope explicitly
memory.remember("Sprint velocity is 42 points", scope="/team/metrics")
4. 读路径:recall → 前缀子树 + 复合打分
recall(query, scope=None, categories=None, limit=10, depth="deep", ...)(unified_memory.py · recall)。三个要点:
| 要点 | 含义 | 出处 |
|---|---|---|
| scope = 前缀子树(向下) | “when you recall within a scope, you only search that branch of the tree”。源码 LanceDB 查询就是 scope LIKE '<prefix>%':给 /project,会搜到 /project/alpha/...,但不会往上搜 / 或兄弟分支 | What Scopes Are · lancedb_storage.py · search |
| recall depth | "shallow":直接向量检索 + 复合打分,无 LLM 调用,约 200ms;"deep"(默认):RecallFlow——查询分析、选 scope、并行检索、按置信度路由、必要时递归探索。短于 200 字符的查询即使 deep 也跳过 LLM 分析 | RecallFlow (Deep Recall) |
| Composite Scoring | semantic_weight·similarity + recency_weight·decay + importance_weight·importance;默认权重 0.5 / 0.3 / 0.2,半衰期 30 天 | Composite Scoring · Configuration Reference |
# Recall across all projects
memory.recall("API design decisions")
# Or within a specific project
memory.recall("API design", scope="/project/beta")
管理操作与存储
| 操作 | 作用 |
|---|---|
tree(path, max_depth) · info(path) | 打印 scope 树与记录数;某 scope 的 ScopeInfo(记录数、categories、最早/最新、子 scope) |
list_scopes(path) · list_records(scope=, limit=) · list_categories() | 直接子 scope;某 scope 下记录(新的在前);类别计数 |
forget(scope=, categories=, older_than=, record_ids=...) | 按条件删除,scope 同样按前缀子树匹配 |
reset(scope=None) | 清空全部或某子树 |
update(record_id, content=, scope=, ...) | 按 ID 改单条记录;传新 scope 即把这条记录移到另一层 |
存储:默认 LanceDB。官方 Storage Backend 写的是 ./.crewai/memory(或 $CREWAI_STORAGE_DIR/memory,或 storage="path");可实现 StorageBackend 协议换后端。
不管哪条路径,它都是一个中央库,所有 scope 都是库里一列字符串——不会在你的代码子目录里散落文件。
5. 对照:CrewAI Unified Memory vs edges 目录记忆
来源说明:本节的横向比较来自 2026-10-11 调研结论(你的 Agent Eval 助手的一手调研),不是 CrewAI 官方说法;CrewAI 一侧的事实以前 4 节的官方文档 / 源码为准。
5.1 edges 是怎么做的(回顾)
可写记忆放在代码目录树里,每层一个 .memory/(或 .edges/memory/);读时从当前目录向上取所有祖先层的并集(ancestor union);写时由 skill 挑最近的一层(nearest layer)。
| 维度 | CrewAI Unified Memory | edges 目录记忆 |
|---|---|---|
| scope 形状 | 层级路径树(/project/alpha/decisions) | 代码目录树,每层一个 .memory/ |
| 绑定 | 抽象命名空间,不绑代码目录 | 绑定真实代码目录 |
| 读方向 | 前缀子树,向下;多分支需显式 slice | 祖先并集,向上,按位置隐式计算 |
| 写时定层 | 显式 scope,或 LLM 给 suggested_scope(可新建路径) | skill 选最近层 |
| 存储 | 中央 LanceDB(一张表),不在仓库目录里 | 文件,散落在仓库各层目录里 |
| 管理操作 | 较全:tree/info/list_scopes/list_records/forget/reset,update(scope=) 逐条移层;另有 consolidation | 较弱:缺跨层 promote / demote / move |
5.2 调研结论要点(来自 2026-10-11 调研结论)
- 主流 coding agent(Claude Code / Cursor / Codex / Gemini / Copilot / Windsurf 等):读侧普遍有嵌套指令文件或路径 glob;但自动写入的记忆是固定的全局 / 仓库级“桶”,没有一个会把新记忆自动归档到某个代码子目录。
- 在“可写 + 路径 scope + 写时选层”这一点上,最接近的公开系统是 CrewAI Unified Memory;但它的路径是抽象命名空间、读是前缀子树向下、存储是中央 LanceDB。
- edges 仍较少见的组合:可写记忆在代码目录树里 + 祖先并集读 + 就近层写。CrewAI 证明了“分层 scope + 写时选层”可行,且管理 API 更完整;edges 的差异在于绑定代码目录 + 祖先并集,而不是“分层”本身。
- 次近但不同构:Anthropic Memory tool / Letta MemFS(agent 自管文件树);GitHub Copilot Memory(仓库桶 + 代码引用校验);Devin Knowledge(组织级文件夹 + promote)。
6. 讲给自己听(1 分钟)
不看上文,试着回答:Unified Memory 取代了哪几种旧记忆?Crew 开 memory=True 后,Task 前后各自动做什么?
remember() 不给 scope 时谁来决定放哪、能不能新建路径?recall(scope="/project") 会不会搜到 / 下的记录?
最后,用一句话说出 edges 和 CrewAI 的真正差别(提示:不是“分层”)。说得出来,就达成了本课目标。然后做小测。
7. 小测(检索练习)
CrewAI 的 Unified Memory 和旧版记忆的关系是?
- 在四种旧记忆之上再加一层统一的检索缓存
- 一个 Memory 类取代短期长期实体外部四种
- 只合并了短期和长期两种,实体记忆仍独立
- 仅供 Flow 使用,Crew 仍沿用旧的四种记忆
Memory class that replaces separate short-term, long-term, entity, and external memory types”。见 Memory · Overview。Crew 设置 memory=True 后,官方说会自动发生什么?
- 只在 kickoff 结束时把最终结果整体存成一条
- 每个 Agent 各自建一个互相隔离的私有记忆库
- Task 后抽取事实存入,Task 前召回并注入
- 只在 hierarchical 下由经理决定何时读写记忆
调用 remember(content) 且不传 scope,会怎样?
- LLM 看现有 scope 树给出位置,必要时新建路径
- 一律写进根 scope 斜杠,之后需要手动再移动
- 直接抛出异常,要求调用方必须显式指定 scope
- 写到调用代码所在的磁盘目录下的 .memory 里
suggested_scope。只有 LLM 分析失败时才退回 /。见 How Scope Inference Works · Failure Behavior。recall("...", scope="/project/beta") 的检索范围是?
- /project/beta 加上它所有祖先,一直到根斜杠
- 只匹配 scope 恰好等于 /project/beta 本身的记录
- 整棵树全部检索,scope 只用来给结果额外加一些权重
- /project/beta 及其下所有子 scope 的前缀子树
scope LIKE '/project/beta%'。祖先并集是 edges 的读法,不是 CrewAI 的。见 What Scopes Are · lancedb_storage.py。关于 recall 的 depth,哪句正确?
- 默认 shallow;deep 需显式开启且总会调用 LLM
- 默认 deep;shallow 是纯向量检索、不调用 LLM
- 两种都会调用 LLM,区别只在于返回结果数量的多少
- depth 决定向上回溯几层祖先 scope 来做合并
depth="shallow":“Direct vector search with composite scoring… no LLM calls”;depth="deep"(default)运行 RecallFlow,且短于 200 字符的查询会跳过 LLM 分析。见 RecallFlow (Deep Recall)。按 2026-10-11 调研结论,edges 与 CrewAI 的关键差异是?
- edges 有分层 scope,CrewAI 只有一个扁平桶
- edges 的管理 API 更全,支持跨层批量移动记忆
- edges 绑定代码目录、按祖先并集读,而非分层本身
- edges 用中央向量库,CrewAI 把文件写进仓库里
延伸阅读与下一步
- 一手资料(本课):CrewAI Docs · Memory——尤其 Hierarchical Scopes、Memory Consolidation、RecallFlow、Discovery 四节。
- 辅助:Flows · Memory in Flows · 源码 crewai/memory(
unified_memory.py、analyze.py、storage/lancedb_storage.py)。 - 上一课:第 3 课 · Process 与 allow_delegation。
- 速查表:术语表 / Glossary(本课新增 Unified Memory、scope、suggested_scope、recall depth、consolidation)。
- 可选加深:Memory Slices、Source and Privacy(
source/private)——本课未展开。
有不清楚的地方随时问我(你的老师)。