Memory Management
Relevant source files
The following files were used as context for generating this wiki page:
- packages/memory/src/index.ts
- packages/core/src/processors/memory/working-memory.ts
- packages/memory/integration-tests-v5/src/working-memory.test.ts
- packages/memory/integration-tests-v5/src/working-memory-additive.test.ts
- examples/memory-per-resource-example/README.md
- packages/agent-builder/src/defaults.ts
- templates/template-pdf-questions/src/mastra/agents/pdf-summarization-agent.ts
The Mastra Memory system provides agents with capabilities for conversation persistence, state management, and contextual recall. It is a core component that allows agents to maintain continuity across interactions. The system is built on a pluggable architecture, allowing developers to integrate various storage backends for message history, vector data, and application state.
Key features include Working Memory, a "scratchpad" for agents to store and update critical information, and Semantic Recall, which uses vector search to retrieve relevant past messages. The primary implementation is the Memory class in the @mastra/memory package, which extends the base MastraMemory class and integrates with storage adapters, vector stores, and embedding models.
Architecture
The Memory system is composed of several key components that work together to provide stateful capabilities to agents. The Memory class is the central orchestrator, relying on external storage, vector, and embedding providers.
This diagram shows the Memory class inheriting from the abstract MastraMemory and its composition of MemoryStorage, VectorStorage, and an Embedder. An Agent uses an instance of MastraMemory.
Sources: packages/memory/src/index.ts:31-39, packages/core/src/processors/memory/working-memory.ts:20-25
Components
| Component | Package | Description |
|---|---|---|
Memory | @mastra/memory | The concrete implementation of the memory system. It manages threads, messages, working memory, and semantic recall. |
MastraMemory | @mastra/core | The abstract base class defining the core memory interface used by agents. |
MemoryStorage | @mastra/core | An interface for pluggable key-value/relational storage backends (e.g., @mastra/libsql, @mastra/pg). Used for storing threads and messages. |
VectorStorage | @mastra/core | An interface for pluggable vector databases (e.g., @mastra/libsql). Used for semantic recall. |
Embedder | ai / @mastra/fastembed | A model that converts text into vector embeddings for semantic search. |
WorkingMemory (Processor) | @mastra/core | An input processor that injects working memory data as a system message. |
SemanticRecall (Processor) | @mastra/core | An input processor that injects semantically relevant past messages into the context. |
Sources: packages/memory/src/index.ts:3-25, packages/core/src/processors/memory/working-memory.ts:27-40, DEVELOPMENT.md:14-22
Core Features
Working Memory
Working Memory acts as a persistent "scratchpad" or short-term memory for an agent. The agent can read from and write to this space to keep track of important facts, user preferences, or evolving context. This is managed via a system prompt and a dedicated updateWorkingMemory tool.
Configuration
Working memory is configured within the Memory constructor's options.
| Option | Type | Description | Default |
|---|---|---|---|
enabled | boolean | Enables or disables the working memory feature. | false |
scope | 'thread' | 'resource' | Determines if memory is per-conversation (thread) or shared across all conversations for a user (resource). | 'resource' |
template | string | A Markdown template for the agent to follow when updating memory. | Default user info template. |
schema | z.ZodObject | JSONSchema7 | A Zod or JSON schema defining the structure of the working memory. The agent will output JSON. | undefined |
version | 'vnext' | Enables an experimental, additive update version of the working memory tool. | undefined |
Sources: packages/memory/src/index.ts:43-53, packages/core/src/processors/memory/working-memory.ts:10-25, examples/memory-per-resource-example/README.md:50-62
How It Works
- System Message Injection: The
WorkingMemoryprocessor retrieves the current working memory data and its template/schema. It formats this into a system instruction that is prepended to the message list sent to the LLM. - Agent Updates: The LLM uses the
updateWorkingMemorytool to save new or changed information. - Data Persistence: The
Memoryclass saves the updated working memory content to the configured storage backend, either in the thread's metadata (threadscope) or in a dedicated resource table (resourcescope).
The diagram below illustrates an agent updating its working memory.
Scopes
threadscope: Memory is isolated to a single conversation thread. It is stored in themetadatafield of the thread record.resourcescope (default): Memory is shared across all threads associated with a singleresourceId(e.g., a user). This allows for persistent user profiles. It is stored in themastra_resourcestable and requires a compatible storage adapter likeLibSQL,PostgreSQL, orUpstash.
Sources: packages/memory/src/index.ts:92-100, examples/memory-per-resource-example/README.md:10-12
Update Strategies
The Memory class provides two main ways to update working memory:
updateWorkingMemory(Standard): This is a full replacement strategy. The agent is expected to provide the entire, updated working memory content in the tool call.__experimental_updateWorkingMemoryVNext: This experimental tool uses a merge/patch strategy. It reads the existing memory, merges the new information, and writes it back. This is more efficient as the agent only needs to provide the changed data. It uses an in-memoryMutexto prevent race conditions during simultaneous updates.
Sources: packages/memory/src/index.ts:400-516, packages/memory/integration-tests-v5/src/working-memory-additive.test.ts:1-7
Semantic Recall
Semantic Recall enhances an agent's memory by finding and injecting relevant past messages from the conversation history, even if they are outside the recent message window. It uses vector embeddings and similarity search.
Configuration
| Option | Type | Description | Default |
|---|---|---|---|
enabled | boolean | Enables or disables semantic recall. | false |
scope | 'thread' | 'resource' | Determines if search is limited to the current thread or all threads for the resource. | 'resource' |
topK | number | The number of most relevant message chunks to retrieve. | 4 |
messageRange | number | {before: number, after: number} | The number of surrounding messages to fetch for context around a recalled message. | {before: 1, after: 1} |
Sources: packages/memory/src/index.ts:153-162, packages/agent-builder/src/defaults.ts:503-505
How It Works
The data flow for saving and recalling messages with semantic recall is as follows:
This diagram shows the two main flows: saving messages with vector embedding and recalling messages with vector search.
Sources: packages/memory/src/index.ts:128-243, packages/memory/src/index.ts:634-733
Methods and Operations
The Memory class provides a comprehensive API for managing conversation state.
Thread Management
| Method | Description |
|---|---|
saveThread | Creates or updates a thread in storage. |
getThreadById | Retrieves a single thread by its ID. |
listThreadsByResourceId | Lists all threads associated with a given resource ID. |
updateThread | Updates a thread's title or metadata. |
deleteThread | Deletes a thread from storage. |
Sources: packages/memory/src/index.ts:278-340
Message Management
| Method | Description |
|---|---|
saveMessages | Saves a batch of messages to storage and, if enabled, creates vector embeddings for semantic recall. |
recall | Retrieves messages from a thread, optionally including semantically similar messages. |
updateMessages | Updates the metadata of one or more messages. |
deleteMessages | Deletes one or more messages from storage by their IDs. |
Sources: packages/memory/src/index.ts:102-243, packages/memory/src/index.ts:634-733, packages/memory/src/index.ts:1102-1149
Example Instantiation
Here is an example of how to instantiate and configure the Memory class for an agent.
import { Agent } from '@mastra/core/agent';
import { LibSQLStore, LibSQLVector } from '@mastra/libsql';
import { Memory } from '@mastra/memory';
import { fastembed } from '@mastra/fastembed';
// Initialize storage and vector stores
const storage = new LibSQLStore({
id: 'my-agent-storage',
url: 'file:../mastra.db',
});
const vector = new LibSQLVector({
id: 'my-agent-vector',
connectionUrl: 'file:../mastra.db',
});
// Configure and instantiate Memory
const memory = new Memory({
storage,
vector,
embedder: fastembed,
options: {
generateTitle: true,
semanticRecall: true, // Enable semantic recall
workingMemory: {
enabled: true, // Enable working memory
scope: 'resource', // Share memory across user's threads
template: `# User Profile
- Name:
- Interests:
- Goals:`,
},
},
});
// Assign memory to an agent
export const myAgent = new Agent({
id: 'my-coding-agent',
// ... other agent config
memory,
});
Sources: templates/template-coding-agent/src/mastra/agents/coding-agent.ts:1-20, 102-114, templates/template-pdf-questions/src/mastra/agents/pdf-summarization-agent.ts:4-11