
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并且在未显式传参时优先使用线程配置中的lastMessagespackages/memory/src/index.ts。const memory new Memory({ storage: new LibSQLStore({ url: file:../../memory.db }), options: { lastMessages: 20, // 覆盖默认的 10把最近 20 条消息带入上下文 }, })semanticRecall.topK控制向量召回条数默认topK为4messageRange默认为{ before: 1, after: 1 }见 packages/memory/src/index.tstopK越大召回越多对复杂主题帮助更大但可能混入相关性较低的消息、增加 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.mdscopethread只搜当前线程resource跨该资源用户的所有线程默认resourcefilter按消息嵌入时写入的元数据过滤支持$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, Im Taylor. I live in Boston and work as a software engineer.→ 讨论项目Im 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.mdoptions: { 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记忆跨线程共享或按线程隔离默认resourceschema以 Zod schema 定义结构化记忆此时不能同时使用template源码中SchemaWorkingMemory与TemplateWorkingMemory二选一见 packages/core/src/memory/types.tsagentManaged: boolean主 Agent 是否直接管理工作记忆当交由 Observational Memory 等其他路径更新时可设为false默认trueuseStateSignals实验性以状态信号而非系统消息的形式投递记忆快照注册的工具名变为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 HistorylastMessages维持最近说了什么覆盖连续对话的短程连续性Semantic RecalltopK/messageRange解决很久以前提过什么按语义相似度跨会话召回Working Memorytemplate/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),仅供参考