CrewAI 学习空间 · 第 4 课 · 约 10 分钟 · 概念为主;附官方短片段体感(非作业) · 一手资料:官方 Memory(辅以 Flows · Memory in Flows、Crews,并对照 源码 crewai/memory;2026-10-12 抓取) · ← 第 3 课

一个 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.

本课唯一目标:读完后,你能讲清楚三件事——

  1. CrewAI 的 Unified Memory 是什么、有哪四种用法;
  2. 写路径(remember → 省略 scope 时由 LLM 给出 suggested_scope → consolidation)与读路径(recall → scope 前缀子树 + 复合打分);
  3. 它和你自己的 edges 目录记忆(代码目录树里的 .memory/、祖先并集读、就近层写)到底哪里像、哪里不像。

前 3 课讲的是“谁来干活”。本课讲“干完以后记住什么、下次怎么找回来”。

1. 一个类取代四种记忆

官方 Memory · Overview 第一句:CrewAI 提供 unified memory system——用一个 Memory 类,取代过去分开的 short-term、long-term、entity、external 四种记忆类型。 保存时由 LLM 分析内容(推断 scope、categories、importance);召回时做自适应深度(adaptive-depth)检索,按语义 + 时近 + 重要度的复合分排序。

四种用法

用法怎么开官方说它会做什么
Standalonememory = Memory()脚本 / notebook 里当知识库用,不需要 Agent 或 Crew
With CrewsCrew(..., memory=True) 或传入 Memory(...) 实例每个 Task 之后自动从输出里抽取事实并存储;每个 Task 之前Agent 召回相关上下文注入 prompt;所有 Agent 共享 crew 的记忆(除非某 Agent 自带)
With AgentsAgent(..., memory=memory.scope("/agent/researcher"))给某个 Agent 一个私有子树视图;不设则用 crew 共享记忆
With Flows每个 Flow 自带(自动创建默认 Memory())在任意 flow 方法里用 self.remember() / self.recall() / self.extract_memories()

出处:Four Ways to Use Memory · With Crews · Memory in Flows。JSONC 写法里 crew.jsonc 也支持 "memory": true(Crews · JSONC)。

官方 Quick Start — 摘自 Memory · Quick Start(节选)。
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)。

3. 写路径:remember → suggested_scope → consolidation

CrewAI 写路径 remember(content) 进入;若未给 scope,LLM 读取现有 scope 列表并给出 suggested_scope,可能是新路径;随后与相似记录比较,相似度超过 0.85 时由 LLM 决定 keep、update、delete 和是否 insert_new;最后写入中央 LanceDB。 remember() content, scope?, categories?, importance? 省略 scope 时 LLM 读现有 scope 列表 → suggested_scope 没合适的就新建路径 (写时选层) consolidation 相似度 > 0.85 时 LLM 对旧记录: keep|update|delete + insert_new? LanceDB 中央存储 一张表 长文本可先 extract_memories() 拆成原子事实,再逐条 remember()
图 1 写路径。出处:How Scope Inference Works · Memory Consolidation · Storage Backend。
  1. remember(content, scope=None, categories=None, importance=None, ...):三个字段都可省;省了就交给 LLM(源码签名还有 metadata、source、private 等,见 unified_memory.py)。
  2. 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 /、importance 0.5(Failure Behavior)。
  3. extract_memories(content):把一段原始文本(如 task 输出)拆成若干条独立陈述,避免存成“一大坨”;Crew 的自动抽取就是这么做的(LLM Analysis Layer)。
  4. consolidation(合并整理):保存前查找相似旧记录,相似度超过 consolidation_threshold(默认 0.85)时,LLM 对旧记录决定 keep / update / delete,并决定新内容是否 insert_new。
官方 省略 scope 由 LLM 推断,或显式给出 — 摘自 How Scope Inference Works。
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 Scoringsemantic_weight·similarity + recency_weight·decay + importance_weight·importance;默认权重 0.5 / 0.3 / 0.2,半衰期 30 天Composite Scoring · Configuration Reference
官方 跨项目召回 vs 限定在一个分支 — 摘自 Use Case Examples。
# 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 即把这条记录移到另一层

出处:Discovery · Troubleshooting(reset)· 源码 unified_memory.py(forget/update 签名;update 官方 Memory 页未单独介绍)。注意 update 是逐条移动,没有“整棵子树搬家”的批量 API。

存储:默认 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 recall(scope="/project"),从 /project 向下覆盖 /project/alpha 和 /project/beta,不包含根和兄弟 /agent。右:edges 在 repo/pkg/api 工作时,读取 api、pkg、repo 三层 .memory 的并集,方向向上;写入时选最近层 api/.memory。 CrewAI:前缀子树,向下 / /project /agent /project/alpha /project/beta recall(q, scope="/project");抽象命名空间 edges:祖先并集,向上 repo/.memory pkg/.memory api/.memory ← 写 读 在 repo/pkg/api 工作;绑定真实代码目录 写:skill 选最近层
图 2 读方向相反:CrewAI 给一个 scope,往下覆盖它的子树;edges 从当前目录往上把祖先层并起来。(edges 侧为教学示意,目录名虚构。)
维度CrewAI Unified Memoryedges 目录记忆
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 调研结论)

6. 讲给自己听(1 分钟)

不看上文,试着回答:Unified Memory 取代了哪几种旧记忆?Crew 开 memory=True 后,Task 前后各自动做什么? remember() 不给 scope 时谁来决定放哪、能不能新建路径?recall(scope="/project") 会不会搜到 / 下的记录? 最后,用一句话说出 edges 和 CrewAI 的真正差别(提示:不是“分层”)。说得出来,就达成了本课目标。然后做小测。

7. 小测(检索练习)

点击选项即判定,每题只能作答一次;选项顺序随机。“重做”可清空重来。一手资料:Memory。

CrewAI 的 Unified Memory 和旧版记忆的关系是?

  1. 在四种旧记忆之上再加一层统一的检索缓存
  2. 一个 Memory 类取代短期长期实体外部四种
  3. 只合并了短期和长期两种,实体记忆仍独立
  4. 仅供 Flow 使用,Crew 仍沿用旧的四种记忆
“a single Memory class that replaces separate short-term, long-term, entity, and external memory types”。见 Memory · Overview。

Crew 设置 memory=True 后,官方说会自动发生什么?

  1. 只在 kickoff 结束时把最终结果整体存成一条
  2. 每个 Agent 各自建一个互相隔离的私有记忆库
  3. Task 后抽取事实存入,Task 前召回并注入
  4. 只在 hierarchical 下由经理决定何时读写记忆
“After each task, the crew automatically extracts discrete facts… Before each task, the agent recalls relevant context… and injects it into the task prompt.” 所有 Agent 默认共享 crew 记忆。见 With Crews。

调用 remember(content) 且不传 scope,会怎样?

  1. LLM 看现有 scope 树给出位置,必要时新建路径
  2. 一律写进根 scope 斜杠,之后需要手动再移动
  3. 直接抛出异常,要求调用方必须显式指定 scope
  4. 写到调用代码所在的磁盘目录下的 .memory 里
“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。只有 LLM 分析失败时才退回 /。见 How Scope Inference Works · Failure Behavior。

recall("...", scope="/project/beta") 的检索范围是?

  1. /project/beta 加上它所有祖先,一直到根斜杠
  2. 只匹配 scope 恰好等于 /project/beta 本身的记录
  3. 整棵树全部检索,scope 只用来给结果额外加一些权重
  4. /project/beta 及其下所有子 scope 的前缀子树
“when you recall within a scope, you only search that branch of the tree”;源码过滤条件为 scope LIKE '/project/beta%'。祖先并集是 edges 的读法,不是 CrewAI 的。见 What Scopes Are · lancedb_storage.py。

关于 recall 的 depth,哪句正确?

  1. 默认 shallow;deep 需显式开启且总会调用 LLM
  2. 默认 deep;shallow 是纯向量检索、不调用 LLM
  3. 两种都会调用 LLM,区别只在于返回结果数量的多少
  4. 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 的关键差异是?

  1. edges 有分层 scope,CrewAI 只有一个扁平桶
  2. edges 的管理 API 更全,支持跨层批量移动记忆
  3. edges 绑定代码目录、按祖先并集读,而非分层本身
  4. edges 用中央向量库,CrewAI 把文件写进仓库里
CrewAI 已证明“分层 scope + 写时选层”可行,且管理 API 更完整;edges 的差别在绑定代码目录 + 祖先并集读(+ 就近层写),edges 反而缺 promote / demote / move。存储方向也正好相反。见本课第 5 节(来自 2026-10-11 调研结论)。

延伸阅读与下一步

有不清楚的地方随时问我(你的老师)。