Mastra Working Memory 实战指南:为 Agent 构建持久化用户记忆的最佳实践
【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra
导读
本指南是 Mastra 官方课程“Agent Memory”系列中关于Working Memory(工作记忆)实战应用的核心章节,面向正在用 Mastra 构建个人助手、客服机器人、教育辅导 Agent 或任务型 Agent 的开发者。读完本文,你将掌握:Working Memory 的适用场景、四项核心最佳实践(精选内容、清晰指令、模板设计、充分测试)、如何在 Mastra 中完成配置与验证,以及如何与对话历史、语义召回协同构建完整的记忆增强 Agent。
Working Memory 适合什么场景
Working Memory 的核心价值,在于让 Agent 在同一个线程(thread)内的多次交互之间持续记住关于用户与任务的关键信息。相比对话历史(conversation history)和语义召回(semantic recall)侧重“回忆过去的消息”,Working Memory 存储的是持续相关、结构化的信息,例如:
- 用户画像信息(姓名、所在地、偏好)
- 任务专属细节(项目目标、截止日期)
- 会话状态(当前话题、待解答问题)
在 19-what-is-working-memory.md 中,Working Memory 被形象地比作“Agent 的活跃思维或便签本(scratchpad)”——就像人在对话中自然记住对方的名字、偏好和重要细节一样。
从源码类型定义看(types.ts),Working Memory 支持resource(默认,跨线程持久化)与thread(按线程隔离)两种作用域,还可以选择 Markdown 模板模式或 schema 模式来约束存储结构,这为不同场景提供了灵活的实现方式。
以下四类 Agent 尤其受益于 Working Memory:
- 个人助手(Personal assistants):需要记住用户偏好,如沟通风格、兴趣话题、时区;
- 客服支持 Agent(Customer support agents):需要跟踪问题细节,如工单号、历史诉求、处理进度;
- 教育类 Agent(Educational agents):需要记住学生的学习进度、薄弱点与学习目标;
- 任务型 Agent(Task-oriented agents):需要跟踪复杂任务的当前状态、已做步骤与待办事项。
合理使用 Working Memory,能让 Agent 表现出更强的个性化与用户关怀——它不再每次都“重新认识”用户,而是像一个真正记得你们对话的人。
工作原理:一段可持续更新的 Markdown
在 20-how-working-memory-works.md 中明确了它的实现机制:Working Memory 被实现为一段 Markdown 文本块,Agent 可以随时间更新它。
- 每次对话开始时,Agent 会读取这段信息;
- 当用户分享需要长期记住的信息(姓名、位置、偏好)时,Agent 会更新Working Memory;
- 在后续对话中,Agent 无需用户重复,即可直接使用这些信息。
工作记忆在代码层面通过标签包裹,例如packages/core/src/memory/working-memory-utils.ts中定义了<working_memory>与</working_memory>起始/结束标签,并提供了extractWorkingMemoryTags、extractWorkingMemoryContent、removeWorkingMemoryTags等工具函数来完成内容的提取与剥离,更新动作则通过updateWorkingMemory工具(默认模式)或setWorkingMemory工具(useStateSignals状态信号模式)触发(见 working-memory-utils.ts)。
与对话历史不同,Working Memory 不是原始消息的流水账,而是 Agent 从对话中提炼出的重要信息的浓缩摘要。这种设计让它比从原始对话历史中反复抽取信息更高效、更聚焦,同时结构化格式(Markdown)也便于 Agent 读取、定位与更新特定条目。
最佳实践一:精选进入 Working Memory 的内容
只存放跨对话依然相关的信息,不要用瞬时细节塞满 Working Memory。
Working Memory 的价值在于“精炼”,而非“全量”。把每一次对话的琐碎内容都塞进去,反而会稀释关键信息,并增加每次请求的 token 开销。实践中建议:
- 优先记录用户画像级信息(姓名、地区、偏好、兴趣)与任务级状态(目标、截止日期);
- 对瞬态内容(一次性的闲聊、临时问题)保持克制,这类信息交给对话历史承载即可。
从设计上看,Working Memory 最终会与对话历史、语义召回一起被折叠进同一个上下文窗口(见 types.ts 中关于三类记忆合并的说明),因此控制内容体积也有助于控制上下文长度。
最佳实践二:使用清晰的指令(Instructions)
给 Agent 明确指导:什么时候更新 Working Memory、如何更新、何时应查询记忆。
配置 Agent 时,instructions是让 Working Memory 真正生效的关键。课程中给出了可直接使用的示例(源自 21-configuring-working-memory.md):
import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' import { LibSQLStore, LibSQLVector } from '@mastra/libsql' // 创建带工作记忆配置的 memory 实例 const memory = new Memory({ storage: new LibSQLStore({ id: 'learning-memory-storage', url: 'file:../../memory.db', // 相对于 .mastra/output 目录的相对路径 }), // 消息历史的存储 vector: new LibSQLVector({ id: 'learning-memory-vector', url: 'file:../../vector.db', // 相对于 .mastra/output 目录的相对路径 }), // 语义搜索的向量数据库 embedder: 'openai/text-embedding-3-small', // 消息嵌入模型 options: { semanticRecall: { topK: 3, messageRange: { before: 2, after: 1, }, }, workingMemory: { enabled: true, }, }, }) // 创建配置了 memory 的 Agent export const memoryAgent = new Agent({ name: 'MemoryAgent', instructions: ` You are a helpful assistant with advanced memory capabilities. You can remember previous conversations and user preferences. IMPORTANT: You have access to working memory to store persistent information about the user. When you learn something important about the user, update your working memory. This includes: - Their name - Their location - Their preferences - Their interests - Any other relevant information that would help personalize the conversation Always refer to your working memory before asking for information the user has already provided. Use the information in your working memory to provide personalized responses. `, model: 'openai/gpt-5.4', memory: memory, })指令中值得关注的三个要点:
- 明确触发条件:告诉 Agent“当你了解到关于用户的某个重要信息时,更新工作记忆”,并列出具体的信息类别;
- 要求先查记忆:
Always refer to your working memory before asking for information the user has already provided——这能避免 Agent 反复索要用户已提供过的信息; - 要求个性化使用:指示 Agent 用工作记忆中的信息来给出个性化回复。
关于workingMemory配置,enabled控制是否启用,template提供工作记忆的内容模板(详见下一节)。从 types.ts 的类型定义看,还支持scope: 'resource' | 'thread'(默认resource)来切换记忆的持久化范围。
最佳实践三:设计周到的模板(Template)
模板决定了 Agent 能记住什么、以什么结构记住,务必按业务需求精心设计。
虽然不提供模板时会使用默认模板,但课程明确建议为具体用例自定义模板(见 22-custom-working-memory-templates.md)。模板的作用有三:
- 引导 Agent 记录哪些信息、如何组织;
- 为跨会话的工作记忆提供一致的结构;
- 让 Agent 更容易定位和更新某条具体信息。
课程给出了一个针对“学习助手”场景的完整模板示例:
options: { workingMemory: { enabled: true, template: ` # User Profile ## Personal Info - Name: - Location: - Timezone: ## Preferences - Communication Style: [e.g., Formal, Casual] - Interests: - Favorite Topics: ## Session State - Current Topic: - Open Questions: - [Question 1] - [Question 2] `, }, },设计模板时的要点:
- 分节组织:按信息类型拆分为 Personal Info(个人信息)、Preferences(偏好)、Session State(会话状态)等区块,结构与 Agent 的业务职责一一对应;
- 标签清晰:使用明确的标签(如
Name:、Location:)便于 Agent 定位与填写; - 预填示例值:如
[e.g., Formal, Casual],向 Agent 提示期望的取值风格; - 为不同信息类型预留位置:会话状态类信息(当前话题、待解答问题)与画像类信息分开存放,便于更新时互不干扰。
配合模板,Agent 的 instructions 也应同步细化,例如课程中的写法:
instructions: ` ... IMPORTANT: You have access to working memory to store persistent information about the user. When you learn something important about the user, update your working memory according to the template. Always refer to your working memory before asking for information the user has already provided. Use the information in your working memory to provide personalized responses. When the user shares personal information such as their name, location, or preferences, acknowledge it and update your working memory accordingly. `,最佳实践四:彻底测试
验证 Agent 能否正确地更新与检索工作记忆,并覆盖冲突信息、更正等边界情况。
课程在 23-testing-working-memory.md 中给出了一套完整的测试流程:
用上述配置更新 Agent 代码;
以
npm run dev重启开发服务器;打开 Playground(http://localhost:4111/);
选择你的 "MemoryAgent";
进行一段透露个人信息的对话:
- "Hi, my name is Jordan"
- "I live in Toronto, Canada"
- "I prefer casual communication"
- "I'm interested in artificial intelligence and music production"
- "What do you know about me so far?"
此时 Agent 应能从工作记忆中完整回忆起上述信息,即使对话已经转移到其他话题。
继续对话切换到新话题,再次提问:
- "Let's talk about the latest AI developments"
- (就 AI 话题聊一会儿)
- "What was my name again and where do I live?"
Agent 依然应记住这些信息——因为它存储在Working Memory中,而非仅仅依赖对话历史。
这个测试清晰地展示了核心差异:对话历史只包含最近的消息,而 Working Memory 用结构化方式跨话题、跨轮次持久保存用户的关键信息。仓库中的 mock-working-memory-merge.test.ts 与 working-memory-utils.test.ts 也印证了这套行为——测试覆盖了工作记忆标签的提取、合并与工具调用,可作为你编写自动化测试时的参考。
测试时务必关注的边界情况:
- 冲突信息:用户在不同时间给出矛盾的偏好,Agent 应更新为最新值;
- 更正行为:用户明确纠正先前提供的信息时,Agent 应正确覆盖旧值;
- 跨话题持久性:切换话题后关键信息仍可召回;
- 不重复提问:Agent 应主动引用已记住的信息,而不是再次询问。
进阶:与对话历史、语义召回协同
Working Memory 不是孤立功能。课程在 25-combining-memory-features.md 中演示了如何构建一个整合三大记忆能力的完整 Agent:
// src/mastra/agents/memory-agent.ts import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' import { LibSQLStore, LibSQLVector } from '@mastra/libsql' const memory = new Memory({ storage: new LibSQLStore({ id: 'learning-memory-storage', url: 'file:../../memory.db', // 相对于 .mastra/output 目录的相对路径 }), vector: new LibSQLVector({ url: 'file:../../vector.db', // 相对于 .mastra/output 目录的相对路径 }), embedder: 'openai/text-embedding-3-small', options: { // 对话历史配置 lastMessages: 20, // 在上下文中包含最近 20 条消息 // 语义召回配置 semanticRecall: { topK: 3, // 检索 3 条最相似的消息 messageRange: { before: 2, // 每条命中消息前包含 2 条 after: 1, // 每条命中消息后包含 1 条 }, }, // 工作记忆配置 workingMemory: { enabled: true, template: ` # User Profile ## Personal Info - Name: - Location: - Timezone: - Occupation: ## Preferences - Communication Style: - Topics of Interest: - Learning Goals: ## Project Information - Current Projects: - [Project 1]: - Deadline: - Status: - [Project 2]: - Deadline: - Status: ## Session State - Current Topic: - Open Questions: - Action Items: `, }, }, })三种记忆能力各司其职:
| 记忆能力 | 配置项 | 职责 |
|---|---|---|
| 对话历史 | lastMessages | 提供短期的对话连续性(默认 10 条,见 types.ts) |
| 语义召回 | semanticRecall | 通过向量相似度检索过去相关消息,跨越近期历史的长程连贯 |
| 工作记忆 | workingMemory | 结构化、持续地保存用户画像与任务状态 |
它们共同构成一个既能维持上下文、又能跨会话提供个性化回复的完整记忆系统——这正是下一阶段“创建完整记忆增强 Agent”的基础。
总结
Working Memory 是让 Mastra Agent 从“无状态工具”走向“懂用户的助手”的关键能力。实践的核心可以概括为四句话:
- 精选内容:只保留跨会话依然相关的结构化信息;
- 清晰指令:明确告诉 Agent 何时更新、先查记忆再提问;
- 精心模板:用分节、带标签的 Markdown 模板约束记忆结构与更新行为;
- 彻底测试:覆盖正常记忆、跨话题召回、冲突与更正等场景。
把 Working Memory 与对话历史、语义召回组合使用,你就能构建出真正具备持久上下文与个性化能力的记忆增强 Agent。若需回顾更早的课程步骤(如 Working Memory 是什么、如何配置、如何自定义模板、如何测试),可继续阅读 19-what-is-working-memory.md、21-configuring-working-memory.md、22-custom-working-memory-templates.md 与 23-testing-working-memory.md;下一步可在 25-combining-memory-features.md 中继续学习如何整合全部记忆特性。
【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考