@mastra/libsql 1.6.1-alpha.0 → 1.6.2-alpha.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.
- package/CHANGELOG.md +22 -0
- package/dist/docs/SKILL.md +50 -0
- package/dist/docs/assets/SOURCE_MAP.json +6 -0
- package/dist/docs/references/docs-agents-agent-approval.md +558 -0
- package/dist/docs/references/docs-agents-agent-memory.md +209 -0
- package/dist/docs/references/docs-agents-network-approval.md +275 -0
- package/dist/docs/references/docs-agents-networks.md +299 -0
- package/dist/docs/references/docs-memory-memory-processors.md +314 -0
- package/dist/docs/references/docs-memory-message-history.md +260 -0
- package/dist/docs/references/docs-memory-overview.md +45 -0
- package/dist/docs/references/docs-memory-semantic-recall.md +272 -0
- package/dist/docs/references/docs-memory-storage.md +261 -0
- package/dist/docs/references/docs-memory-working-memory.md +400 -0
- package/dist/docs/references/docs-observability-overview.md +70 -0
- package/dist/docs/references/docs-observability-tracing-exporters-default.md +209 -0
- package/dist/docs/references/docs-rag-retrieval.md +515 -0
- package/dist/docs/references/docs-workflows-snapshots.md +238 -0
- package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +140 -0
- package/dist/docs/references/reference-core-getMemory.md +50 -0
- package/dist/docs/references/reference-core-listMemory.md +56 -0
- package/dist/docs/references/reference-core-mastra-class.md +66 -0
- package/dist/docs/references/reference-memory-memory-class.md +147 -0
- package/dist/docs/references/reference-storage-composite.md +235 -0
- package/dist/docs/references/reference-storage-dynamodb.md +282 -0
- package/dist/docs/references/reference-storage-libsql.md +135 -0
- package/dist/docs/references/reference-vectors-libsql.md +305 -0
- package/dist/index.cjs +14 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +14 -3
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/vector/index.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
# Storage
|
|
2
|
+
|
|
3
|
+
For agents to remember previous interactions, Mastra needs a database. Use a storage adapter for one of the [supported databases](#supported-providers) and pass it to your Mastra instance.
|
|
4
|
+
|
|
5
|
+
```typescript
|
|
6
|
+
import { Mastra } from '@mastra/core'
|
|
7
|
+
import { LibSQLStore } from '@mastra/libsql'
|
|
8
|
+
|
|
9
|
+
export const mastra = new Mastra({
|
|
10
|
+
storage: new LibSQLStore({
|
|
11
|
+
id: 'mastra-storage',
|
|
12
|
+
url: 'file:./mastra.db',
|
|
13
|
+
}),
|
|
14
|
+
})
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
> **Sharing the database with Mastra Studio:** When running `mastra dev` alongside your application (e.g., Next.js), use an absolute path to ensure both processes access the same database:
|
|
18
|
+
>
|
|
19
|
+
> ```typescript
|
|
20
|
+
> url: 'file:/absolute/path/to/your/project/mastra.db'
|
|
21
|
+
> ```
|
|
22
|
+
>
|
|
23
|
+
> Relative paths like `file:./mastra.db` resolve based on each process's working directory, which may differ.
|
|
24
|
+
|
|
25
|
+
This configures instance-level storage, which all agents share by default. You can also configure [agent-level storage](#agent-level-storage) for isolated data boundaries.
|
|
26
|
+
|
|
27
|
+
Mastra automatically creates the necessary tables on first interaction. See the [core schema](https://mastra.ai/reference/storage/overview) for details on what gets created, including tables for messages, threads, resources, workflows, traces, and evaluation datasets.
|
|
28
|
+
|
|
29
|
+
## Supported providers
|
|
30
|
+
|
|
31
|
+
Each provider page includes installation instructions, configuration parameters, and usage examples:
|
|
32
|
+
|
|
33
|
+
- [libSQL](https://mastra.ai/reference/storage/libsql)
|
|
34
|
+
- [PostgreSQL](https://mastra.ai/reference/storage/postgresql)
|
|
35
|
+
- [MongoDB](https://mastra.ai/reference/storage/mongodb)
|
|
36
|
+
- [Upstash](https://mastra.ai/reference/storage/upstash)
|
|
37
|
+
- [Cloudflare D1](https://mastra.ai/reference/storage/cloudflare-d1)
|
|
38
|
+
- [Cloudflare Durable Objects](https://mastra.ai/reference/storage/cloudflare)
|
|
39
|
+
- [Convex](https://mastra.ai/reference/storage/convex)
|
|
40
|
+
- [DynamoDB](https://mastra.ai/reference/storage/dynamodb)
|
|
41
|
+
- [LanceDB](https://mastra.ai/reference/storage/lance)
|
|
42
|
+
- [Microsoft SQL Server](https://mastra.ai/reference/storage/mssql)
|
|
43
|
+
|
|
44
|
+
> **Tip:** libSQL is the easiest way to get started because it doesn’t require running a separate database server.
|
|
45
|
+
|
|
46
|
+
## Configuration scope
|
|
47
|
+
|
|
48
|
+
Storage can be configured at the instance level (shared by all agents) or at the agent level (isolated to a specific agent).
|
|
49
|
+
|
|
50
|
+
### Instance-level storage
|
|
51
|
+
|
|
52
|
+
Add storage to your Mastra instance so all agents, workflows, observability traces and scores share the same memory provider:
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
import { Mastra } from '@mastra/core'
|
|
56
|
+
import { PostgresStore } from '@mastra/pg'
|
|
57
|
+
|
|
58
|
+
export const mastra = new Mastra({
|
|
59
|
+
storage: new PostgresStore({
|
|
60
|
+
id: 'mastra-storage',
|
|
61
|
+
connectionString: process.env.DATABASE_URL,
|
|
62
|
+
}),
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
// Both agents inherit storage from the Mastra instance above
|
|
66
|
+
const agent1 = new Agent({ id: 'agent-1', memory: new Memory() })
|
|
67
|
+
const agent2 = new Agent({ id: 'agent-2', memory: new Memory() })
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
This is useful when all primitives share the same storage backend and have similar performance, scaling, and operational requirements.
|
|
71
|
+
|
|
72
|
+
#### Composite storage
|
|
73
|
+
|
|
74
|
+
[Composite storage](https://mastra.ai/reference/storage/composite) is an alternative way to configure instance-level storage. Use `MastraCompositeStore` to set the `memory` domain (and any other [domains](https://mastra.ai/reference/storage/composite) you need) to different storage providers.
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { Mastra } from '@mastra/core'
|
|
78
|
+
import { MastraCompositeStore } from '@mastra/core/storage'
|
|
79
|
+
import { MemoryLibSQL } from '@mastra/libsql'
|
|
80
|
+
import { WorkflowsPG } from '@mastra/pg'
|
|
81
|
+
import { ObservabilityStorageClickhouse } from '@mastra/clickhouse'
|
|
82
|
+
|
|
83
|
+
export const mastra = new Mastra({
|
|
84
|
+
storage: new MastraCompositeStore({
|
|
85
|
+
id: 'composite',
|
|
86
|
+
domains: {
|
|
87
|
+
memory: new MemoryLibSQL({ url: 'file:./memory.db' }),
|
|
88
|
+
workflows: new WorkflowsPG({ connectionString: process.env.DATABASE_URL }),
|
|
89
|
+
observability: new ObservabilityStorageClickhouse({
|
|
90
|
+
url: process.env.CLICKHOUSE_URL,
|
|
91
|
+
username: process.env.CLICKHOUSE_USERNAME,
|
|
92
|
+
password: process.env.CLICKHOUSE_PASSWORD,
|
|
93
|
+
}),
|
|
94
|
+
},
|
|
95
|
+
}),
|
|
96
|
+
})
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
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.
|
|
100
|
+
|
|
101
|
+
### Agent-level storage
|
|
102
|
+
|
|
103
|
+
Agent-level storage overrides storage configured at the instance level. Add storage to a specific agent when you need data boundaries or compliance requirements:
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
import { Agent } from '@mastra/core/agent'
|
|
107
|
+
import { Memory } from '@mastra/memory'
|
|
108
|
+
import { PostgresStore } from '@mastra/pg'
|
|
109
|
+
|
|
110
|
+
export const agent = new Agent({
|
|
111
|
+
id: 'agent',
|
|
112
|
+
memory: new Memory({
|
|
113
|
+
storage: new PostgresStore({
|
|
114
|
+
id: 'agent-storage',
|
|
115
|
+
connectionString: process.env.AGENT_DATABASE_URL,
|
|
116
|
+
}),
|
|
117
|
+
}),
|
|
118
|
+
})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
> **Warning:** [Mastra Cloud Store](https://mastra.ai/docs/mastra-cloud/deployment) doesn't support agent-level storage.
|
|
122
|
+
|
|
123
|
+
## Threads and resources
|
|
124
|
+
|
|
125
|
+
Mastra organizes conversations using two identifiers:
|
|
126
|
+
|
|
127
|
+
- **Thread** - a conversation session containing a sequence of messages.
|
|
128
|
+
- **Resource** - the entity that owns the thread, such as a user, organization, project, or any other domain entity in your application.
|
|
129
|
+
|
|
130
|
+
Both identifiers are required for agents to store information:
|
|
131
|
+
|
|
132
|
+
**Generate**:
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
const response = await agent.generate('hello', {
|
|
136
|
+
memory: {
|
|
137
|
+
thread: 'conversation-abc-123',
|
|
138
|
+
resource: 'user_123',
|
|
139
|
+
},
|
|
140
|
+
})
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
**Stream**:
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
const stream = await agent.stream('hello', {
|
|
147
|
+
memory: {
|
|
148
|
+
thread: 'conversation-abc-123',
|
|
149
|
+
resource: 'user_123',
|
|
150
|
+
},
|
|
151
|
+
})
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
> **Note:** [Studio](https://mastra.ai/docs/getting-started/studio) automatically generates a thread and resource ID for you. When calling `stream()` or `generate()` yourself, remember to provide these identifiers explicitly.
|
|
155
|
+
|
|
156
|
+
### Thread title generation
|
|
157
|
+
|
|
158
|
+
Mastra can automatically generate descriptive thread titles based on the user's first message when `generateTitle` is enabled.
|
|
159
|
+
|
|
160
|
+
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.
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
export const agent = new Agent({
|
|
164
|
+
id: 'agent',
|
|
165
|
+
memory: new Memory({
|
|
166
|
+
options: {
|
|
167
|
+
generateTitle: true,
|
|
168
|
+
},
|
|
169
|
+
}),
|
|
170
|
+
})
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Title generation runs asynchronously after the agent responds and does not affect response time.
|
|
174
|
+
|
|
175
|
+
To optimize cost or behavior, provide a smaller [`model`](https://mastra.ai/models) and custom `instructions`:
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
export const agent = new Agent({
|
|
179
|
+
id: 'agent',
|
|
180
|
+
memory: new Memory({
|
|
181
|
+
options: {
|
|
182
|
+
generateTitle: {
|
|
183
|
+
model: 'openai/gpt-4o-mini',
|
|
184
|
+
instructions: 'Generate a 1 word title',
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
}),
|
|
188
|
+
})
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Semantic recall
|
|
192
|
+
|
|
193
|
+
Semantic recall has different storage requirements - it needs a vector database in addition to the standard storage adapter. See [Semantic recall](https://mastra.ai/docs/memory/semantic-recall) for setup and supported vector providers.
|
|
194
|
+
|
|
195
|
+
## Handling large attachments
|
|
196
|
+
|
|
197
|
+
Some storage providers enforce record size limits that base64-encoded file attachments (such as images) can exceed:
|
|
198
|
+
|
|
199
|
+
| Provider | Record size limit |
|
|
200
|
+
| ------------------------------------------------------------------ | ----------------- |
|
|
201
|
+
| [DynamoDB](https://mastra.ai/reference/storage/dynamodb) | 400 KB |
|
|
202
|
+
| [Convex](https://mastra.ai/reference/storage/convex) | 1 MiB |
|
|
203
|
+
| [Cloudflare D1](https://mastra.ai/reference/storage/cloudflare-d1) | 1 MiB |
|
|
204
|
+
|
|
205
|
+
PostgreSQL, MongoDB, and libSQL have higher limits and are generally unaffected.
|
|
206
|
+
|
|
207
|
+
To avoid this, use an input processor to upload attachments to external storage (S3, R2, GCS, [Convex file storage](https://docs.convex.dev/file-storage), etc.) and replace them with URL references before persistence.
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
import type { Processor } from '@mastra/core/processors'
|
|
211
|
+
import type { MastraDBMessage } from '@mastra/core/memory'
|
|
212
|
+
|
|
213
|
+
export class AttachmentUploader implements Processor {
|
|
214
|
+
id = 'attachment-uploader'
|
|
215
|
+
|
|
216
|
+
async processInput({ messages }: { messages: MastraDBMessage[] }) {
|
|
217
|
+
return Promise.all(messages.map(msg => this.processMessage(msg)))
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async processMessage(msg: MastraDBMessage) {
|
|
221
|
+
const attachments = msg.content.experimental_attachments
|
|
222
|
+
if (!attachments?.length) return msg
|
|
223
|
+
|
|
224
|
+
const uploaded = await Promise.all(
|
|
225
|
+
attachments.map(async att => {
|
|
226
|
+
// Skip if already a URL
|
|
227
|
+
if (!att.url?.startsWith('data:')) return att
|
|
228
|
+
|
|
229
|
+
// Upload base64 data and replace with URL
|
|
230
|
+
const url = await this.upload(att.url, att.contentType)
|
|
231
|
+
return { ...att, url }
|
|
232
|
+
}),
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
return { ...msg, content: { ...msg.content, experimental_attachments: uploaded } }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async upload(dataUri: string, contentType?: string): Promise<string> {
|
|
239
|
+
const base64 = dataUri.split(',')[1]
|
|
240
|
+
const buffer = Buffer.from(base64, 'base64')
|
|
241
|
+
|
|
242
|
+
// Replace with your storage provider (S3, R2, GCS, Convex, etc.)
|
|
243
|
+
// return await s3.upload(buffer, contentType);
|
|
244
|
+
throw new Error('Implement upload() with your storage provider')
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Use the processor with your agent:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
import { Agent } from '@mastra/core/agent'
|
|
253
|
+
import { Memory } from '@mastra/memory'
|
|
254
|
+
import { AttachmentUploader } from './processors/attachment-uploader'
|
|
255
|
+
|
|
256
|
+
const agent = new Agent({
|
|
257
|
+
id: 'my-agent',
|
|
258
|
+
memory: new Memory({ storage: yourStorage }),
|
|
259
|
+
inputProcessors: [new AttachmentUploader()],
|
|
260
|
+
})
|
|
261
|
+
```
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
# Working Memory
|
|
2
|
+
|
|
3
|
+
While [message history](https://mastra.ai/docs/memory/message-history) and [semantic recall](https://mastra.ai/docs/memory/semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
|
|
4
|
+
|
|
5
|
+
Think of it as the agent's active thoughts or scratchpad – the key information they keep available about the user or task. It's similar to how a person would naturally remember someone's name, preferences, or important details during a conversation.
|
|
6
|
+
|
|
7
|
+
This is useful for maintaining ongoing state that's always relevant and should always be available to the agent.
|
|
8
|
+
|
|
9
|
+
Working memory can persist at two different scopes:
|
|
10
|
+
|
|
11
|
+
- **Resource-scoped** (default): Memory persists across all conversation threads for the same user
|
|
12
|
+
- **Thread-scoped**: Memory is isolated per conversation thread
|
|
13
|
+
|
|
14
|
+
**Important:** Switching between scopes means the agent won't see memory from the other scope - thread-scoped memory is completely separate from resource-scoped memory.
|
|
15
|
+
|
|
16
|
+
## Quick Start
|
|
17
|
+
|
|
18
|
+
Here's a minimal example of setting up an agent with working memory:
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { Agent } from '@mastra/core/agent'
|
|
22
|
+
import { Memory } from '@mastra/memory'
|
|
23
|
+
|
|
24
|
+
// Create agent with working memory enabled
|
|
25
|
+
const agent = new Agent({
|
|
26
|
+
id: 'personal-assistant',
|
|
27
|
+
name: 'PersonalAssistant',
|
|
28
|
+
instructions: 'You are a helpful personal assistant.',
|
|
29
|
+
model: 'openai/gpt-5.1',
|
|
30
|
+
memory: new Memory({
|
|
31
|
+
options: {
|
|
32
|
+
workingMemory: {
|
|
33
|
+
enabled: true,
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
}),
|
|
37
|
+
})
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## How it Works
|
|
41
|
+
|
|
42
|
+
Working memory is a block of Markdown text that the agent is able to update over time to store continuously relevant information:
|
|
43
|
+
|
|
44
|
+
[YouTube video player](https://www.youtube-nocookie.com/embed/UMy_JHLf1n8)
|
|
45
|
+
|
|
46
|
+
## Memory Persistence Scopes
|
|
47
|
+
|
|
48
|
+
Working memory can operate in two different scopes, allowing you to choose how memory persists across conversations:
|
|
49
|
+
|
|
50
|
+
### Resource-Scoped Memory (Default)
|
|
51
|
+
|
|
52
|
+
By default, working memory persists across all conversation threads for the same user (resourceId), enabling persistent user memory:
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
const memory = new Memory({
|
|
56
|
+
storage,
|
|
57
|
+
options: {
|
|
58
|
+
workingMemory: {
|
|
59
|
+
enabled: true,
|
|
60
|
+
scope: 'resource', // Memory persists across all user threads
|
|
61
|
+
template: `# User Profile
|
|
62
|
+
- **Name**:
|
|
63
|
+
- **Location**:
|
|
64
|
+
- **Interests**:
|
|
65
|
+
- **Preferences**:
|
|
66
|
+
- **Long-term Goals**:
|
|
67
|
+
`,
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
})
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**Use cases:**
|
|
74
|
+
|
|
75
|
+
- Personal assistants that remember user preferences
|
|
76
|
+
- Customer service bots that maintain customer context
|
|
77
|
+
- Educational applications that track student progress
|
|
78
|
+
|
|
79
|
+
### Usage with Agents
|
|
80
|
+
|
|
81
|
+
When using resource-scoped memory, make sure to pass the `resource` parameter in the memory options:
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
// Resource-scoped memory requires resource
|
|
85
|
+
const response = await agent.generate('Hello!', {
|
|
86
|
+
memory: {
|
|
87
|
+
thread: 'conversation-123',
|
|
88
|
+
resource: 'user-alice-456', // Same user across different threads
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Thread-Scoped Memory
|
|
94
|
+
|
|
95
|
+
Thread-scoped memory isolates working memory to individual conversation threads. Each thread maintains its own isolated memory:
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
const memory = new Memory({
|
|
99
|
+
storage,
|
|
100
|
+
options: {
|
|
101
|
+
workingMemory: {
|
|
102
|
+
enabled: true,
|
|
103
|
+
scope: 'thread', // Memory is isolated per thread
|
|
104
|
+
template: `# User Profile
|
|
105
|
+
- **Name**:
|
|
106
|
+
- **Interests**:
|
|
107
|
+
- **Current Goal**:
|
|
108
|
+
`,
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
**Use cases:**
|
|
115
|
+
|
|
116
|
+
- Different conversations about separate topics
|
|
117
|
+
- Temporary or session-specific information
|
|
118
|
+
- Workflows where each thread needs working memory but threads are ephemeral and not related to each other
|
|
119
|
+
|
|
120
|
+
## Storage Adapter Support
|
|
121
|
+
|
|
122
|
+
Resource-scoped working memory requires specific storage adapters that support the `mastra_resources` table:
|
|
123
|
+
|
|
124
|
+
### Supported Storage Adapters
|
|
125
|
+
|
|
126
|
+
- **libSQL** (`@mastra/libsql`)
|
|
127
|
+
- **PostgreSQL** (`@mastra/pg`)
|
|
128
|
+
- **Upstash** (`@mastra/upstash`)
|
|
129
|
+
- **MongoDB** (`@mastra/mongodb`)
|
|
130
|
+
|
|
131
|
+
## Custom Templates
|
|
132
|
+
|
|
133
|
+
Templates guide the agent on what information to track and update in working memory. While a default template is used if none is provided, you'll typically want to define a custom template tailored to your agent's specific use case to ensure it remembers the most relevant information.
|
|
134
|
+
|
|
135
|
+
Here's an example of a custom template. In this example the agent will store the users name, location, timezone, etc as soon as the user sends a message containing any of the info:
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
const memory = new Memory({
|
|
139
|
+
options: {
|
|
140
|
+
workingMemory: {
|
|
141
|
+
enabled: true,
|
|
142
|
+
template: `
|
|
143
|
+
# User Profile
|
|
144
|
+
|
|
145
|
+
## Personal Info
|
|
146
|
+
|
|
147
|
+
- Name:
|
|
148
|
+
- Location:
|
|
149
|
+
- Timezone:
|
|
150
|
+
|
|
151
|
+
## Preferences
|
|
152
|
+
|
|
153
|
+
- Communication Style: [e.g., Formal, Casual]
|
|
154
|
+
- Project Goal:
|
|
155
|
+
- Key Deadlines:
|
|
156
|
+
- [Deadline 1]: [Date]
|
|
157
|
+
- [Deadline 2]: [Date]
|
|
158
|
+
|
|
159
|
+
## Session State
|
|
160
|
+
|
|
161
|
+
- Last Task Discussed:
|
|
162
|
+
- Open Questions:
|
|
163
|
+
- [Question 1]
|
|
164
|
+
- [Question 2]
|
|
165
|
+
`,
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
})
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Designing Effective Templates
|
|
172
|
+
|
|
173
|
+
A well-structured template keeps the information easy for the agent to parse and update. Treat the template as a short form that you want the assistant to keep up to date.
|
|
174
|
+
|
|
175
|
+
- **Short, focused labels.** Avoid paragraphs or very long headings. Keep labels brief (for example `## Personal Info` or `- Name:`) so updates are easy to read and less likely to be truncated.
|
|
176
|
+
- **Use consistent casing.** Inconsistent capitalization (`Timezone:` vs `timezone:`) can cause messy updates. Stick to Title Case or lower case for headings and bullet labels.
|
|
177
|
+
- **Keep placeholder text simple.** Use hints such as `[e.g., Formal]` or `[Date]` to help the LLM fill in the correct spots.
|
|
178
|
+
- **Abbreviate very long values.** If you only need a short form, include guidance like `- Name: [First name or nickname]` or `- Address (short):` rather than the full legal text.
|
|
179
|
+
- **Mention update rules in `instructions`.** You can instruct how and when to fill or clear parts of the template directly in the agent's `instructions` field.
|
|
180
|
+
|
|
181
|
+
### Alternative Template Styles
|
|
182
|
+
|
|
183
|
+
Use a shorter single block if you only need a few items:
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
const basicMemory = new Memory({
|
|
187
|
+
options: {
|
|
188
|
+
workingMemory: {
|
|
189
|
+
enabled: true,
|
|
190
|
+
template: `User Facts:\n- Name:\n- Favorite Color:\n- Current Topic:`,
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
})
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
You can also store the key facts in a short paragraph format if you prefer a more narrative style:
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
const paragraphMemory = new Memory({
|
|
200
|
+
options: {
|
|
201
|
+
workingMemory: {
|
|
202
|
+
enabled: true,
|
|
203
|
+
template: `Important Details:\n\nKeep a short paragraph capturing the user's important facts (name, main goal, current task).`,
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
})
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## Structured Working Memory
|
|
210
|
+
|
|
211
|
+
Working memory can also be defined using a structured schema instead of a Markdown template. This allows you to specify the exact fields and types that should be tracked, using a [Zod](https://zod.dev/) schema. When using a schema, the agent will see and update working memory as a JSON object matching your schema.
|
|
212
|
+
|
|
213
|
+
**Important:** You must specify either `template` or `schema`, but not both.
|
|
214
|
+
|
|
215
|
+
### Example: Schema-Based Working Memory
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { z } from 'zod'
|
|
219
|
+
import { Memory } from '@mastra/memory'
|
|
220
|
+
|
|
221
|
+
const userProfileSchema = z.object({
|
|
222
|
+
name: z.string().optional(),
|
|
223
|
+
location: z.string().optional(),
|
|
224
|
+
timezone: z.string().optional(),
|
|
225
|
+
preferences: z
|
|
226
|
+
.object({
|
|
227
|
+
communicationStyle: z.string().optional(),
|
|
228
|
+
projectGoal: z.string().optional(),
|
|
229
|
+
deadlines: z.array(z.string()).optional(),
|
|
230
|
+
})
|
|
231
|
+
.optional(),
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
const memory = new Memory({
|
|
235
|
+
options: {
|
|
236
|
+
workingMemory: {
|
|
237
|
+
enabled: true,
|
|
238
|
+
schema: userProfileSchema,
|
|
239
|
+
// template: ... (do not set)
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
})
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
When a schema is provided, the agent receives the working memory as a JSON object. For example:
|
|
246
|
+
|
|
247
|
+
```json
|
|
248
|
+
{
|
|
249
|
+
"name": "Sam",
|
|
250
|
+
"location": "Berlin",
|
|
251
|
+
"timezone": "CET",
|
|
252
|
+
"preferences": {
|
|
253
|
+
"communicationStyle": "Formal",
|
|
254
|
+
"projectGoal": "Launch MVP",
|
|
255
|
+
"deadlines": ["2025-07-01"]
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### Merge Semantics for Schema-Based Memory
|
|
261
|
+
|
|
262
|
+
Schema-based working memory uses **merge semantics**, meaning the agent only needs to include fields it wants to add or update. Existing fields are preserved automatically.
|
|
263
|
+
|
|
264
|
+
- **Object fields are deep merged:** Only provided fields are updated; others remain unchanged
|
|
265
|
+
- **Set a field to `null` to delete it:** This explicitly removes the field from memory
|
|
266
|
+
- **Arrays are replaced entirely:** When an array field is provided, it replaces the existing array (arrays are not merged element-by-element)
|
|
267
|
+
|
|
268
|
+
## Choosing Between Template and Schema
|
|
269
|
+
|
|
270
|
+
- Use a **template** (Markdown) if you want the agent to maintain memory as a free-form text block, such as a user profile or scratchpad. Templates use **replace semantics** — the agent must provide the complete memory content on each update.
|
|
271
|
+
- Use a **schema** if you need structured, type-safe data that can be validated and programmatically accessed as JSON. Schemas use **merge semantics** — the agent only provides fields to update, and existing fields are preserved.
|
|
272
|
+
- Only one mode can be active at a time: setting both `template` and `schema` is not supported.
|
|
273
|
+
|
|
274
|
+
## Example: Multi-step Retention
|
|
275
|
+
|
|
276
|
+
Below is a simplified view of how the `User Profile` template updates across a short user conversation:
|
|
277
|
+
|
|
278
|
+
```nohighlight
|
|
279
|
+
# User Profile
|
|
280
|
+
|
|
281
|
+
## Personal Info
|
|
282
|
+
|
|
283
|
+
- Name:
|
|
284
|
+
- Location:
|
|
285
|
+
- Timezone:
|
|
286
|
+
|
|
287
|
+
--- After user says "My name is **Sam** and I'm from **Berlin**" ---
|
|
288
|
+
|
|
289
|
+
# User Profile
|
|
290
|
+
- Name: Sam
|
|
291
|
+
- Location: Berlin
|
|
292
|
+
- Timezone:
|
|
293
|
+
|
|
294
|
+
--- After user adds "By the way I'm normally in **CET**" ---
|
|
295
|
+
|
|
296
|
+
# User Profile
|
|
297
|
+
- Name: Sam
|
|
298
|
+
- Location: Berlin
|
|
299
|
+
- Timezone: CET
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
The agent can now refer to `Sam` or `Berlin` in later responses without requesting the information again because it has been stored in working memory.
|
|
303
|
+
|
|
304
|
+
If your agent is not properly updating working memory when you expect it to, you can add system instructions on _how_ and _when_ to use this template in your agent's `instructions` setting.
|
|
305
|
+
|
|
306
|
+
## Setting Initial Working Memory
|
|
307
|
+
|
|
308
|
+
While agents typically update working memory through the `updateWorkingMemory` tool, you can also set initial working memory programmatically when creating or updating threads. This is useful for injecting user data (like their name, preferences, or other info) that you want available to the agent without passing it in every request.
|
|
309
|
+
|
|
310
|
+
### Setting Working Memory via Thread Metadata
|
|
311
|
+
|
|
312
|
+
When creating a thread, you can provide initial working memory through the metadata's `workingMemory` key:
|
|
313
|
+
|
|
314
|
+
```typescript
|
|
315
|
+
// Create a thread with initial working memory
|
|
316
|
+
const thread = await memory.createThread({
|
|
317
|
+
threadId: 'thread-123',
|
|
318
|
+
resourceId: 'user-456',
|
|
319
|
+
title: 'Medical Consultation',
|
|
320
|
+
metadata: {
|
|
321
|
+
workingMemory: `# Patient Profile
|
|
322
|
+
- Name: John Doe
|
|
323
|
+
- Blood Type: O+
|
|
324
|
+
- Allergies: Penicillin
|
|
325
|
+
- Current Medications: None
|
|
326
|
+
- Medical History: Hypertension (controlled)
|
|
327
|
+
`,
|
|
328
|
+
},
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
// The agent will now have access to this information in all messages
|
|
332
|
+
await agent.generate("What's my blood type?", {
|
|
333
|
+
memory: {
|
|
334
|
+
thread: thread.id,
|
|
335
|
+
resource: 'user-456',
|
|
336
|
+
},
|
|
337
|
+
})
|
|
338
|
+
// Response: "Your blood type is O+."
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
### Updating Working Memory Programmatically
|
|
342
|
+
|
|
343
|
+
You can also update an existing thread's working memory:
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
// Update thread metadata to add/modify working memory
|
|
347
|
+
await memory.updateThread({
|
|
348
|
+
id: 'thread-123',
|
|
349
|
+
title: thread.title,
|
|
350
|
+
metadata: {
|
|
351
|
+
...thread.metadata,
|
|
352
|
+
workingMemory: `# Patient Profile
|
|
353
|
+
- Name: John Doe
|
|
354
|
+
- Blood Type: O+
|
|
355
|
+
- Allergies: Penicillin, Ibuprofen // Updated
|
|
356
|
+
- Current Medications: Lisinopril 10mg daily // Added
|
|
357
|
+
- Medical History: Hypertension (controlled)
|
|
358
|
+
`,
|
|
359
|
+
},
|
|
360
|
+
})
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### Direct Memory Update
|
|
364
|
+
|
|
365
|
+
Alternatively, use the `updateWorkingMemory` method directly:
|
|
366
|
+
|
|
367
|
+
```typescript
|
|
368
|
+
await memory.updateWorkingMemory({
|
|
369
|
+
threadId: 'thread-123',
|
|
370
|
+
resourceId: 'user-456', // Required for resource-scoped memory
|
|
371
|
+
workingMemory: 'Updated memory content...',
|
|
372
|
+
})
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
## Read-Only Working Memory
|
|
376
|
+
|
|
377
|
+
In some scenarios, you may want an agent to have access to working memory data without the ability to modify it. This is useful for:
|
|
378
|
+
|
|
379
|
+
- **Routing agents** that need context but shouldn't update user profiles
|
|
380
|
+
- **Sub agents** in a multi-agent system that should reference but not own the memory
|
|
381
|
+
|
|
382
|
+
To enable read-only mode, set `readOnly: true` in the memory options:
|
|
383
|
+
|
|
384
|
+
```typescript
|
|
385
|
+
const response = await agent.generate('What do you know about me?', {
|
|
386
|
+
memory: {
|
|
387
|
+
thread: 'conversation-123',
|
|
388
|
+
resource: 'user-alice-456',
|
|
389
|
+
options: {
|
|
390
|
+
readOnly: true, // Working memory is provided but cannot be updated
|
|
391
|
+
},
|
|
392
|
+
},
|
|
393
|
+
})
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
## Examples
|
|
397
|
+
|
|
398
|
+
- [Working memory with template](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-template)
|
|
399
|
+
- [Working memory with schema](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-schema)
|
|
400
|
+
- [Per-resource working memory](https://github.com/mastra-ai/mastra/tree/main/examples/memory-per-resource-example) - Complete example showing resource-scoped memory persistence
|