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 中工作记忆Working Memory是 Agent 的便签纸用于跨对话轮次持久保存用户的关键信息。本文以 docs/src/course/03-agent-memory/23-testing-working-memory.md 为骨架完整讲解如何配置工作记忆、通过 Playground 测试其跨主题记忆能力并结合mastra/memory与mastra/core的源码剖析其底层更新机制与防数据丢失保护。读完本文你将掌握从配置、启动、对话测试到结果验证的完整闭环并能理解 Markdown 模板与 Schema 两种工作记忆形态的底层差异。工作记忆Agent 的活跃思维草稿在深入测试之前先明确工作记忆在整个 Mastra 记忆体系中的定位。Mastra 把 Agent 的上下文窗口划分为三部分参见 01-understanding-memory.md系统指令与用户信息即工作记忆 Working Memory最近的对话消息对话历史 Conversation History更早的相关消息语义召回 Semantic Recall与对话历史、语义召回着眼于记住过去的消息不同工作记忆专门存储持续相关的结构化信息详见 19-what-is-working-memory.md典型内容包括用户画像信息姓名、所在地、沟通偏好任务级细节项目目标、截止日期会话状态当前主题、待解决问题工作记忆的价值在于即使对话历史中的具体消息不断滚动替换Agent 依然能保持对用户与上下文语境的持久理解从而持续给出个性化回复。工作记忆的运行机制工作记忆在实现上是一块可被 Agent 持续更新的 Markdown 文本块参见 20-how-working-memory-works.mdAgent 在每轮对话开始时读取这块信息当用户透露需要长期记住的信息姓名、所在地、偏好等时Agent 通过updateWorkingMemory工具更新这块记忆后续对话中Agent 无需用户重复即可使用这些信息对话历史是原始消息记录而工作记忆是 Agent 学到的关键信息的蒸馏摘要因此更聚焦、更高效。在类型层面工作记忆的配置由 packages/core/src/memory/types.ts 中的WorkingMemory联合类型定义支持三种形态TemplateWorkingMemoryMarkdown 模板、SchemaWorkingMemoryJSON Schema 结构、WorkingMemoryNone仅开启开关。其中scope字段控制记忆的作用域resource默认表示记忆在同一用户resource的所有线程间共享thread则表示每个会话线程隔离。前置准备为 Agent 开启工作记忆测试前需要先完成配置。以下配置节选自 21-configuring-working-memory.md它创建了一个具备工作记忆能力的MemoryAgentimport { Agent } from mastra/core/agent import { Memory } from mastra/memory import { LibSQLStore, LibSQLVector } from mastra/libsql // Create a memory instance with working memory configuration const memory new Memory({ storage: new LibSQLStore({ id: learning-memory-storage, url: file:../../memory.db, // relative path from the .mastra/output directory }), // Storage for message history vector: new LibSQLVector({ id: learning-memory-vector, url: file:../../vector.db, // relative path from the .mastra/output directory }), // Vector database for semantic search embedder: openai/text-embedding-3-small, // Embedder for message embeddings options: { semanticRecall: { topK: 3, messageRange: { before: 2, after: 1, }, }, workingMemory: { enabled: true, }, }, }) // Create an agent with the configured memory 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, })workingMemory配置的关键选项enabled是否启用工作记忆template工作记忆内容的模板不提供时使用默认模板除此之外从 packages/core/src/memory/types.ts 的类型定义看还有scopethread | resource默认resource、useStateSignals实验性将工作记忆作为状态信号而非系统消息注入、agentManaged主 Agent 是否直接管理工作记忆默认true等高级选项。同时Agent 的instructions也至关重要——它引导 Agent 该存储哪些信息、以及如何利用这些信息作答。当用户透露姓名、所在地、偏好、兴趣等个人信息时Agent 应更新工作记忆在询问用户已经提供过的信息前应先查阅工作记忆。使用自定义模板精细控制记忆结构默认模板未必适合所有场景。通过自定义模板你可以引导 Agent 记录更贴合业务的结构化信息。以下示例来自 22-custom-working-memory-templates.mdimport { Agent } from mastra/core/agent import { Memory } from mastra/memory // Create a memory instance with a custom working memory template const memory new Memory({ storage: new LibSQLStore({ id: learning-memory-storage, url: file:../../memory.db, // relative path from the .mastra/output directory }), // Storage for message history vector: new LibSQLVector({ url: file:../../vector.db, // relative path from the .mastra/output directory }), // Vector database for semantic search embedder: openai/text-embedding-3-small, // Embedder for message embeddings options: { semanticRecall: { topK: 3, messageRange: { before: 2, after: 1, }, }, 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] , }, }, }) // Create an agent with the configured memory 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 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. , model: openai/gpt-5.4, memory: memory, })模板作为一份 Markdown 文档定义了工作记忆的结构包含个人信息、偏好、会话状态等分节。它的价值体现在三方面引导Agent 该跟踪哪些信息、如何组织它们为跨会话的工作记忆提供一致的格式让 Agent 更容易定位并更新某条具体信息。模板应基于 Agent 的具体需求与它需要记住的信息类型来设计。注册 Agent 到 Mastra 实例要使MemoryAgent出现在 Playground 中必须更新src/mastra/index.ts将其注册到mastra导出参见 05-updating-mastra-export.mdimport { Mastra } from mastra/core import { memoryAgent } from ./agents export const mastra: Mastra new Mastra({ agents: { memoryAgent, }, })mastra导出是 Mastra 应用的唯一入口只有注册进agents对象的 Agent 才会在 Playground 及其他应用部分中可用。核心测试步骤验证跨主题记忆能力完成上述配置后就可以按照 23-testing-working-memory.md 的完整流程验证 Agent 的工作记忆能力使用上文配置更新你的 Agent 代码运行npm run dev重启开发服务器打开 Playgroundhttp://localhost:4111/在 Playground 中选择你的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与 Agent 展开一段关于 AI 的对话What was my name again and where do I live?Agent 依然应该记住这些信息——因为它们存储在工作记忆中而非仅仅存在于对话历史里。这个测试很好地演示了工作记忆的核心价值让 Agent 在不同主题、不同轮次的对话间维持对用户的持久认知。与仅包含最近消息的对话历史不同工作记忆以结构化方式存储和检索用户的关键信息与信息被提及的时间无关。测试通过的关键判据按照上述脚本执行时可通过以下标准判断工作记忆是否正常工作即时召回第 5 步询问 What do you know about me so far? 时Agent 应完整复述姓名、城市、沟通偏好、兴趣等全部信息跨主题持久性第 6 步在切换至 AI 发展话题并展开一段完整对话后Agent 仍能准确回答 What was my name again and where do I live?对话历史的对照验证如果 Agent 只能记住最近几条消息即依赖对话历史说明工作记忆并未真正启用或未被正确更新若 Agent 能跨越多个话题召回早期信息则说明工作记忆链路存储、注入、工具更新全部生效。源码级原理updateWorkingMemory 工具与防数据丢失保护理解底层实现有助于排查测试中的异常。工作记忆的写入由 packages/memory/src/tools/working-memory.ts 中的updateWorkingMemoryTool承载它注册为updateWorkingMemory工具供 Agent 调用。核心要点如下1. 两种更新语义由配置形态决定working-memory.tsSchema 模式配置了schema采用合并语义merge semantics。调用deepMergeWorkingMemory将新数据与既有记忆递归合并——对象属性递归合并、null表示删除字段、数组整体替换、原始值直接覆盖见 working-memory.ts。同时由于合并语义依赖模型省略未更新的字段该模式下工具被标记为strict: false避免结构化输出强制所有字段进入required而导致未触及字段被占位值覆盖。模板Markdown模式采用替换语义replace semanticsAgent 传入完整的 Markdown 文本块直接替换旧内容。2. 防数据丢失保护working-memory.ts模板模式下存在一个典型风险LLM 可能返回空的模板例如只包含标题结构、所有字段留空从而清空已有数据。实现中通过归一化空白后比较新内容 vs 模板内容 vs 既有内容来拦截这种情况——若新内容与空模板逐字等价、而既有内容是有意义的非模板数据则跳过本次更新并返回失败提示防止工作记忆被意外清空。测试阶段若发现信息丢失可优先检查日志中是否出现了这条保护性跳过信息。3. 作用域与线程校验working-memory.ts工具执行时根据scope校验thread作用域要求必须存在threadIdresource作用域要求必须存在resourceId若线程不存在会自动创建并校验线程的resourceId与当前请求一致防止跨用户串写记忆。4. 记忆的持久化最终通过memory.updateWorkingMemory()将工作记忆写入存储层本教程中即 LibSQL并在每轮对话开始时由 Agent 读取注入上下文。这些行为均有对应的单元测试覆盖例如 packages/memory/src/tools/working-memory.test.ts 中的deepMergeWorkingMemory系列测试验证了 null 删除、数组替换、嵌套合并与不可变性packages/memory/src/processors/working-memory-state/processor.test.ts 则覆盖了useStateSignals状态信号模式下的快照与 diff 增量投递行为。测试阶段若行为不符预期可从这些测试用例反推配置是否正确。测试中常见问题与排查思路Agent 无法召回早期信息优先检查workingMemory.enabled是否为true、Agent 的instructions是否明确要求记住用户信息并更新工作记忆——课程配置中的指令段落列出姓名、位置、偏好、兴趣等对模型行为有直接引导作用对话切换主题后遗忘确认scope配置——默认resource会在同一用户的所有线程间共享记忆若误配为thread新线程将无法读取旧线程的记忆信息被清空检查是否触发模板模式下的防丢失保护Agent 返回了空模板若为 Schema 模式确认模型更新时省略未修改字段而非传入占位值Playground 中找不到 MemoryAgent确认src/mastra/index.ts的mastra导出中已注册该 Agent见上文 05-updating-mastra-export.md 的代码。小结通过 Playground 中透露个人信息 → 切换话题 → 再次询问的测试脚本你可以快速验证 Mastra 工作记忆是否真正发挥作用。关键在于理解三层事实工作记忆以 Markdown或 Schema JSON形式持久存储用户的关键信息Agent 通过updateWorkingMemory工具在每轮对话中增量维护它底层实现合并/替换语义、作用域校验、空模板保护决定了信息的更新与防丢失行为。掌握这套测试与排查方法后你可以进一步阅读 24-working-memory-in-practice.md 了解生产环境中的实践技巧或通过 25-combining-memory-features.md 将工作记忆与对话历史、语义召回组合使用构建具备完整记忆能力的 Agent。【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表