Mastra Working Memory 实战测试指南:验证 Agent 跨主题记忆用户信息的能力
2026/9/13 23:38:27 网站建设 项目流程

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):

  1. 系统指令与用户信息(即工作记忆 Working Memory)
  2. 最近的对话消息(对话历史 Conversation History)
  3. 更早的相关消息(语义召回 Semantic Recall)

与对话历史、语义召回着眼于"记住过去的消息"不同,工作记忆专门存储持续相关的结构化信息(详见 19-what-is-working-memory.md),典型内容包括:

  • 用户画像信息:姓名、所在地、沟通偏好
  • 任务级细节:项目目标、截止日期
  • 会话状态:当前主题、待解决问题

工作记忆的价值在于:即使对话历史中的具体消息不断滚动替换,Agent 依然能保持对用户与上下文语境的持久理解,从而持续给出个性化回复。

工作记忆的运行机制

工作记忆在实现上是一块可被 Agent 持续更新的 Markdown 文本块(参见 20-how-working-memory-works.md):

  • Agent 在每轮对话开始时读取这块信息;
  • 当用户透露需要长期记住的信息(姓名、所在地、偏好等)时,Agent 通过updateWorkingMemory工具更新这块记忆;
  • 后续对话中,Agent 无需用户重复即可使用这些信息;
  • 对话历史是原始消息记录,而工作记忆是 Agent 学到的关键信息的蒸馏摘要,因此更聚焦、更高效。

在类型层面,工作记忆的配置由 packages/core/src/memory/types.ts 中的WorkingMemory联合类型定义,支持三种形态:TemplateWorkingMemory(Markdown 模板)、SchemaWorkingMemory(JSON Schema 结构)、WorkingMemoryNone(仅开启开关)。其中scope字段控制记忆的作用域:'resource'(默认)表示记忆在同一用户(resource)的所有线程间共享,'thread'则表示每个会话线程隔离。

前置准备:为 Agent 开启工作记忆

测试前需要先完成配置。以下配置节选自 21-configuring-working-memory.md,它创建了一个具备工作记忆能力的MemoryAgent

import { 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 的类型定义看,还有scope'thread' | 'resource',默认'resource')、useStateSignals(实验性:将工作记忆作为状态信号而非系统消息注入)、agentManaged(主 Agent 是否直接管理工作记忆,默认true)等高级选项。

同时,Agent 的instructions也至关重要——它引导 Agent 该存储哪些信息、以及如何利用这些信息作答。当用户透露姓名、所在地、偏好、兴趣等个人信息时,Agent 应更新工作记忆;在询问用户已经提供过的信息前,应先查阅工作记忆。

使用自定义模板精细控制记忆结构

默认模板未必适合所有场景。通过自定义模板,你可以引导 Agent 记录更贴合业务的结构化信息。以下示例来自 22-custom-working-memory-templates.md:

import { 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 文档,定义了工作记忆的结构,包含个人信息、偏好、会话状态等分节。它的价值体现在三方面:

  1. 引导Agent 该跟踪哪些信息、如何组织它们;
  2. 为跨会话的工作记忆提供一致的格式
  3. 让 Agent 更容易定位并更新某条具体信息。

模板应基于 Agent 的具体需求与它需要记住的信息类型来设计。

注册 Agent 到 Mastra 实例

要使MemoryAgent出现在 Playground 中,必须更新src/mastra/index.ts将其注册到mastra导出(参见 05-updating-mastra-export.md):

import { 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 的工作记忆能力:

  1. 使用上文配置更新你的 Agent 代码;

  2. 运行npm run dev重启开发服务器;

  3. 打开 Playground:http://localhost:4111/;

  4. 在 Playground 中选择你的MemoryAgent

  5. 展开一段透露个人信息的对话:

    • "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 也应该能从工作记忆中召回以上全部信息。

  6. 继续对话,引入新话题,然后再次提问:

    • "Let's 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.ts)

  • Schema 模式(配置了schema):采用合并语义(merge semantics)。调用deepMergeWorkingMemory将新数据与既有记忆递归合并——对象属性递归合并、null表示删除字段、数组整体替换、原始值直接覆盖(见 working-memory.ts)。同时由于合并语义依赖模型省略未更新的字段,该模式下工具被标记为strict: false,避免结构化输出强制所有字段进入required而导致未触及字段被占位值覆盖。
  • 模板(Markdown)模式:采用替换语义(replace semantics),Agent 传入完整的 Markdown 文本块直接替换旧内容。

2. 防数据丢失保护(working-memory.ts)

模板模式下存在一个典型风险:LLM 可能返回"空的模板"(例如只包含标题结构、所有字段留空)从而清空已有数据。实现中通过归一化空白后比较"新内容 vs 模板内容 vs 既有内容"来拦截这种情况——若新内容与空模板逐字等价、而既有内容是有意义的非模板数据,则跳过本次更新并返回失败提示,防止工作记忆被意外清空。测试阶段若发现信息丢失,可优先检查日志中是否出现了这条保护性跳过信息。

3. 作用域与线程校验(working-memory.ts)

工具执行时根据scope校验:'thread'作用域要求必须存在threadId'resource'作用域要求必须存在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.tsmastra导出中已注册该 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),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询