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工作原理
- Every read and write takes a partition, usually the user id. The partition is the boundary.每次读写都带一个分区,通常是用户 ID。分区就是边界。
- Facts are small key and value notes. A short briefing of them is added to the system prompt.事实是简短的键值记录。它们的简短摘要会加进系统提示词。
- Turns are the full history. They are searched on demand and are not placed in every prompt.对话轮次是完整的历史。按需检索,不会放进每次提示词。
- Writing happens after the answer, in the background. A failure there never reaches the user.写入发生在回答之后,在后台进行。即使失败,用户也不会受影响。
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.py | Per-partition reads and writes.按分区读写。 |
| apps/agent-server/memory_pipeline.py | Post-response extraction, run in the background.响应之后在后台运行的信息提取。 |
| apps/agent-server/conversation_index.py | Searchable index of past conversations.历史对话的可检索索引。 |
| apps/agent-server/tools/conversation_recall.py | Recall as a tool the agent can call.作为工具供智能体调用的回忆功能。 |
Process map流程图
Memory around one request一次请求前后的记忆流程
- 1Request with a partition带分区的请求The partition comes from the authenticated key or session, never from the model.分区来自已认证的密钥或会话,绝不来自模型。
- 2Briefing摘要A few fact lines for this partition are added to the system prompt.该分区的几行事实被加进系统提示词。
- 3Agent runs智能体运行It may call the recall tool to search earlier threads.它可以调用回忆工具检索之前的会话。
- 4Answer returned返回回答The user has the answer before anything is written.在任何写入发生之前,用户已经拿到回答。
- 5Record记录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 实际运行时打印的内容。
- 1Fix the partition rule确定分区规则
- 2Store facts and build the briefing保存事实并生成摘要
- 3Write the record pipeline, after the answer编写记录流程,放在回答之后
- 4Add recall over past turns加入对历史对话的回忆
- 5Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性
- 6Test the three boundaries of recall测试回忆的三条边界
- 7Prove a memory failure cannot break an answer证明记忆故障不会破坏回答
- 8Offer recall as a tool bound to one user把回忆做成绑定到单个用户的工具
01Fix the partition rule确定分区规则
- an authenticated identity to derive the partition from用于推导分区的已认证身份 ← API and gatewayAPI 与网关 2: Build the key store建立密钥库
Do this操作
- Derive the partition from the authenticated caller: the key's app, or a signed user id.从已认证的调用方得出分区:密钥对应的应用,或一个签名的用户 ID。
- Never accept a partition from the model or from tool arguments.绝不接受模型或工具参数提供的分区。
- Write it as the first parameter of every memory function.把它写成每个记忆函数的第一个参数。
02Store facts and build the briefing保存事实并生成摘要
- the partition argument分区参数 ← Memory记忆 1: Fix the partition rule确定分区规则
- the mem_facts tablemem_facts 表 ← State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表
Do this操作
- `remember()` upserts one key for one partition.`remember()` 为某个分区更新或插入一个键。
- `briefing()` returns a few lines, newest first, with a hard limit.`briefing()` 返回几行内容,新的在前,并有硬性上限。
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)03Write the record pipeline, after the answer编写记录流程,放在回答之后
- remember()remember() ← Memory记忆 2: Store facts and build the briefing保存事实并生成摘要
- proof that a background writer is safe后台写入安全的证据 ← State and storage状态与存储 5: Test concurrent writers before you depend on them在依赖并发写入之前先测试
Do this操作
- `record()` stores the user turn and the assistant turn, then extracts facts from what the user said.`record()` 保存用户和助手各一轮对话,然后从用户说的话里提取事实。
- `record_async()` runs it in a background thread and catches every exception.`record_async()` 在后台线程里执行它,并捕获所有异常。
- The lab extracts with patterns to stay deterministic. A real system asks a small model what is worth keeping.为保持确定性,lab 用正则模式提取。真实系统会让一个小模型判断什么值得保留。
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()- Memory记忆 4: Add recall over past turns加入对历史对话的回忆 (stored turns已保存的对话)
- Memory记忆 5: Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性 (record_async()record_async())
04Add recall over past turns加入对历史对话的回忆
Do this操作
- Search this partition's turns by similarity to the query.按与查询的相似度检索该分区的对话。
- Skip the current thread. It is already in context.跳过当前会话。它已经在上下文里了。
- Return nothing below a similarity floor. A weak match presented as memory is worse than none.相似度低于门槛就什么都不返回。把弱匹配当成记忆,比没有记忆更糟。
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]- Memory记忆 6: Test the three boundaries of recall测试回忆的三条边界 (recall()recall())
- Memory记忆 8: Offer recall as a tool bound to one user把回忆做成绑定到单个用户的工具 (recall()recall())
05Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性
- record_async()record_async() ← Memory记忆 3: Write the record pipeline, after the answer编写记录流程,放在回答之后
- the memory plug point记忆接入点 ← Harness engineeringHarness 工程 5: Compose the system prompt from parts分部分组装系统提示词
- the place run() hands off the exchangerun() 交出对话的位置 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
Do this操作
- Pass the memory object as the `memory` argument of the agent.把记忆对象作为智能体的 `memory` 参数传入。
- Run two users through the agent. Each states a cost center.让两个用户分别通过智能体。各自说出一个成本中心。
- Check each briefing, then check that one user's fact is absent from the other's prompt.检查各自的摘要,再确认一个用户的事实没有出现在另一个用户的提示词里。
python3 -m labs.m09_memory.demo1 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- Memory记忆 7: Prove a memory failure cannot break an answer证明记忆故障不会破坏回答 (memory attached to the agent已接到智能体上的记忆)
06Test the three boundaries of recall测试回忆的三条边界
Do this操作
- Owner recalls an earlier thread: a hit.所有者回忆之前的会话:有命中。
- Another user runs the same query: nothing.另一个用户执行同样的查询:没有结果。
- Owner queries from the same thread: nothing, it is already in context.所有者在同一个会话里查询:没有结果,因为已在上下文里。
- Owner queries something unrelated: nothing.所有者查询不相关的内容:没有结果。
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 : []07Prove a memory failure cannot break an answer证明记忆故障不会破坏回答
- memory attached to the agent已接到智能体上的记忆 ← Memory记忆 5: Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性
Do this操作
- Replace `record` with a function that raises.把 `record` 换成一个会抛异常的函数。
- Run a request and read the answer.发一个请求,查看回答。
memory write failed (response unaffected): disk full
8 answer despite failed write: Lodging is reimbursed at actual cost up to 220 dol ...08Offer recall as a tool bound to one user把回忆做成绑定到单个用户的工具
- recall()recall() ← Memory记忆 4: Add recall over past turns加入对历史对话的回忆
- the registry decorator注册表的装饰器 ← Tools and MCP工具与 MCP 2: Build the registry搭建注册表
Do this操作
- Create the tool function per request with the partition and thread already fixed.每个请求创建一次工具函数,分区和会话在创建时就固定。
- Expose one argument: the query.只暴露一个参数:查询内容。
- Return a diagnostic when nothing matches.没有匹配时返回诊断信息。
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 regpython3 -m labs.m09_memory.tool_check1 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 resultsHow it works with the other parts它如何与其他部分协作
- Harness engineeringHarness 工程The briefing enters prompt composition. The record call follows the response.摘要在组装提示词时进入。记录调用紧随响应之后。
- State and storage状态与存储Facts and turns live in mem and conv tables. Background writes rely on WAL.事实和对话存放在 mem 和 conv 表里。后台写入依赖 WAL。
- Evaluation评估A memory eval seeds two synthetic users and checks hits, silence, and separation.记忆评估会创建两个模拟用户,检查命中、应保持沉默的情况和隔离性。
- Self-evolving agents自进化智能体Learned rules are a kind of memory that belongs to the agent, stored with the same status discipline.学到的规则是属于智能体自身的一种记忆,按同样的状态管理方式存储。
What went wrong in the real build真实搭建中踩过的坑
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.记忆应该补充上下文里没有的东西。
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.根据测得的分数差距来选阈值。
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本模块如何对应 |
|---|---|
| Databricks | Agent 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 watsonx | Orchestrate keeps conversation context. Long-term memory is a store you connect and read through a tool.Orchestrate 保留对话上下文。长期记忆是你接入的存储,通过工具读取。 |
| Codex | Persistent instructions live in AGENTS.md. Memories are files the agent is told to read and update.持久指令放在 AGENTS.md 里。记忆是让智能体去读取和更新的文件。 |
| Cursor | Rules and memory features hold persistent preferences. Project facts belong in repo files.规则和记忆功能保存持久偏好。项目相关的事实应放在仓库文件里。 |
| Claude Code / Agent SDK | A project instruction file plus memory files and tools. The pattern is the same: write after, read at start, scope by project.项目指令文件加上记忆文件和工具。模式相同:事后写入、开始时读取、按项目限定范围。 |
| Another machine | A 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?为什么记忆写入要“发出即不管”?
What stops one user's memory from reaching another?是什么阻止一个用户的记忆到达另一个用户?
Why are facts in every prompt and turns only on demand?为什么事实进入每次提示词,而对话历史只按需读取?
In what order did you build memory, and what does each step need from the one before?你按什么顺序搭建记忆?每一步需要上一步的什么?
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.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Memory store on Postgres, second attempt (qualified upsert columns); recall skips the current thread, memory briefing cannot fail a request
- Memory store on Postgres (mem schema), recall skips the current thread, memory briefing cannot fail a request
- Recall similarity floor 0.35 (eval: lowest hit 0.55, highest unrelated 0.24)
- Conversation recall: mem.turns index, recall_conversations tool, recall gate in the daily cycle
- Self-evolution: what was broken, what changed
- Issues 7, 8 and 9 — diagnosis and fix
- Local Agent Server — Build Guide v2
- the quarantined learned-knowledge store (BRAIN-ARCHITECTURE.md §3.1). Deliberately modelled on memory_store.py, right down to the conventions: contextmanager connection, schema-if-not-exists, 0600 permissions, PRAGMA journal_mode=TRUNCATE, and idempotent additive migrations via ...
- the agent-facing wrapper around claim_recall. REGISTERED 2026-08-18, AFTER IT EARNED IT. ------------------------------------------ This file sat unregistered until the T5 discrimination drill said it was worth registering.
- the agent can look up what was said before (2026-10-01). Thin wrapper over conversation_index.search(). Registered after nightly/recall_eval.py passed its gate (see evals/memory/history.jsonl).
- Step 3.6 (AGENT_SERVER_GUIDE_v2.md §4/§7.1): the durable episodic + user-profile memory layer.
- memory_store on Postgres behaves like it did on SQLite (2026-10-01). Runs the same calls against both backends under a throwaway partition, compares what comes back, removes its rows. Exits non-zero on a difference.
- copy memory.db into Postgres schema mem (2026-10-01). Idempotent. agent:self observations are collapsed to the newest row per distinct finding (10,998 rows were 26 findings re-logged hourly). venv/bin/python3 ../ops/migrate_memory_pg.py # migrate + verify
- does conversation recall find the right exchange, stay quiet when nothing fits, and keep users apart? (2026-10-01) Seeds two synthetic users (partitions eval:recall-a / eval:recall-b) straight into mem.turns, asks paraphrased questions, removes the seed rows.
- the missing wire between 144,386 learned atoms and a live answer, plus the instrumentation that proves whether it helps.