Skip to content

Chapter 10 · Memory: Conversation History ​

Chapter goals: Understand Mastra Memory's thread (thread) and resource (resource) model, and configure persistent conversation memory for Agents.

10.1 The Statelessness Dilemma ​

By default, Agents are stateless — each generate is a fresh session:

typescript
// Behavior without memory
await agent.generate('My name is Xiao Ming');
await agent.generate('What is my name?'); // ❌ "Sorry, you haven't told me your name yet"

The Memory module solves this: it stores conversation history by thread in Storage and自动 injects relevant history into context on each request.

10.2 Two Core Concepts: Thread and Resource ​

ConceptMeaningAnalogy
ResourceLong-term identity of a user/entityUser account
ThreadContainer for a continuous conversationA chat window
text
Resource: user-alice
 ├── Thread: support-monday   (独立 history)
 └── Thread: tech-wednesday   (独立 history)

The same resource can have multiple parallel threads; messages within a thread are strictly time-ordered. Cross-thread long-term preferences belong to resource-level knowledge, handled by the observational memory in the next chapter.

10.3 Configuring and Using Memory ​

bash
npm install @mastra/libsql   # Storage adapter
typescript
// src/mastra/index.ts —— create Memory and attach to Agent
import { Mastra } from '@mastra/core';
import { Memory } from '@mastra/memory';
import { LibSQLStore } from '@mastra/libsql';
import { supportAgent } from './agents/support-agent';

// Persistent backend for conversation history
const store = new LibSQLStore({ url: process.env.LIBSQL_URL ?? 'file:memory.db' });

export const mastra = new Mastra({
  agents: { supportAgent },
  storage: store,
});
typescript
// src/mastra/agents/support-agent.ts —— Agent declares memory enabled
import { Agent } from '@mastra/core/agent';

export const supportAgent = new Agent({
  id: 'support',
  name: 'Support Agent',
  instructions: 'You are a customer support assistant. Remember information the user provides in this session.',
  model: 'openai/gpt-5-mini',
  // Enable memory in defaultOptions and limit injected history count
  memory: {
    options: {
      lastMessages: 20,      // Inject the most recent 20 messages as context
    },
  },
});
typescript
// Call with thread/resource identifiers → auto-load and save history
await supportAgent.generate('My name is Xiao Ming, order #A1024', {
  memory: {
    thread: 'support-monday',   // Session thread ID
    resource: 'user-xiaoming',  // User resource ID
  },
});

// New call, same thread → remembers prior content
const res = await supportAgent.generate('What is my order number?', {
  memory: { thread: 'support-monday', resource: 'user-xiaoming' },
});
console.log(res.text); // ✅ "Your order number is A1024"

10.4 lastMessages and Context Budget ​

lastMessages: N controls how many historical messages are injected per request — the most important cost knob:

ValueEffectRisk
Too small (e.g., 2)Saves tokens, but容易"失忆"Forgets prior agreements
Too large (e.g., 500)Remembers everything, but token cost scales linearlyLong conversation costs spiral

Practice advice: start at 20, supplement with Chapter 11's observational memory for "earlier but important" info.

Thread design advice

Open new threads by "business scenario + time period" (e.g., support-2026w34) to avoid单个 thread growing infinitely; user-level preferences live at the resource dimension.

10.5 Chapter Summary ​

  • Default Agent is stateless; Memory persists history via Storage and auto-injects on requests;
  • Resource = user identity, Thread = single conversation; one resource can hold multiple threads;
  • Pass { memory: { thread, resource } } on each call to auto-read/write history;
  • lastMessages is the balance knob between memory length and cost; start at 20 and adjust as needed.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. In Mastra Memory, what do thread and resource correspond to?

2. What is the necessary condition for two generate calls to share conversation history?

3. What does lastMessages: 20 mean?

4. In a customer support system, should a user's "morning return咨询" and "afternoon tech support" share a thread?

🛠️ Hands-On Exercises ​

  1. Configure Memory for supportAgent; verify "remembers order number" across three consecutive rounds, then switch thread to verify isolation.
  2. Change lastMessages from 20 to 2; test which information is lost on the 3rd round question.
  3. Find the conversation records in Studio's Storage/Threads view and observe the message storage structure.

Next: Chapter 11 · Observational Memory