@mastra/memory 1.0.0-beta.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ # Core API Reference
2
+
3
+ > API reference for core - 2 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: Mastra.getMemory()
9
+
10
+ > Documentation for the `Mastra.getMemory()` method in Mastra, which retrieves a registered memory instance by its registry key.
11
+
12
+ The `.getMemory()` method retrieves a memory instance from the Mastra registry by its key. Memory instances are registered in the Mastra constructor and can be referenced by stored agents.
13
+
14
+ ## Usage example
15
+
16
+ ```typescript
17
+ const memory = mastra.getMemory("conversationMemory");
18
+
19
+ // Use the memory instance
20
+ const thread = await memory.createThread({
21
+ resourceId: "user-123",
22
+ title: "New Conversation",
23
+ });
24
+ ```
25
+
26
+ ## Parameters
27
+
28
+ ## Returns
29
+
30
+ ## Example: Registering and Retrieving Memory
31
+
32
+ ```typescript
33
+ import { Mastra } from "@mastra/core";
34
+ import { Memory } from "@mastra/memory";
35
+ import { LibSQLStore } from "@mastra/libsql";
36
+
37
+ const conversationMemory = new Memory({
38
+ storage: new LibSQLStore({ id: 'conversation-store', url: ":memory:" }),
39
+ });
40
+
41
+ const mastra = new Mastra({
42
+ memory: {
43
+ conversationMemory,
44
+ },
45
+ });
46
+
47
+ // Later, retrieve the memory instance
48
+ const memory = mastra.getMemory("conversationMemory");
49
+ ```
50
+
51
+ ## Related
52
+
53
+ - [Mastra.listMemory()](https://mastra.ai/reference/v1/core/listMemory)
54
+ - [Memory overview](https://mastra.ai/docs/v1/memory/overview)
55
+ - [Agent Memory](https://mastra.ai/docs/v1/agents/agent-memory)
56
+
57
+ ---
58
+
59
+ ## Reference: Mastra.listMemory()
60
+
61
+ > Documentation for the `Mastra.listMemory()` method in Mastra, which returns all registered memory instances.
62
+
63
+ The `.listMemory()` method returns all memory instances registered with the Mastra instance.
64
+
65
+ ## Usage example
66
+
67
+ ```typescript
68
+ const memoryInstances = mastra.listMemory();
69
+
70
+ for (const [key, memory] of Object.entries(memoryInstances)) {
71
+ console.log(`Memory "${key}": ${memory.id}`);
72
+ }
73
+ ```
74
+
75
+ ## Parameters
76
+
77
+ This method takes no parameters.
78
+
79
+ ## Returns
80
+
81
+ ## Example: Checking Registered Memory
82
+
83
+ ```typescript
84
+ import { Mastra } from "@mastra/core";
85
+ import { Memory } from "@mastra/memory";
86
+ import { LibSQLStore } from "@mastra/libsql";
87
+
88
+ const conversationMemory = new Memory({
89
+ id: "conversation-memory",
90
+ storage: new LibSQLStore({ id: 'conversation-store', url: ":memory:" }),
91
+ });
92
+
93
+ const analyticsMemory = new Memory({
94
+ id: "analytics-memory",
95
+ storage: new LibSQLStore({ id: 'analytics-store', url: ":memory:" }),
96
+ });
97
+
98
+ const mastra = new Mastra({
99
+ memory: {
100
+ conversationMemory,
101
+ analyticsMemory,
102
+ },
103
+ });
104
+
105
+ // List all registered memory instances
106
+ const allMemory = mastra.listMemory();
107
+ console.log(Object.keys(allMemory)); // ["conversationMemory", "analyticsMemory"]
108
+ ```
109
+
110
+ ## Related
111
+
112
+ - [Mastra.getMemory()](https://mastra.ai/reference/v1/core/getMemory)
113
+ - [Memory overview](https://mastra.ai/docs/v1/memory/overview)
114
+ - [Agent Memory](https://mastra.ai/docs/v1/agents/agent-memory)
@@ -0,0 +1,76 @@
1
+ > Learn how Mastra
2
+
3
+ # Memory
4
+
5
+ Memory gives your agent coherence across interactions and allows it to improve over time by retaining relevant information from past conversations.
6
+
7
+ Mastra requires a [storage provider](./storage) to persist memory and supports three types:
8
+
9
+ - [**Message history**](https://mastra.ai/docs/v1/memory/message-history) captures recent messages from the current conversation, providing short-term continuity and maintaining dialogue flow.
10
+ - [**Working memory**](https://mastra.ai/docs/v1/memory/working-memory) stores persistent user-specific details such as names, preferences, goals, and other structured data.
11
+ - [**Semantic recall**](https://mastra.ai/docs/v1/memory/semantic-recall) retrieves older messages from past conversations based on semantic relevance. Matches are retrieved using vector search and can include surrounding context for better comprehension.
12
+
13
+ You can enable any combination of these memory types. Mastra assembles the relevant memories into the model’s context window. If the total exceeds the model's token limit, use [memory processors](https://mastra.ai/docs/v1/memory/memory-processors) to trim or filter messages before sending them to the model.
14
+
15
+ ## Getting started
16
+
17
+ Install Mastra's memory module and the storage adapter for your preferred database (see the storage section below):
18
+
19
+ ```bash
20
+ npm install @mastra/memory@beta @mastra/libsql@beta
21
+ ```
22
+
23
+ Add the storage adapter to the main Mastra instance:
24
+
25
+ ```typescript title="src/mastra/index.ts"
26
+ import { Mastra } from "@mastra/core";
27
+ import { LibSQLStore } from "@mastra/libsql";
28
+
29
+ export const mastra = new Mastra({
30
+ storage: new LibSQLStore({
31
+ id: 'mastra-storage',
32
+ url: ":memory:",
33
+ }),
34
+ });
35
+ ```
36
+
37
+ Enable memory by passing a `Memory` instance to your agent:
38
+
39
+ ```typescript title="src/mastra/agents/test-agent.ts"
40
+ import { Memory } from "@mastra/memory";
41
+ import { Agent } from "@mastra/core/agent";
42
+
43
+ export const testAgent = new Agent({
44
+ id: "test-agent",
45
+ memory: new Memory({
46
+ options: {
47
+ lastMessages: 20,
48
+ },
49
+ }),
50
+ });
51
+ ```
52
+ When you send a new message, the model can now "see" the previous 20 messages, which gives it better context for the conversation and leads to more coherent, accurate replies.
53
+
54
+ This example configures basic [message history](https://mastra.ai/docs/v1/memory/message-history). You can also enable [working memory](https://mastra.ai/docs/v1/memory/working-memory) and [semantic recall](https://mastra.ai/docs/v1/memory/semantic-recall) by passing additional options to `Memory`.
55
+
56
+ ## Storage
57
+
58
+ Before enabling memory, you must first configure a storage adapter. Mastra supports multiple database providers including PostgreSQL, MongoDB, libSQL, and more.
59
+
60
+ Storage can be configured at the instance level (shared across all agents) or at the agent level (dedicated per agent). You can also use different databases for storage and vector operations.
61
+
62
+ See the [Storage](https://mastra.ai/docs/v1/memory/storage) documentation for configuration options, supported providers, and examples.
63
+
64
+ ## Debugging memory
65
+
66
+ When tracing is enabled, you can inspect exactly which messages the agent uses for context in each request. The trace output shows all memory included in the agent's context window - both recent message history and messages recalled via semantic recall.
67
+
68
+ This visibility helps you understand why an agent made specific decisions and verify that memory retrieval is working as expected.
69
+
70
+ For more details on enabling and configuring tracing, see [Tracing](https://mastra.ai/docs/v1/observability/tracing/overview).
71
+
72
+ ## Next Steps
73
+
74
+ - Learn more about [Storage](https://mastra.ai/docs/v1/memory/storage) providers and configuration options
75
+ - Add [Message History](https://mastra.ai/docs/v1/memory/message-history), [Working Memory](https://mastra.ai/docs/v1/memory/working-memory), or [Semantic Recall](https://mastra.ai/docs/v1/memory/semantic-recall)
76
+ - Visit [Memory configuration reference](https://mastra.ai/reference/v1/memory/memory-class) for all available options
@@ -0,0 +1,233 @@
1
+ > Configure storage for Mastra
2
+
3
+ # Storage
4
+
5
+ For Mastra to remember previous interactions, you must configure a storage adapter. Mastra is designed to work with your preferred database provider - choose from the [supported providers](#supported-providers) and pass it to your Mastra instance.
6
+
7
+ ```typescript title="src/mastra/index.ts"
8
+ import { Mastra } from "@mastra/core";
9
+ import { LibSQLStore } from "@mastra/libsql";
10
+
11
+ export const mastra = new Mastra({
12
+ storage: new LibSQLStore({
13
+ id: 'mastra-storage',
14
+ url: "file:./mastra.db",
15
+ }),
16
+ });
17
+ ```
18
+ On first interaction, Mastra automatically creates the necessary tables following the [core schema](https://mastra.ai/reference/v1/storage/overview#core-schema). This includes tables for messages, threads, resources, workflows, traces, and evaluation datasets.
19
+
20
+ ## Supported providers
21
+
22
+ Each provider page includes installation instructions, configuration parameters, and usage examples:
23
+
24
+ - [libSQL Storage](https://mastra.ai/reference/v1/storage/libsql)
25
+ - [PostgreSQL Storage](https://mastra.ai/reference/v1/storage/postgresql)
26
+ - [MongoDB Storage](https://mastra.ai/reference/v1/storage/mongodb)
27
+ - [Upstash Storage](https://mastra.ai/reference/v1/storage/upstash)
28
+ - [Cloudflare D1](https://mastra.ai/reference/v1/storage/cloudflare-d1)
29
+ - [Cloudflare Durable Objects](https://mastra.ai/reference/v1/storage/cloudflare)
30
+ - [Convex](https://mastra.ai/reference/v1/storage/convex)
31
+ - [DynamoDB](https://mastra.ai/reference/v1/storage/dynamodb)
32
+ - [LanceDB](https://mastra.ai/reference/v1/storage/lance)
33
+ - [Microsoft SQL Server](https://mastra.ai/reference/v1/storage/mssql)
34
+
35
+ > **Note:**
36
+ libSQL is the easiest way to get started because it doesn’t require running a separate database server
37
+
38
+ ## Configuration scope
39
+
40
+ You can configure storage at two different scopes:
41
+
42
+ ### Instance-level storage
43
+
44
+ Add storage to your Mastra instance so all agents, workflows, observability traces and scores share the same memory provider:
45
+
46
+ ```typescript
47
+ import { Mastra } from "@mastra/core";
48
+ import { PostgresStore } from "@mastra/pg";
49
+
50
+ export const mastra = new Mastra({
51
+ storage: new PostgresStore({
52
+ id: 'mastra-storage',
53
+ connectionString: process.env.DATABASE_URL,
54
+ }),
55
+ });
56
+
57
+ // All agents automatically use this storage
58
+ const agent1 = new Agent({ id: "agent-1", memory: new Memory() });
59
+ const agent2 = new Agent({ id: "agent-2", memory: new Memory() });
60
+ ```
61
+
62
+ This is useful when all primitives share the same storage backend and have similar performance, scaling, and operational requirements.
63
+
64
+ #### Composite storage
65
+
66
+ Add storage to your Mastra instance using `MastraCompositeStore` and configure individual storage domains to use different storage providers.
67
+
68
+ ```typescript title="src/mastra/index.ts"
69
+ import { Mastra } from "@mastra/core";
70
+ import { MastraCompositeStore } from "@mastra/core/storage";
71
+ import { MemoryLibSQL } from "@mastra/libsql";
72
+ import { WorkflowsPG } from "@mastra/pg";
73
+ import { ObservabilityStorageClickhouse } from "@mastra/clickhouse";
74
+
75
+ export const mastra = new Mastra({
76
+ storage: new MastraCompositeStore({
77
+ id: "composite",
78
+ domains: {
79
+ memory: new MemoryLibSQL({ url: "file:./memory.db" }),
80
+ workflows: new WorkflowsPG({ connectionString: process.env.DATABASE_URL }),
81
+ observability: new ObservabilityStorageClickhouse({
82
+ url: process.env.CLICKHOUSE_URL,
83
+ username: process.env.CLICKHOUSE_USERNAME,
84
+ password: process.env.CLICKHOUSE_PASSWORD,
85
+ }),
86
+ },
87
+ }),
88
+ });
89
+ ```
90
+
91
+ This is useful when different types of data have different performance or operational requirements, such as low-latency storage for memory, durable storage for workflows, and high-throughput storage for observability.
92
+
93
+ > **Note:**
94
+ See [Storage Domains](https://mastra.ai/reference/v1/storage/composite#storage-domains) for more information.
95
+
96
+ ### Agent-level storage
97
+
98
+ Agent-level storage overrides storage configured at the instance-level. Add storage to a specific agent when you need data boundaries or compliance requirements:
99
+
100
+ ```typescript title="src/mastra/agents/memory-agent.ts"
101
+ import { Agent } from "@mastra/core/agent";
102
+ import { Memory } from "@mastra/memory";
103
+ import { PostgresStore } from "@mastra/pg";
104
+
105
+ export const agent = new Agent({
106
+ id: "agent",
107
+ memory: new Memory({
108
+ storage: new PostgresStore({
109
+ id: 'agent-storage',
110
+ connectionString: process.env.AGENT_DATABASE_URL,
111
+ }),
112
+ }),
113
+ });
114
+ ```
115
+
116
+ This is useful when different agents need to store data in separate databases for security, compliance, or organizational reasons.
117
+
118
+ > **Mastra Cloud Store limitation**
119
+ Agent-level storage is not supported when using [Mastra Cloud Store](https://mastra.ai/docs/v1/mastra-cloud/deployment#using-mastra-cloud-store). If you use Mastra Cloud Store, configure storage on the Mastra instance instead. This limitation does not apply if you bring your own database.
120
+
121
+ ## Threads and resources
122
+
123
+ Mastra organizes memory into threads using two identifiers:
124
+
125
+ - **Thread**: A conversation session containing a sequence of messages (e.g., `convo_123`)
126
+ - **Resource**: An identifier for the entity the thread belongs to, typically a user (e.g., `user_123`)
127
+
128
+ Both identifiers are required for agents to store and recall information:
129
+
130
+ ```typescript
131
+ const stream = await agent.stream("message for agent", {
132
+ memory: {
133
+ thread: "convo_123",
134
+ resource: "user_123",
135
+ },
136
+ });
137
+ ```
138
+
139
+ > **Note:**
140
+ [Studio](https://mastra.ai/docs/v1/getting-started/studio) automatically generates a thread and resource ID for you. Remember to to pass these explicitly when calling `stream` or `generate` yourself.
141
+
142
+ ### Thread and resource relationship
143
+
144
+ Each thread has an owner (its `resourceId`) that is set when the thread is created and cannot be changed. When you query a thread, you must use the correct owner's resource ID. Attempting to query a thread with a different resource ID will result in an error:
145
+
146
+ ```text
147
+ Thread with id <thread_id> is for resource with id <resource_a>
148
+ but resource <resource_b> was queried
149
+ ```
150
+
151
+ Note that while each thread has one owner, messages within that thread can have different `resourceId` values. This is used for message attribution and filtering (e.g., distinguishing between different agents in a multi-agent system, or filtering messages for analytics).
152
+
153
+ **Security:** Memory is a storage layer, not an authorization layer. Your application must implement access control before calling memory APIs. The `resourceId` parameter controls both validation and filtering - provide it to validate ownership and filter messages, or omit it for server-side access without validation.
154
+
155
+ To avoid accidentally reusing thread IDs across different owners, use UUIDs: `crypto.randomUUID()`
156
+
157
+ ### Thread title generation
158
+
159
+ Mastra can automatically generate descriptive thread titles based on the user's first message.
160
+
161
+ Use this option when implementing a ChatGPT-style chat interface to render a title alongside each thread in the conversation list (for example, in a sidebar) derived from the thread’s initial user message.
162
+
163
+ ```typescript
164
+ export const testAgent = new Agent({
165
+ id: "test-agent",
166
+ memory: new Memory({
167
+ options: {
168
+ generateTitle: true,
169
+ },
170
+ }),
171
+ });
172
+ ```
173
+
174
+ Title generation runs asynchronously after the agent responds and does not affect response time.
175
+
176
+ To optimize cost or behavior, provide a smaller `model` and custom `instructions`:
177
+
178
+ ```typescript
179
+ export const testAgent = new Agent({
180
+ id: "test-agent",
181
+ memory: new Memory({
182
+ options: {
183
+ generateTitle: {
184
+ model: "openai/gpt-4o-mini",
185
+ instructions: "Generate a concise title based on the user's first message",
186
+ },
187
+ },
188
+ }),
189
+ });
190
+ ```
191
+
192
+ ## Semantic recall
193
+
194
+ Semantic recall uses vector embeddings to retrieve relevant past messages based on meaning rather than recency. This requires a vector database instance, which can be configured at the instance or agent level.
195
+
196
+ The vector database doesn't have to be the same as your storage provider. For example, you might use PostgreSQL for storage and Pinecone for vectors:
197
+
198
+ ```typescript
199
+ import { Mastra } from "@mastra/core";
200
+ import { Agent } from "@mastra/core/agent";
201
+ import { Memory } from "@mastra/memory";
202
+ import { PostgresStore } from "@mastra/pg";
203
+ import { PineconeVector } from "@mastra/pinecone";
204
+
205
+ // Instance-level vector configuration
206
+ export const mastra = new Mastra({
207
+ storage: new PostgresStore({
208
+ id: 'mastra-storage',
209
+ connectionString: process.env.DATABASE_URL,
210
+ }),
211
+ });
212
+
213
+ // Agent-level vector configuration
214
+ export const agent = new Agent({
215
+ id: "agent",
216
+ memory: new Memory({
217
+ vector: new PineconeVector({
218
+ id: 'agent-vector',
219
+ apiKey: process.env.PINECONE_API_KEY,
220
+ }),
221
+ options: {
222
+ semanticRecall: {
223
+ topK: 5,
224
+ messageRange: 2,
225
+ },
226
+ },
227
+ }),
228
+ });
229
+ ```
230
+
231
+ We support all popular vector providers including [Pinecone](https://mastra.ai/reference/v1/vectors/pinecone), [Chroma](https://mastra.ai/reference/v1/vectors/chroma), [Qdrant](https://mastra.ai/reference/v1/vectors/qdrant), and many more.
232
+
233
+ For more information on configuring semantic recall, see the [Semantic Recall](./semantic-recall) documentation.