Mastra 为记忆系统推出 Memory Hooks
Introducing Memory Hooks | Mastra Blog
Mastra 的记忆系统新增 Memory Hooks,可观察 observation 与 reflection 循环,或修改 Observer 和 Reflector 看到与存储的内容。钩子分两类:生命周期钩子(onObservationStart、onObservationEnd、onReflectionStart、onReflectionEnd)用于外部上报,如按循环记录 token 用量以发现成本飙升;转换钩子(beforeObservation、afterObservation、beforeReflection、afterReflection)可拦截并修改记忆数据,如剔除噪声工具输出、内部推理或脱敏密钥与 PII。同时发布的 skillResultRedactor() 会用占位符替换 Skill 的完整文件内容,避免 Observer 每次看到,但智能体仍记得该技能。
正文
当前显示原文,中文全文译文尚未就绪。
You can now add hooks to Mastra's memory system, letting you watch observations and reflections, or change what the Observer and Reflector see and store.
There are two types of hooks:
Lifecycle hooks (onObservationStart, onObservationEnd, onReflectionStart, onReflectionEnd): These let you report on a cycle externally, e.g. catch a cost spike by logging token usage per cycle, or trace why an agent has forgotten something; Transform hooks (beforeObservation, afterObservation, beforeReflection, afterReflection): These let you intercept and modify the actual memory data. You can pare/remove noisy tool output, internal reasoning or redact secrets and PII
Before hooks, observational memory didn't give levers to affect what happened during an observation or reflection cycle (other than filtering messages before they reached memory). Now the hooks sit inside the cycle.
We also shipped skillResultRedactor(), a ready-made version of a transform hook. When an agent uses a Skill, the tool result contains the skill's entire file contents. The Observer sees it every time. To avoid that, the redactor replaces the content with a placeholder. The agent still remembers the skill.
Install @mastra/memory and a storage adapter. The storage adapter is required for Observational Memory. Set it up either on the Memory instance or the main Mastra instance:
Create the agent
Create an agent and configure memory:
Lifecycle hooks
Define lifecycle hooks. They can fire at the start and end of every cycle. This example logs when a cycle starts, and what it costs when it ends:
Transform hooks
Define transform hooks. This example strips a bulky tool result before the Observer ever sees it:
Transform hooks are always awaited, on every path: manual observe()/reflect(), turn-synchronous observation, and async buffering. Returning void from any of them passes the input through unchanged.
For more information and full configuration options, see:
Observational memory hooks; Redact skill results; Observational Memory overview