智能体记忆:写进什么、找回什么、什么会过时
Agent memory
按近因、重要性与相关性为记忆流打分,再在含事实更新的合成对话上比较有界消息队列、回溯检索与可编辑工作上下文。
agent-memory模型在上下文窗口的边缘遗忘
语言模型只依据当前上下文中的词元进行生成。一个连续运行数天、或跨多次会话与人交谈的智能体,积累的历史远远超过窗口能容纳的量。必须由模型之外的某个部分决定:存什么,当前这一步取回什么,某个事实变化时覆盖什么。这个部分就是智能体的记忆系统,它的决定会直接体现在行为上:一个总把你领到上个月会议室的助手,问题出在记忆,而不在推理。
2023 年的两个系统把这些设计选择具体化了。Generative Agents 用自然语言完整地、只追加地记录智能体的经历,称为记忆流(memory stream),每次决策时结合近因、重要性和相关性取回其中一小部分。记忆与检索,第 4.1 节 MemGPT 借鉴操作系统:把提示看作主存,把外部数据库看作磁盘,由模型自己发出函数调用在两者之间搬运信息,上下文快满时由系统发出警告。第 2.1–2.3 节
两种设计回答不同的问题。Generative Agents 问:在一个很大的存储里,模型此刻应该看到哪些条目?MemGPT 问:窗口大小固定时,由谁、在何时把什么移进移出?还有第三个问题两者都只部分回答:两条存储内容互相矛盾时,哪一条是当前有效的?本文用一个确定性程序把三个问题逐一走一遍。面向文档集合的检索增强生成和向量索引结构另有条目,这里不涉及;本文聚焦智能体对自身经历的记忆。
检索分数、归一化与记忆层级
在 Generative Agents 中,每个记忆对象保存一段自然语言描述、一个创建时间戳和一个最近访问时间戳。对时刻 的查询 计算三个分数。近因(recency)是对“自上次被取回以来的游戏小时数”做指数衰减,衰减因子为 0.995。重要性(importance)是记忆创建时由语言模型给出的 1 到 10 的整数。相关性(relevance)是记忆与查询的嵌入向量之间的余弦相似度。第 4.1 节,第 9 页 每个分数都在候选记忆上做最小—最大缩放,映射到 0 到 1:
最终分数是加权和;论文把三个权重都设为 1,并把排名靠前、能装进上下文窗口的记忆放入提示:第 4.1 节,第 9 页
其中 是该记忆的最近访问时间, 是重要性, 是嵌入向量。最小—最大缩放带来一个容易被忽视的后果。因为 ,把 往后推,相当于给每个原始近因值乘上同一个正常数,而这个常数在归一化中被约掉:
所以,只要两次查询之间访问时间不变,归一化后的近因只编码过去各次访问的先后与间隔,而不反映“现在”离它们有多远。一个闲置很久的智能体,对记忆的排序与之前完全相同。这是对公式本身的推导,不是论文的主张。在论文中,检索还会刷新访问时间,经常被取回的记忆因此保持“近”,由此形成一个反馈回路。
Generative Agents 还引入第二类记忆对象:反思(reflection)。当最近事件的重要性之和超过阈值(实现中为 150)时,系统让模型针对最近 100 条记录提出几个高层问题,为每个问题检索证据,再写出引用所依据记录的见解。反思进入同一个记忆流,可以再被检索、再被反思,形成树状结构。第 4.2 节,第 9–10 页 作为智能体层面纠错循环的反思是另一个主题(智能体反思);在这里它是一种记忆压缩机制。
MemGPT 把提示分成三个连续部分:只读的系统指令;固定大小、可读写、只能通过函数调用修改的工作上下文;以及先进先出(FIFO)消息队列,队首保存被逐出消息的递归摘要。提示之外有回溯存储(recall storage),保存全部消息;还有归档存储(archival storage),是可读写、存放任意文本的数据库。第 2.1–2.2 节,第 2–3 页 设上下文容量为 个词元,按论文描述,约束和两个阈值为:
达到警告阈值时,队列管理器插入一条“内存压力”消息,让模型把重要内容存进工作上下文或归档存储;达到清空阈值时,它逐出消息、更新递归摘要,被逐出的消息仍可在回溯存储中检索。70% 和 50% 是论文举的例子,不是固定常数。第 2.2 节,第 3 页 模型通过函数调用自行编辑和搜索记忆;输出会被解析与校验,错误会反馈给模型,检索结果分页返回,还有一个标志允许模型连续调用多个函数再交还控制权。第 2.3–2.4 节,第 3–4 页 论文的对话示例中,用户说已经分手后,工作上下文里的“Boyfriend named James”被替换为“Ex-boyfriend named James”。图 4,第 4 页 这种替换操作正是回答上面第三个问题的机制。
在合成数据上比较检索权重与三种记忆策略
程序分两部分,不使用语言模型、嵌入模型或网络。
A 部分用 Generative Agents 的公式为十一条手写的合成办公室记忆打分。相关性是去掉一小份停用词表后,词袋计数向量之间的余弦相似度,用来代替嵌入。重要性由人工固定。近因只用创建时间,省略了访问时间刷新。查询在第 100 小时提出:“where is the team meeting this week”。记忆流里有一条旧事实(第 2 小时:会议在 Birch 会议室)和一条更新(第 58 小时:会议改到 Cedar 会议室)。
B 部分生成 200 段各 48 条消息的合成对话。每段有 16 条形如“键 = 值”的事实消息,覆盖 8 个键,因此每个键先被陈述、后被更新各一次;其余为闲聊。四分之一的事实消息被标记为改述:它们在上下文中时智能体能理解,但在回溯存储上按键精确搜索找不到。上下文容纳 12 条消息;系统在 70%(9 条)时警告,满时清掉一半。策略如下:
fifo:只根据仍在队列中的消息回答;recall-first-hit:队列中没有时搜索回溯存储,返回第一条(最旧的)匹配;recall-latest:同上,但返回最新的匹配;working:每次警告时,一个脚本化写入器把队列里尚未写过的事实全部复制进键值式工作上下文,并替换旧值;回答依次查队列、工作上下文、回溯存储;working-missed:同一写入器每四次写入跳过一次,代表一个没能保存某些内容的模型。
"""Original synthetic memory study. No language model, embedding model or network is used.
Part A scores a memory stream with recency, importance and relevance.
Part B compares a bounded message queue with recall search and an editable working context.
A paraphrased fact is understood while it is in context but is invisible to exact-key recall search.
"""
import math
import random
import re
from collections import Counter
STOP = {'the', 'a', 'is', 'at', 'in', 'to', 'of', 'on', 'for', 'and', 'this', 'with', 'now', 'will', 'be'}
def words(text):
return Counter(w for w in re.findall(r'[a-z]+', text.lower()) if w not in STOP)
def cosine(a, b):
dot = sum(a[k] * b[k] for k in a)
na, nb = math.sqrt(sum(v * v for v in a.values())), math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
def minmax(xs):
lo, hi = min(xs), max(xs)
return [0.0 if hi == lo else (x - lo) / (hi - lo) for x in xs]
STREAM = [
(2, 3, 'Weekly team meeting is in Room Birch on Thursday'),
(5, 2, 'Bought coffee beans for the office kitchen'),
(9, 6, 'Dana prefers short written summaries before meetings'),
(20, 2, 'Watered the plants near the window'),
(31, 8, 'Release deadline for the billing service is Friday'),
(44, 2, 'Printer on floor two is out of toner'),
(58, 7, 'Team meeting moved from Room Birch to Room Cedar starting this week'),
(63, 2, 'Lunch order arrived late'),
(77, 3, 'Read an article about meeting room booking software'),
(90, 2, 'Cleaned the whiteboard in Room Birch'),
(96, 4, 'Dana asked for the billing release checklist'),
]
def retrieve(query, now, weights, k=3, decay=0.995):
q = words(query)
rec = minmax([decay ** (now - t) for t, _, _ in STREAM])
imp = minmax([i for _, i, _ in STREAM])
rel = minmax([cosine(q, words(text)) for _, _, text in STREAM])
a, b, c = weights
scores = [a * r + b * m + c * v for r, m, v in zip(rec, imp, rel)]
order = sorted(range(len(STREAM)), key=lambda j: (-scores[j], j))[:k]
return [(STREAM[j][0], round(scores[j], 3)) for j in order]
def conversation(rng, n=48, keys=8):
msgs, truth = [], {}
fact_slots = sorted(rng.sample(range(n), 16))
for t in range(n):
if t in fact_slots:
key = 'k%d' % (fact_slots.index(t) % keys)
value = 'v%d' % rng.randrange(100)
truth[key] = value
paraphrased = rng.random() < 0.25
msgs.append((t, 'fact', key, value, paraphrased))
else:
msgs.append((t, 'chat', None, None, False))
return msgs, truth
def run(msgs, policy, capacity=12, warn=0.7, flush=0.5, miss_every=0):
queue, recall, working, writes, seen = [], [], {}, 0, set()
for m in msgs:
queue.append(m)
recall.append(m)
if policy == 'working' and len(queue) >= math.ceil(warn * capacity):
for item in queue:
if item[1] == 'fact' and item[0] not in seen:
seen.add(item[0])
writes += 1
if miss_every and writes % miss_every == 0:
continue
working[item[2]] = item[3]
if len(queue) >= capacity:
queue = queue[int(flush * capacity):]
return queue, recall, working
def answer(key, queue, recall, working, policy):
in_queue = [m for m in queue if m[2] == key]
if in_queue:
return in_queue[-1][3]
if policy == 'fifo':
return None
if policy == 'working' and key in working:
return working[key]
hits = [m for m in recall if m[2] == key and not m[4]]
if not hits:
return None
return hits[0][3] if policy == 'recall-first-hit' else hits[-1][3]
def main(seed=0, trials=200):
query = 'where is the team meeting this week'
print('A: query at hour 100 =', repr(query))
for name, w in [('equal', (1, 1, 1)), ('relevance_only', (0, 0, 1)), ('recency_only', (1, 0, 0)),
('importance_only', (0, 1, 0))]:
print(' ', name, retrieve(query, 100, w))
print(' equal_weights_top1_if_now_is_hour_1000', retrieve(query, 1000, (1, 1, 1), k=1))
rng = random.Random(seed)
policies = ['fifo', 'recall-first-hit', 'recall-latest', 'working', 'working-missed']
correct = {p: 0 for p in policies}
missing = {p: 0 for p in policies}
total = 0
for _ in range(trials):
msgs, truth = conversation(rng)
for p in policies:
base = 'working' if p.startswith('working') else p
queue, recall, working = run(msgs, base, miss_every=4 if p == 'working-missed' else 0)
replies = {k: answer(k, queue, recall, working, base) for k in truth}
correct[p] += sum(replies[k] == v for k, v in truth.items())
missing[p] += sum(r is None for r in replies.values())
total += len(truth)
print('B: conversations', trials, 'questions', total, 'capacity 12, warn at 70%, flush 50%')
for p in policies:
wrong = total - correct[p]
print(' %-17s accuracy %.3f no_answer %4d stale_answer %4d' % (p, correct[p] / total, missing[p], wrong - missing[p]))
if __name__ == '__main__':
main()
记录的输出如下:
A: query at hour 100 = 'where is the team meeting this week'
equal [(58, 2.372), (96, 1.333), (77, 1.333)]
relevance_only [(58, 1.0), (2, 0.943), (77, 0.408)]
recency_only [(96, 1.0), (90, 0.921), (77, 0.758)]
importance_only [(31, 1.0), (58, 0.833), (9, 0.667)]
equal_weights_top1_if_now_is_hour_1000 [(58, 2.372)]
B: conversations 200 questions 1600 capacity 12, warn at 70%, flush 50%
fifo accuracy 0.249 no_answer 1201 stale_answer 0
recall-first-hit accuracy 0.386 no_answer 81 stale_answer 901
recall-latest accuracy 0.816 no_answer 81 stale_answer 214
working accuracy 1.000 no_answer 0 stale_answer 0
working-missed accuracy 0.971 no_answer 14 stale_answer 32
A 部分。三项等权时,第 58 小时的更新以 2.372 分排第一(缩放后相关性 1、重要性 0.833、近因约 0.539)。只看相关性时它也排第一,但过时的第 2 小时事实以 0.943 紧随其后:两条都提到团队会议,余弦相似度里没有任何东西能标记其中一条已被取代。只看近因,返回的是三条较新的无用记忆,其中“Cleaned the whiteboard in Room Birch”还会误导把它当作证据的智能体。只看重要性,排第一的是计费服务的截止日期。把“现在”移到第 1000 小时,第一名及其分数 2.372 不变,这正是上文推导的归一化恒等式。
B 部分。只用有界队列,1,600 个问题中能回答 24.9%;其余 1,201 个事实已被逐出。搜索回溯存储能找回大部分,但返回最旧匹配时有 901 次给出过时的值:检索找到了正确的键,却是错误的版本。返回最新匹配把准确率提高到 81.6%;仍有 214 个过时答案,原因是改述的更新无法被搜索看到(此时可见的最新匹配就是旧值),另有 81 个问题完全没有可见的提及。趁事实仍在上下文中时把它写进可编辑的工作上下文,在这个玩具中达到 100%,因为脚本化写入器从不误读事实。每四次写入跳过一次时,准确率降到 97.1%。由于 16 条事实按顺序轮流对应 8 个键,被跳过的第 4、8、12、16 次写入两次都落在同样的两个键上,这两个键因此根本没有进入工作上下文。它们的问题退回到回溯存储搜索:46 个错误中有 32 个是过时答案,原因是改述的更新无法被搜索看到;另外 14 个问题完全没有可见的提及。没有任何错误来自工作上下文里的过时值,所以这一行是跳过规律造成的结构性产物,不是对随机写入失败的模拟。
A 部分每次查询的代价与存储的记忆条数成线性关系,因为每条记忆都要打分;真实系统用近似最近邻索引来避免这一点。B 部分各策略每个问题只需扫描一次队列,最多再扫描一次回溯存储。
合成结果能支持与不能支持的结论
B 部分工作上下文的 100% 来自脚本化写入器的性质,它读的是结构完全规整的“键 = 值”消息。由语言模型在内存压力警告下决定保存什么,可能漏掉事实、保存错误片段,或覆盖正确的值;working-missed 这一行只是其中一种粗糙的模拟。这里没有任何数字能估计真实模型出现这些情况的频率。
词袋余弦不是嵌入。它无法匹配改述,所以程序把改述建模为“对搜索不可见”。稠密嵌入更能匹配改述,但会带来自己的错误,例如把一条主题相近但已过时的事实排得很高——只看相关性时,第 2 小时那条记忆正是如此。
两篇论文都在各自设定下评估了可信度、一致性或任务准确率:Generative Agents 在沙盒小镇中用 25 个智能体,并对观察、规划和反思做了消融;MemGPT 评估了多会话聊天与文档问答。本文只读了来源说明中列出的架构章节,不报告也不复现它们的评测数字。
长期记忆还带来任何排序公式都无法解决的问题:用户同意存储哪些内容、如何删除,以及如何防止存储文本中隐藏的指令在日后被取回时被当作命令执行。跨会话持续存在的记忆,也会让其中的错误和被注入的内容持续存在。
练习
-
为什么 Generative Agents 只取回记忆流的一个子集,而不是把全部内容放进去或做总摘要?
答案:论文给出两个理由:完整的记忆流放不进上下文窗口,而且放入过多内容会分散模型注意力。论文还报告,在其示例中把全部经历做摘要得到的回答空泛无用,而检索能找出具体相关的记忆。检索是在模型之外决定“模型看到什么”。
-
按程序的分词,查询保留 where、team、meeting、week。记忆 2 保留 weekly、team、meeting、room、birch、thursday。记忆 58 保留 team、meeting、moved、from、room(两次)、birch、cedar、starting、week。计算两者的余弦相似度;已知记忆 58 为最大值、某条记忆为 0,求记忆 2 归一化后的相关性。
答案:记忆 2 与查询共有 team 和 meeting:余弦 = 2 / (2 × √6) ≈ 0.408。记忆 58 共有 team、meeting 和 week;其范数平方为 8 × 1 + 2² = 12:余弦 = 3 / (2 × √12) ≈ 0.433。记忆 2 的归一化相关性为 0.408 / 0.433 ≈ 0.943,与输出一致。过时的事实与更新几乎同样相关。
-
一个智能体闲置 900 小时后回答同一个查询。按程序的打分,长时间间隔会不会让旧记忆排得更靠后?如果希望绝对时长起作用,你会改什么?
答案:不会。时间戳固定时,每个原始近因值都乘上同一个因子 γ 的 900 次方,最小—最大缩放把它约掉,排序和分数都不变(第 1000 小时仍为 2.372)。若要绝对时长起作用,可以使用未归一化的衰减、固定的参照尺度,或为可能过期的事实设置明确的失效时间或有效区间。
-
一个客服助手必须始终使用客户当前的收货地址,客户偶尔更新地址,且有时换一种说法描述。你会选择哪种记忆设计?要测试什么?
答案:把地址作为单个可编辑槽位保存(工作上下文或数据库字段,带替换语义和时间戳),而不是依赖对消息历史的相似度搜索,因为搜索会把新旧陈述一起返回,还可能漏掉改述的更新;在玩具中,按最新匹配搜索仍有 214 个过时答案。要直接测试写入步骤:用不同措辞表达的更新能否被捕获,漏写时会发生什么,过时的槽位能否被发现,例如发货前请用户确认地址。
开放问题
Generative Agents 表明,结合近因、重要性与相关性的检索分数,加上定期反思,可以在沙盒中支撑可信的长期行为;它的权重全部设为 1,重要性分数来自模型自己。第 4.1 节 MemGPT 展示了一种方法:让固定窗口的模型通过函数调用和系统警告自行管理记忆层级,从而访问无界的历史。第 2 节 两种设计都没有一般性地解决以下问题:如何处理互相冲突的记忆,如何把写入策略与读取策略分开评估,以及一条错误记忆被存储、又被反思之后,如何限制它的影响。
比较记忆系统时,应分别报告写入规则、读取规则和冲突规则,并用会随时间变化、会被换种说法重述的事实来测试。对永不变化的事实的准确率衡量的是存储,而不是记忆管理。相关条目包括上下文窗口与长上下文模型、检索增强生成、向量数据库和智能体反思。
先判断,再看解释
回溯存储里能搜到某个键的新旧两条陈述,只看相关性排序时最可能出现什么问题?
学习目标
- 计算并解释近因、重要性与相关性的组合检索分数,包括最小—最大缩放使近因与当前时刻无关这一性质。
- 区分记忆的写入、读取与冲突处理规则,并用会更新、会被改述的事实检验有界队列、回溯检索与可编辑工作上下文。
先修与延伸
查看知识关联图 →参考文献
- Generative Agents: Interactive Simulacra of Human Behavior — scoped arXiv v2 (UIST 2023)
Joon Sung Park; Joseph C. O'Brien; Carrie J. Cai; Meredith Ringel Morris; Percy Liang; Michael S. Bernstein · 2023 - MemGPT: Towards LLMs as Operating Systems — scoped arXiv v2
Charles Packer; Sarah Wooders; Kevin Lin; Vivian Fang; Shishir G. Patil; Ion Stoica; Joseph E. Gonzalez · 2024
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Claude · 2026-12-02 · Independent AI check (Claude subagent, not the author; not a human or expert review). Ran example.py with python3 3.12 and diffed it against example.stdout.txt (identical); confirmed the python block is byte-identical in en.mdx and zh.mdx and the four display equations match. Re-derived the min-max recency identity (gamma^t > 0 factors out of numerator and denominator, so normalized recency is t-invariant for fixed access times) and confirmed the article labels it as its own derivation, not a paper claim; recomputed recency 0.538 for the hour-58 memory, 1 + 0.833 + 0.539 = 2.372, exercise 2 cosines 2/(2*sqrt 6) = 0.408 and 3/(2*sqrt 12) = 0.433 and ratio 0.943, and the Part B accounting. Instrumented the working-missed run to classify its 46 errors. Downloaded Generative Agents arXiv v2 and MemGPT arXiv v2 PDFs with curl and read pdftotext output of Generative Agents pp. 8-10 (Section 4.1 memory fields, 0.995 decay over game hours since last retrieval, 1-10 importance, cosine relevance, min-max scaling, all alphas 1; Section 4.2 threshold 150, 100 recent records) and MemGPT pp. 1-4 (three-part main context, recursive summary, recall/archival storage, warning e.g. 70%, flush evicting e.g. 50%, error feedback, heartbeat, Figure 4 caption). Compared zh and en section by section and checked data.json IDs. Did not read either paper's evaluation sections and did not render the MDX.
- 代码输出与记录一致,代码块逐字节相同,A、B两部分的所有数字与输出一致。
- 最小—最大归一化下近因与t无关的推导正确(γ^t为正、分子分母同时约去),并已标为本文推导而非论文主张;练习2的0.408、0.433、0.943复算无误。
- Generative Agents的0.995、1—10、min-max、权重1、阈值150与100条,以及MemGPT的三段主上下文、70%/50%为示例值、图4替换例,均与PDF一致。
- 发现并修正working-missed误差来源的错误解释;中英文逐节对应,ID存在,测验答案正确。
核对的来源位置:
- Generative Agents: Interactive Simulacra of Human Behavior — scoped arXiv v2 (UIST 2023) · arXiv v2 PDF pages 8–10 (Sections 4, 4.1, 4.2, start of 4.3): memory object fields; recency decay 0.995 over game hours since last retrieval; LLM importance 1–10 with the poignancy prompt; cosine relevance on embeddings; min-max to [0,1]; all alphas 1; top memories that fit context; reflection trigger at importance sum 150, 100 most recent records, cited evidence, reflection trees; gpt3.5-turbo. arXiv abstract page for 25 agents and ablation claim. Evaluation sections, appendix not read. The t-invariance of normalized recency is the author's derivation, not a paper claim.
- MemGPT: Towards LLMs as Operating Systems — scoped arXiv v2 · arXiv v2 PDF pages 2–4 (Sections 2–2.4, Figures 1–4, Table 1 caption, start of Section 3): main vs external context; system instructions / working context / FIFO queue with recursive summary; recall and archival storage; warning token count e.g. 70%, flush e.g. evict 50%; self-directed function calls with parsing, error feedback, pagination; events and heartbeat chaining; working_context.replace example. Experimental results not read; no code run.
相关主题