09
关键片段 · 14 处注解
跨会话记住该记的Memory
把以后还会用到的信息留下来
解决什么问题 · 每开一个新会话都从零开始:昨天定下的约定、这个项目的坑,今天还得再说一遍。把整段历史都带上又太重。
思路
- 记忆写成 markdown 文件,外加一份索引(名字 + 一句话);
- 每轮结束抽取候选记忆,先判断值不值得记、是否重复,再写盘并重建索引;
- 下一轮开始时,把「目录 + 当前请求」给模型,让它挑编号召回;
- 模型不可用就退回关键词匹配——记忆坏了不能拖垮主流程。
s09_memory/code.py · L271–335
GitHub 原文 ↗
271def keyword_memory_selection(
L271–271
兜底方案:把用户这句话切成词,和记忆的名字、描述做匹配打分。粗糙,但不需要模型,通常都能用。
272 records: list[dict], query: str, max_items: int
273) -> list[str]:
274 words = set(
275 re.findall(r"[a-z0-9_]{3,}|[\u4e00-\u9fff]{2,}", query.lower())
276 )
277 ranked = []
278 for record in records:
279 catalog_text = f"{record['name']} {record['description']}".lower()
280 score = sum(word in catalog_text for word in words)
L272–280
按命中的关键词数量打分;一个都没中就跳过。
281 if score:
282 ranked.append((score, record["filename"]))
283 ranked.sort(key=lambda item: (-item[0], item[1]))
L281–283
按命中词数从高到低排,分高的先取。
284 return [filename for _, filename in ranked[:max_items]]
L284–284
只取前几条。召回宁缺毋滥——塞十条不相干的记忆,比不塞更糟。
285
286def select_relevant_memories(messages: list, max_items: int = 5) -> list[str]:
L285–286
主方案让模型自己挑:给一份带编号的目录和当前请求,让它只回一个 JSON 数组,比如 [0, 2]。
287 records = list_memory_files()
288 query = recent_user_text(messages)
289 if not records or not query:
290 return []
291
292 catalog = "\n".join(
L287–292
把目录拼成「编号: 名字 - 描述」,给模型挑。
293 f"{index}: {' '.join(record['name'].split())} - "
294 f"{' '.join(record['description'].split())}"
295 for index, record in enumerate(records)
296 )
297 prompt = (
L293–297
提示只要求返回 JSON 下标数组,解析简单。
298 "Select memory records that are relevant to the current user request. "
299 "Return only a JSON array of catalog indices, such as [0, 2]. "
300 "Return [] when none are relevant.\n\n"
301 f"Current request:\n{query}\n\nMemory catalog:\n{catalog[:12000]}"
302 )
303
304 try:
305 response = client.messages.create(
L298–305
这一步也要调一次模型;失败就走兜底。
306 model=MODEL,
307 messages=[{"role": "user", "content": prompt}],
308 max_tokens=200,
309 )
310 indices = extract_json_array(
L306–310
解析下标;越界、非整数会被过滤。
311 message_text({"content": response.content})
312 )
313 selected = []
L311–313
去重并限制条数,最多 5 条。
314 for index in indices:
315 if isinstance(index, int) and 0 <= index < len(records):
316 filename = records[index]["filename"]
317 if filename not in selected:
318 selected.append(filename)
319 if len(selected) == max_items:
320 break
321 return selected
322 except Exception:
323 return keyword_memory_selection(records, query, max_items)
L314–323
模型调用一失败就退回关键词匹配。记忆是增强功能,不能变成单点故障。
324
325def load_memories(messages: list) -> str:
L324–325
选中后按字符预算截断,拼成 JSON 注入 system prompt;预算用完就停。
326 loaded = []
L326–326
按预算依次读正文,读满就停。
327 remaining = RECALL_CHAR_LIMIT
328 for filename in select_relevant_memories(messages):
L327–328
只读选中的记忆,不整库加载。
329 content = read_memory_file(filename)
330 if not content or remaining <= 0:
331 continue
332 recalled = content[:remaining]
333 loaded.append({"source": filename, "content": recalled})
334 remaining -= len(recalled)
335 return json.dumps(loaded, ensure_ascii=False, indent=2) if loaded else ""
记住这几条
两级结构
索引常驻(便宜),正文按需(贵)。和 s07 技能加载是同一个套路。
召回要有 query
拿当前用户请求去匹配,而不是把所有记忆一股脑塞进去。
写入发生在轮末
这一版在每轮结束后抽取候选记忆并整理索引,不是边聊边写。
一定要能降级
模型挑选失败 → 关键词匹配;匹配失败 → 不召回。
容易踩的坑
- 什么都记:一次性的调试细节也写进去,下次召回全是噪声。
- 记忆和当前代码冲突:记着「用 npm」,但项目早换 pnpm 了,模型会照记忆办事。
- 召回条数不设上限,一次塞进十条长记忆,上下文直接见底。
动手改一改
让它记住「这个项目用 pnpm,不要用 npm」,然后开一个新会话直接问「装个依赖用哪个命令」。验收:新会话里模型引用了这条记忆,或回答里明确说「按记忆用 pnpm」。