ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Mastra Working Memory 实战指南:为 Agent 构建持久化用户记忆的最佳实践

Mastra Working Memory 实战指南:为 Agent 构建持久化用户记忆的最佳实践 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.tsWorking Memory 支持resource默认跨线程持久化与thread按线程隔离两种作用域还可以选择 Markdown 模板模式或 schema 模式来约束存储结构这为不同场景提供了灵活的实现方式。以下四类 Agent 尤其受益于 Working Memory个人助手Personal assistants需要记住用户偏好如沟通风格、兴趣话题、时区客服支持 AgentCustomer support agents需要跟踪问题细节如工单号、历史诉求、处理进度教育类 AgentEducational agents需要记住学生的学习进度、薄弱点与学习目标任务型 AgentTask-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.mdimport { 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重启开发服务器打开 Playgroundhttp://localhost:4111/选择你的 MemoryAgent进行一段透露个人信息的对话Hi, my name is JordanI live in Toronto, CanadaI prefer casual communicationIm interested in artificial intelligence and music productionWhat do you know about me so far?此时 Agent 应能从工作记忆中完整回忆起上述信息即使对话已经转移到其他话题。继续对话切换到新话题再次提问Lets 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),仅供参考
返回列表