Chapter 11 · Observational Memory
Chapter goals: Understand the principle of observational memory (Observer/Reflector background proxies), learn to configure long-term memory, and make Agents remember user facts across sessions.
11.1 Why Observational Memory Is Needed
Plain conversation history is "word-for-word recording": the more messages, the more bloated the context, the higher the token cost, and early information gets truncated and lost. Mastra's Observational Memory (OM, @mastra/memory@1.1.0+) solves this with a different approach:
- Two background proxies, Observer and Reflector,持续旁观对话;
- They maintain a high-density observation log — distilled facts like "the user prefers blue" or "the project uses pnpm not npm";
- When history grows past the activation threshold, 原始旧消息被观察日志替换, keeping context compact without losing key info.
Difference from Working Memory
Working Memory is an explicit "notepad" — the model读写 fixed-format content per instructions. Observational Memory is automatic, continuously-running long-term memory pipeline — no user prompt needed.
11.2 Minimal Working Configuration
OM requires persistent storage. The following script creates a local LibSQL database and enables observational memory:
// src/observational-memory.ts
import { Agent } from '@mastra/core/agent'
import { LibSQLStore } from '@mastra/libsql'
import { Memory } from '@mastra/memory'
const memory = new Memory({
// Both observation log and history messages need persistence
storage: new LibSQLStore({
id: 'memory-storage',
url: 'file:./memory.db',
}),
options: {
// Specify the model for background proxy refinement; true uses the default model
observationalMemory: {
model: 'openai/gpt-5-mini',
},
},
})
export const agent = new Agent({
id: 'memory-agent',
name: 'Memory Agent',
instructions: 'You are a helpful assistant.',
model: 'openai/gpt-5-mini',
memory,
})11.3 Cross-Call Memory Verification
resource identifies the user entity; thread identifies a conversation. Reusing both continues the same context:
// src/demo.ts
import { agent } from './observational-memory'
const memoryOptions = { resource: 'user-123', thread: 'conversation-123' }
// Round 1: tell a personal fact
const first = await agent.generate(
'Remember: my favorite color is blue.',
{ memory: memoryOptions },
)
console.log(first.text)
// Round 2 (even a新对话 after process restart): the model recalls the fact
const second = await agent.generate(
'What is my favorite color?',
{ memory: memoryOptions },
)
console.log(second.text) // → "Your favorite color is blue."11.4 Mounting Storage on the Mastra Instance
In production projects, it's recommended to配置 storage on the Mastra instance so all Agents share:
// src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { LibSQLStore } from '@mastra/libsql'
export const mastra = new Mastra({
// Global default storage: memory / workflow snapshots / trace data share this
storage: new LibSQLStore({ url: 'file:./mastra.db' }),
agents: { memoryAgent: agent },
})11.5 Checking Memory State
When debugging记忆 issues, read threads and resources directly from storage:
// src/check-memory.ts —— list all conversation threads for a user
const memory = agent.memory!
const threads = await memory.getThreadsByResourceId({
resource: 'user-123',
})
for (const t of threads) {
console.log(`thread=${t.id} title=${t.title} created ${t.createdAt}`)
}11.6 Usage Notes
- OM consumes extra background LLM calls (Observer/Reflector); a cheap小 model suffices;
- Activation thresholds are configurable: how long history before triggering compression — balance cost vs. consistency;
- Sensitive信息会被写进观察日志 — do脱敏 at the Processor layer for compliance scenarios.
11.7 Chapter Summary
- Observational Memory uses Observer/Reflector background proxies to自动 distill long-term记忆;
- Persistent storage provider must be configured for cross-session生效;
resource+thread定位 user and conversation; old messages are replaced by observation logs past the threshold;- Background refinement has extra token cost; use a cheap小 model for OM.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. In Observational Memory, who is responsible for refining and maintaining the observation log?
2. What is the necessary prerequisite for enabling Observational Memory?
3. In the memory options passed to generate(), what do resource and thread分别代表?
4. Regarding the cost of observational memory, which statement is correct?
🛠️ Hands-On Exercises
- Enable OM; teach the Agent your name and profession across two rounds; restart the process and ask if it remembers.
- Switch
observationalMemory.modelto a cheaper model; compare记忆质量差异. - Create two不同 threads for the same resource; verify facts remembered in conversation A are召回able in conversation B.