Mastra 记忆最佳实践:为 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、semantic recall、conversation history 三类记忆协同使用时的工程实践要点。你将掌握如何筛选进入工作记忆的信息、如何为 Agent 编写清晰的内存更新指令、如何调优
lastMessages/topK/messageRange等关键参数、如何处理隐私与安全边界,以及如何通过系统化测试验证记忆增强 Agent 的行为一致性。
为什么需要"记忆最佳实践"
Mastra 的 Memory 体系由三个层次构成(见 packages/core/src/memory/types.ts):
- 会话历史(Conversation History):以
lastMessages控制最近 N 条消息进入上下文,负责近期上下文; - 语义召回(Semantic Recall):基于向量相似度检索历史中与当前问题相关的旧消息,负责跨会话检索;
- 工作记忆(Working Memory):以结构化文本(Markdown 或 schema)持久保存用户画像与任务状态,负责长期稳定的用户信息。
只开启记忆并不等于拥有"好记忆"。文档强调:如果信息过载、指令含糊、参数失当、隐私处理不当,记忆反而会拖累 Agent——这正是 29-memory-best-practices.md 存在的意义。它把散落在各章的配置技巧收敛为一组可执行的工程守则,帮助你在个性化体验与信息过载 / 隐私风险 / 行为不一致之间取得平衡。
守则一:谨慎筛选进入工作记忆的信息
工作记忆是 Agent 的"便签纸",只应存放跨多个会话仍然有用的信息。文档给出的判断标准是:
- 只保留跨会话持续相关的信息(用户姓名、位置、偏好、目标);
- 不要让工作记忆被瞬时、易变的细节塞满(如一次性的小任务、临时闲聊内容)。
从实现上看,Mastra 默认提供一份结构化模板(见 packages/core/src/memory/memory.ts),覆盖 First Name、Location、Occupation、Interests、Goals、Events、Facts、Projects 等字段;而 memoryDefaultOptions 中workingMemory.enabled默认是false,即工作记忆是按需开启的能力,开启前值得先问自己:这个 Agent 真正需要跨会话记住什么?
判断是否放入工作记忆时,可以对照三类信息的定位:
| 信息类型 | 存放位置 | 理由 |
|---|---|---|
| 最近几轮对话细节 | Conversation History | 由lastMessages自动带入,无需写入工作记忆 |
| 历史中零散但相关的信息 | Semantic Recall | 通过向量检索按需召回 |
| 用户画像、任务状态等持久信息 | Working Memory | 以结构化模板长期保存 |
守则二:用清晰的指令约束 Agent 的写入与读取时机
工作记忆的更新主体是 Agent 本身(工具调用模式),因此指令(instructions)是记忆质量的第一道闸门。文档要求两类明确指引:
- 何时写入:告诉 Agent 在学到用户重要信息(姓名、位置、偏好、兴趣等)时更新工作记忆;
- 何时读取:要求 Agent 在向用户索要信息之前,先查自己的工作记忆,避免重复提问。
课程中MemoryAgent的指令模板(见 21-configuring-working-memory.md)可直接复用:
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. `,从源码看,工作记忆采用工具调用模式注入:源码中移除了旧的workingMemory.use配置项,若传入会直接抛出错误(见 packages/core/src/memory/memory.ts),并注册updateWorkingMemory等工具供 Agent 调用。因此指令中"应当何时调用更新工具"的描述,直接决定了 Agent 记忆行为的质量。
守则三:为使用场景调优记忆参数,而非一味求大
文档明确指出:lastMessages、topK、messageRange应当按用例调整,"更大并不总是更好"——过大的上下文窗口会稀释注意力,甚至把无关信息挤进模型视野。
lastMessages:控制带入上下文的最近消息数
- 默认值为
10(见 packages/core/src/memory/memory.ts),即每个新请求默认携带当前线程最近 10 条消息; - 可设为任意正整数,也可设为
false完全禁用会话历史(见 packages/core/src/memory/types.ts); - 源码中消息按页从最新向旧加载,
lastMessages作为页大小上限(见 packages/memory/src/index.ts),并且在未显式传参时优先使用线程配置中的lastMessages(packages/memory/src/index.ts)。
const memory = new Memory({ storage: new LibSQLStore({ url: 'file:../../memory.db' }), options: { lastMessages: 20, // 覆盖默认的 10,把最近 20 条消息带入上下文 }, })semanticRecall.topK:控制向量召回条数
- 默认
topK为4,messageRange默认为{ before: 1, after: 1 }(见 packages/memory/src/index.ts); topK越大召回越多,对复杂主题帮助更大,但可能混入相关性较低的消息、增加 token 开销;SemanticRecall类型定义中对该参数有明确注释:更高的值提供更多上下文,但同时增加 token 用量(见 packages/core/src/memory/types.ts)。
messageRange:控制每条命中的上下文窗口
- 支持单个数字(前后对称)或
{ before, after }对象:messageRange: 2表示每条命中消息前后各带 2 条;messageRange: { before: 1, after: 3 }表示前 1 条、后 3 条;
- 其作用是为匹配到的消息补齐"对话流",帮助模型理解命中消息的上下文。
进阶:scope与filter
语义召回还支持两个常用于调优的选项(见 18-advanced-configuration-semantic-recall.md):
scope:'thread'只搜当前线程,'resource'跨该资源(用户)的所有线程,默认'resource';filter:按消息嵌入时写入的元数据过滤,支持$and、$or、$eq、$ne、$gt、$gte、$lt、$lte、$in、$nin等运算符。注意:过滤器匹配的是消息保存时嵌入的元数据快照,若之后线程元数据变化,旧嵌入会保留旧元数据直到重新保存/索引。
const memory = new Memory({ storage: new LibSQLStore({ url: 'file:../../memory.db' }), vector: new LibSQLVector({ url: 'file:../../vector.db' }), embedder: 'openai/text-embedding-3-small', options: { semanticRecall: { topK: 3, messageRange: { before: 2, after: 1 }, scope: 'resource', filter: { projectId: { $eq: 'project-a' } }, }, }, })调参建议:从默认值起步,用真实对话逐步放大topK/lastMessages,观察响应是否更准确;一旦出现"答非所问"或关键信息被挤掉,就说明上下文已过载,应回退并转而依赖 semantic recall 按需检索。
守则四:正视隐私与安全
记忆系统天然涉及用户数据的持久化,文档要求:
- 向用户透明:明确告知哪些信息会被存储;
- 对敏感信息实施适当的安全措施:结合存储选型(如 10-storage-configuration.md 讨论的各类存储)做访问控制与加密策略。
实践中可以进一步:
- 在指令中约束 Agent不要写入敏感信息(密码、证件号、支付信息等),或写入前先询问用户;
- 利用
scope隔离数据:'resource'让同一用户跨线程共享记忆,'thread'则把记忆隔离在单次会话内,适合隐私敏感场景(见 packages/core/src/memory/types.ts); - 为资源/线程建立清晰的 id 体系,确保记忆归属正确、可审计、可清理。
守则五:系统性测试,覆盖冲突与修正等边界场景
文档要求验证 Agent 在不同场景下的记忆正确性,并专门测试冲突信息与修正这两类边界情况。课程 28-testing-memory-enhanced-agents.md 给出了可直接执行的测试脚本(npm run dev后打开http://localhost:4111/的 playground):
- 记忆主 Agent 测试:分享个人信息("Hi, I'm Taylor. I live in Boston and work as a software engineer.")→ 讨论项目("I'm working on a web application with a deadline next month.")→ 切换话题 → 回到旧话题("Remind me, what was the deadline for my web application?")→ 询问"你对我了解多少";
- 学习助手测试:从"想学 Python"→ 告知视觉学习偏好 → 学习变量与函数 → 切换 Web 开发话题 → 再切回 Python 验证是否还记得"函数怎么讲"。
建议补充的边界用例:
- 冲突信息:先告诉 Agent "我在北京",后改口"我搬到上海了",验证工作记忆是否覆盖旧值而非叠加矛盾数据;
- 修正行为:Agent 记错后用户纠正,验证下次回复不再沿用错误信息;
- 跨会话:新开线程(同一 resourceId),验证姓名、偏好等是否仍然可用;
- 参数边界:
lastMessages: false时确认不再注入任何历史消息,semantic recall 被禁用时确认recall()返回空结果——这两类断言在 packages/memory/src/index.test.ts 的测试中均有覆盖,可作为你编写自身测试的参照。
守则六:用心设计模板结构
工作记忆模板是一份 Markdown 文档,它决定了 Agent"该记什么、记在哪"。文档总结模板的三个作用:
- 引导 Agent 决定追踪哪些信息、如何组织;
- 为跨会话的记忆提供一致的结构;
- 让 Agent 更容易定位并更新某条具体信息。
课程推荐按"分区"组织模板(见 22-custom-working-memory-templates.md):
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] `, }, }除template外,workingMemory还支持:
scope: 'resource' | 'thread':记忆跨线程共享或按线程隔离,默认'resource';schema:以 Zod schema 定义结构化记忆(此时不能同时使用template),源码中SchemaWorkingMemory与TemplateWorkingMemory二选一(见 packages/core/src/memory/types.ts);agentManaged: boolean:主 Agent 是否直接管理工作记忆,当交由 Observational Memory 等其他路径更新时可设为false(默认true);useStateSignals(实验性):以状态信号而非系统消息的形式投递记忆快照,注册的工具名变为setWorkingMemory。
模板设计应与守则一呼应:分区服务于你的业务领域(个人资料、偏好、任务状态),每个字段都应是"会被多次复用"的信息,而不是流水账。
守则七:平衡三类记忆,各司其职
最终,一份成熟的记忆配置是把三类记忆组合起来、让它们互补(见 25-combining-memory-features.md):
// 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' }), embedder: 'openai/text-embedding-3-small', options: { // 1. 会话历史:近期上下文 lastMessages: 20, // 2. 语义召回:按需检索历史相关信息 semanticRecall: { topK: 3, messageRange: { before: 2, after: 1 }, }, // 3. 工作记忆:持久用户信息与状态 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: ## Session State - Current Topic: - Open Questions: - Action Items: `, }, }, }) export const memoryAgent = new Agent({ name: 'MemoryAgent', instructions: ` You are a helpful assistant with advanced memory capabilities. When you learn something important about the user, update your working memory. Always refer to your working memory before asking for information the user has already provided. `, model: 'openai/gpt-5.4', memory, })三类记忆的职责边界可以这样概括:
- Conversation History(
lastMessages):维持"最近说了什么",覆盖连续对话的短程连续性; - Semantic Recall(
topK/messageRange):解决"很久以前提过什么",按语义相似度跨会话召回; - Working Memory(
template/schema):固化"用户是谁、任务到哪一步",用结构化解耦消息内容的变化。
总结:从"能记"到"记得好"
记忆系统的价值不在存储量,而在在正确的时间取回正确的信息。将上述七条守则落地为工程动作:
- 用指令约束写入与读取时机,让 Agent 只记值得记的;
- 从默认参数起步逐步调优,警惕上下文稀释;
- 对敏感场景用
scope: 'thread'隔离、在指令中禁止记录敏感字段; - 用包含冲突与修正场景的测试脚本持续验证;
- 用分区模板 + 三类记忆的组合,构建真正个性化、上下文一致且行为稳定的记忆增强 Agent。
有关记忆配置的完整代码示例与测试方法,可继续翻阅 03-agent-memory 课程目录 中的配置章节,以及 packages/core/src/memory/types.ts 中的类型定义与注释。
【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考