Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 9 / labs/m09_*

Memory记忆

What the agent keeps about a user, and how it gets back into the prompt.智能体为用户保留了什么,以及这些内容如何回到提示词里。

What it is and why it exists它是什么,为什么需要它

What是什么

Memory is durable information written after conversations and read back in later ones. This module builds per-user facts that go into every prompt, a searchable history of past turns, and the background pipeline that writes both.记忆是在对话之后写入、在以后的对话中读回的持久信息。本模块搭建三样东西:进入每次提示词的用户事实、可检索的历史对话,以及负责写入这两者的后台流程。

Why为什么

Without memory every conversation starts cold. With careless memory the agent leaks one user's context into another's, or delays every answer while it takes notes.没有记忆,每次对话都从零开始。记忆做得不仔细,智能体会把一个用户的上下文泄露给另一个用户,或者为了记笔记而拖慢每一次回答。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

  • Harness engineeringHarness 工程Memory is read at prompt composition and written after the response. Both are harness stages.记忆在组装提示词时读取,在响应之后写入。这两处都是 Harness 的阶段。Build out of order不按顺序搭建 Stand in with:可用以下替代: A JSON file per user, read at start and appended at end.每个用户一个 JSON 文件,开始时读取,结束时追加。
  • State and storage状态与存储Memory is durable state with concurrent writers: live chats and background jobs. It needs the tables and the connection settings from the state module.记忆是有并发写入方的持久状态:实时对话和后台任务都会写。它需要状态模块里的表和连接设置。Build out of order不按顺序搭建 Stand in with:可用以下替代: A single-writer file store, for one user only.一个单写入方的文件存储,只服务一个用户。

Unlocks解锁

  • Self-evolving agents自进化智能体Learned rules are memory that belongs to the agent. They use the same store and the same status discipline.学到的规则是属于智能体自身的记忆。它们使用同一个存储和同样的状态管理方式。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/memory_store.pyPer-partition reads and writes.按分区读写。
apps/agent-server/memory_pipeline.pyPost-response extraction, run in the background.响应之后在后台运行的信息提取。
apps/agent-server/conversation_index.pySearchable index of past conversations.历史对话的可检索索引。
apps/agent-server/tools/conversation_recall.pyRecall as a tool the agent can call.作为工具供智能体调用的回忆功能。

Process map流程图

Memory around one request一次请求前后的记忆流程

  1. 1
    Request with a partition带分区的请求The partition comes from the authenticated key or session, never from the model.分区来自已认证的密钥或会话,绝不来自模型。
  2. 2
    Briefing摘要A few fact lines for this partition are added to the system prompt.该分区的几行事实被加进系统提示词。
  3. 3
    Agent runs智能体运行It may call the recall tool to search earlier threads.它可以调用回忆工具检索之前的会话。
  4. 4
    Answer returned返回回答The user has the answer before anything is written.在任何写入发生之前,用户已经拿到回答。
  5. 5
    Record记录A background task stores both turns and extracts durable facts.后台任务保存这两轮对话,并提取可长期保留的事实。

Build steps搭建步骤

Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。

  1. 1Fix the partition rule确定分区规则
  2. 2Store facts and build the briefing保存事实并生成摘要
  3. 3Write the record pipeline, after the answer编写记录流程,放在回答之后
  4. 4Add recall over past turns加入对历史对话的回忆
  5. 5Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性
  6. 6Test the three boundaries of recall测试回忆的三条边界
  7. 7Prove a memory failure cannot break an answer证明记忆故障不会破坏回答
  8. 8Offer recall as a tool bound to one user把回忆做成绑定到单个用户的工具
01Fix the partition rule确定分区规则
Why this step is here为什么这一步排在这里Decide where the partition comes from before writing any memory code. Every function takes it as its first argument, and retrofitting it is how leaks happen.在写任何记忆代码之前,先确定分区从哪里来。每个函数都把它作为第一个参数,事后再补正是泄露的来源。
Uses用到

Do this操作

  1. Derive the partition from the authenticated caller: the key's app, or a signed user id.从已认证的调用方得出分区:密钥对应的应用,或一个签名的用户 ID。
  2. Never accept a partition from the model or from tool arguments.绝不接受模型或工具参数提供的分区。
  3. Write it as the first parameter of every memory function.把它写成每个记忆函数的第一个参数。
You are done when完成标志No memory function can be called without a partition.没有任何记忆函数可以在不带分区的情况下被调用。
Produces产出A rule: partition comes from authentication.一条规则:分区来自身份认证。
02Store facts and build the briefing保存事实并生成摘要
Why this step is here为什么这一步排在这里Facts are the simplest memory and the only kind that goes into every prompt, so they are built first and kept small.事实是最简单的记忆,也是唯一会进入每次提示词的那种,所以先做它,并保持精简。

Do this操作

  1. `remember()` upserts one key for one partition.`remember()` 为某个分区更新或插入一个键。
  2. `briefing()` returns a few lines, newest first, with a hard limit.`briefing()` 返回几行内容,新的在前,并有硬性上限。
labs/m09_memory/memory.py · facts
def remember(self, partition: str, key: str, value: str) -> None:
    with self.lock:
        self.db.execute("INSERT INTO mem_facts VALUES (?,?,?,?) ON CONFLICT(partition, key) "
                        "DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
                        (partition, key, value, time.time()))
        self.db.commit()

def briefing(self, partition: str, limit: int = 8) -> str:
    """A few lines for the system prompt. Short on purpose: it is charged on every turn."""
    with self.lock:
        rows = self.db.execute("SELECT key, value FROM mem_facts WHERE partition=? ORDER BY updated_at DESC LIMIT ?",
                               (partition, limit)).fetchall()
    return "\n".join(f"- {k}: {v}" for k, v in rows)
You are done when完成标志A second `remember()` for the same key replaces the value.对同一个键再次调用 `remember()` 会替换原值。
Produces产出`remember()` and `briefing()`.`remember()` 和 `briefing()`。
03Write the record pipeline, after the answer编写记录流程,放在回答之后
Why this step is here为什么这一步排在这里It needs the fact store. It runs after the answer because the user is waiting for the answer and no one is waiting for the notes.它依赖事实存储。它在回答之后运行,因为用户等的是回答,没有人在等笔记。

Do this操作

  1. `record()` stores the user turn and the assistant turn, then extracts facts from what the user said.`record()` 保存用户和助手各一轮对话,然后从用户说的话里提取事实。
  2. `record_async()` runs it in a background thread and catches every exception.`record_async()` 在后台线程里执行它,并捕获所有异常。
  3. The lab extracts with patterns to stay deterministic. A real system asks a small model what is worth keeping.为保持确定性,lab 用正则模式提取。真实系统会让一个小模型判断什么值得保留。
labs/m09_memory/memory.py · pipeline
def record(self, partition: str, thread: str, user_text: str, answer: str) -> None:
    """Store the exchange and extract durable facts from what the user said."""
    with self.lock:
        now = time.time()
        self.db.executemany("INSERT INTO conv_turns (partition, thread, role, content, ts) VALUES (?,?,?,?,?)",
                            [(partition, thread, "user", user_text, now), (partition, thread, "assistant", answer, now)])
        self.db.commit()
    for key, pattern in FACT_PATTERNS:
        m = pattern.search(user_text)
        if m:
            self.remember(partition, key, m.group(1).strip())

def record_async(self, partition: str, thread: str, user_text: str, answer: str) -> None:
    """Fire and forget. A failure here is logged and swallowed: the user already has the answer."""
    def work():
        try:
            self.record(partition, thread, user_text, answer)
        except Exception as e:  # noqa: BLE001
            print("memory write failed (response unaffected):", e)
    t = threading.Thread(target=work, daemon=True)
    t.start()
    self.pending.append(t)

def flush(self) -> None:
    for t in self.pending:
        t.join()
    self.pending.clear()
You are done when完成标志`record_async()` returns immediately.`record_async()` 立即返回。
Produces产出`record_async()`: what the harness calls after responding.`record_async()`:Harness 在响应之后调用它。
04Add recall over past turns加入对历史对话的回忆
Why this step is here为什么这一步排在这里Recall needs stored turns, so it follows the pipeline. History is searched on demand because putting it all in the prompt costs every turn.回忆需要已保存的对话,所以排在记录流程之后。历史按需检索,因为全放进提示词的话每一轮都要付费。

Do this操作

  1. Search this partition's turns by similarity to the query.按与查询的相似度检索该分区的对话。
  2. Skip the current thread. It is already in context.跳过当前会话。它已经在上下文里了。
  3. Return nothing below a similarity floor. A weak match presented as memory is worse than none.相似度低于门槛就什么都不返回。把弱匹配当成记忆,比没有记忆更糟。
labs/m09_memory/memory.py · recall
def recall(self, partition: str, query: str, exclude_thread: Optional[str] = None, top_k: int = 2) -> list:
    """Search this user's past turns. The current thread is skipped: it is already in context."""
    q = llm.embed(query)
    with self.lock:
        rows = self.db.execute("SELECT thread, role, content FROM conv_turns WHERE partition=?", (partition,)).fetchall()
    scored = [(llm.cosine(q, llm.embed(content)), thread, role, content)
              for thread, role, content in rows if thread != exclude_thread]
    scored.sort(reverse=True)
    return [{"score": round(s, 2), "thread": t, "role": r, "content": c} for s, t, r, c in scored[:top_k] if s >= RECALL_FLOOR]
You are done when完成标志An unrelated query returns an empty list.不相关的查询返回空列表。
Produces产出`recall()`: this user's earlier turns that match.`recall()`:该用户之前与查询匹配的对话。
05Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性
Why this step is here为什么这一步排在这里This joins memory to the loop. Isolation is tested here, with two users, before any real user exists.这一步把记忆接到循环上。隔离性就在这里用两个用户测试,赶在任何真实用户出现之前。

Do this操作

  1. Pass the memory object as the `memory` argument of the agent.把记忆对象作为智能体的 `memory` 参数传入。
  2. Run two users through the agent. Each states a cost center.让两个用户分别通过智能体。各自说出一个成本中心。
  3. Check each briefing, then check that one user's fact is absent from the other's prompt.检查各自的摘要,再确认一个用户的事实没有出现在另一个用户的提示词里。
run
python3 -m labs.m09_memory.demo
Recorded output / 记录的输出 · m09.demo
1 dana briefing : - name: Dana - home_city: Boston - cost_center: CC-200
2 eli briefing  : - cost_center: CC-100
3 in dana prompt: True | in eli prompt: False
You are done when完成标志Line 3 reads True for the owner's prompt and False for the other user's.第 3 行显示:所有者的提示词为 True,另一个用户的为 False。
Produces产出An agent that briefs itself per user and records after answering.一个按用户生成摘要、在回答之后做记录的智能体。
Feeds供给
06Test the three boundaries of recall测试回忆的三条边界
Why this step is here为什么这一步排在这里Each boundary is a line of output. Test them now so a later change that breaks one is caught by the same demo.每条边界对应一行输出。现在就测好,以后哪次改动破坏了其中一条,同一个 demo 就能发现。

Do this操作

  1. Owner recalls an earlier thread: a hit.所有者回忆之前的会话:有命中。
  2. Another user runs the same query: nothing.另一个用户执行同样的查询:没有结果。
  3. Owner queries from the same thread: nothing, it is already in context.所有者在同一个会话里查询:没有结果,因为已在上下文里。
  4. Owner queries something unrelated: nothing.所有者查询不相关的内容:没有结果。
Recorded output / 记录的输出 · m09.demo
4 recall (dana) : mon user -> What is the nightly lodging cap? ... score 0.51
5 recall (eli)  : []
6 same thread   : [] (skipped: already in context)
7 unrelated     : []
You are done when完成标志Lines 5, 6, and 7 are empty lists.第 5、6、7 行都是空列表。
Produces产出Four checks that double as a regression test.四项检查,同时可作为回归测试。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
07Prove a memory failure cannot break an answer证明记忆故障不会破坏回答
Why this step is here为什么这一步排在这里The pipeline claims to be fire and forget. Test the claim by making it fail.记录流程声称自己“发出即不管”。通过让它故意失败来验证这个说法。
Uses用到

Do this操作

  1. Replace `record` with a function that raises.把 `record` 换成一个会抛异常的函数。
  2. Run a request and read the answer.发一个请求,查看回答。
Recorded output / 记录的输出 · m09.demo
memory write failed (response unaffected): disk full
8 answer despite failed write: Lodging is reimbursed at actual cost up to 220 dol ...
You are done when完成标志The failure is printed, and the answer is returned unchanged.失败信息被打印出来,回答原样返回。
Produces产出Evidence that memory is best effort and never load-bearing.证明记忆是尽力而为的附加能力,系统不依赖它才能正常工作。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
08Offer recall as a tool bound to one user把回忆做成绑定到单个用户的工具
Why this step is here为什么这一步排在这里Last, because it combines recall with the tool registry. The partition is bound when the tool is created, so the model has no argument through which to ask for another user's history.放在最后,因为它把回忆和工具注册表结合起来。分区在创建工具时就绑定了,所以模型没有任何参数可以用来索取别人的历史。

Do this操作

  1. Create the tool function per request with the partition and thread already fixed.每个请求创建一次工具函数,分区和会话在创建时就固定。
  2. Expose one argument: the query.只暴露一个参数:查询内容。
  3. Return a diagnostic when nothing matches.没有匹配时返回诊断信息。
labs/m09_memory/tool_check.py · bind
def tools_for_request(base: Registry, memory: Memory, partition: str, thread: str) -> Registry:
    """A registry for one request: the shared tools plus a recall tool bound to this caller."""
    reg = Registry()
    reg.tools.update(base.tools)
    fn = recall_tool(memory, partition=partition, thread=thread)
    reg.tool("Search this user's earlier conversations. Use when they refer to something said before.")(fn)
    return reg
run
python3 -m labs.m09_memory.tool_check
Recorded output / 记录的输出 · m09.tool
1 schema properties: ['query']
2 dana's tool      : [('mon', 'What is the nightly lodging cap?')]
3 asks for eli     : refused, got an unexpected keyword argument 'partition'
4 nothing similar  : {"results": [], "diagnostic": "nothing similar in earlier conversations"}
5 eli's tool, same query: no results
You are done when完成标志The schema has one property, `query`. A call that adds a `partition` argument is refused, and the same query through another user's tool returns nothing.schema 只有一个属性 `query`。多传一个 `partition` 参数的调用会被拒绝;同样的查询通过另一个用户的工具返回空。
Produces产出A recall tool with no way to cross users.一个无法跨用户的回忆工具。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

2026-10

Recall returned the conversation it was in回忆返回了当前所在的对话

What happened发生了什么
A recall search matched turns from the current thread, which were already in context.回忆检索匹配到了当前会话里的内容,而这些本来就在上下文中。
Fix修复
Skip the current thread.跳过当前会话。
Lesson教训
Memory should add what the context lacks.记忆应该补充上下文里没有的东西。
2026-10

A weak match presented as a memory把弱匹配当成了记忆

What happened发生了什么
With no floor, recall always returned its closest turn, however unrelated.没有设门槛时,回忆总会返回最接近的那一轮,哪怕毫不相关。
Fix修复
A similarity floor chosen from an eval: the lowest true hit scored 0.55 and the highest unrelated match 0.24, so the floor was set between them.根据评估设定相似度门槛:最低的真实命中得分 0.55,最高的无关匹配 0.24,门槛设在两者之间。
Lesson教训
Pick thresholds from measured gaps.根据测得的分数差距来选阈值。
2026-10

A memory briefing that could fail a request记忆摘要可能导致请求失败

What happened发生了什么
An error while building the briefing propagated and the request failed.生成摘要时出错,错误向上传播,导致请求失败。
Fix修复
Catch errors in the briefing and continue without it.捕获生成摘要时的错误,没有摘要也继续执行。
Lesson教训
Anything optional must be unable to break what is required.任何可选的东西,都不能有能力破坏必需的东西。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksAgent Bricks lists memory as a platform component. For your own schema use Lakebase or Delta tables keyed by user, read in your agent code.Agent Bricks 把记忆列为平台组件之一。如果要用自己的表结构,可以使用以用户为键的 Lakebase 或 Delta 表,在智能体代码中读取。
IBM watsonxOrchestrate keeps conversation context. Long-term memory is a store you connect and read through a tool.Orchestrate 保留对话上下文。长期记忆是你接入的存储,通过工具读取。
CodexPersistent instructions live in AGENTS.md. Memories are files the agent is told to read and update.持久指令放在 AGENTS.md 里。记忆是让智能体去读取和更新的文件。
CursorRules and memory features hold persistent preferences. Project facts belong in repo files.规则和记忆功能保存持久偏好。项目相关的事实应放在仓库文件里。
Claude Code / Agent SDKA project instruction file plus memory files and tools. The pattern is the same: write after, read at start, scope by project.项目指令文件加上记忆文件和工具。模式相同:事后写入、开始时读取、按项目限定范围。
Another machineA table with a partition column and a background writer. Portable.一张带分区列的表加一个后台写入任务。可移植。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

Why is the memory write fire and forget?为什么记忆写入要“发出即不管”?
A strong answer参考答案The user is waiting on the answer. A slow or failed write should cost nothing in latency or correctness, so it runs after the response and swallows its own errors.用户在等的是回答。写入慢或失败都不应影响延迟和正确性,所以它在响应之后运行,并自行吞掉错误。
What stops one user's memory from reaching another?是什么阻止一个用户的记忆到达另一个用户?
A strong answer参考答案A partition taken from authentication and applied in the store on every read and write. The recall tool has no partition argument at all.分区取自身份认证,并在存储层的每次读写中强制使用。回忆工具根本没有分区参数。
Why are facts in every prompt and turns only on demand?为什么事实进入每次提示词,而对话历史只按需读取?
A strong answer参考答案Facts are few and short. History grows without bound, and prompt tokens are charged on every turn. Searching it when needed costs one tool call.事实数量少、内容短。历史会无限增长,而提示词 token 每一轮都要计费。需要时再检索只花一次工具调用。
In what order did you build memory, and what does each step need from the one before?你按什么顺序搭建记忆?每一步需要上一步的什么?
A strong answer参考答案Partition rule, facts, record pipeline, recall, harness plug, boundary tests, failure test, recall tool. Facts need the partition, the pipeline needs facts, recall needs stored turns, and the tests need all of it attached to the agent.分区规则、事实、记录流程、回忆、接入 Harness、边界测试、故障测试、回忆工具。事实需要分区,记录流程需要事实,回忆需要已保存的对话,而测试需要这一切都已接到智能体上。

Terms术语

Briefing摘要(Briefing)The few memory lines added to the system prompt for this user.为该用户加进系统提示词的几行记忆。
Recall回忆(Recall)Searching earlier conversation turns for this user.检索该用户之前的对话内容。
Fire and forget发出即不管Started in the background, with no one waiting for the result.在后台启动,没有任何环节等待它的结果。

From the live build来自实时构建

Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问