@mastra/pg 1.0.0-beta.9 → 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.
- package/CHANGELOG.md +1404 -0
- package/dist/docs/README.md +36 -0
- package/dist/docs/SKILL.md +37 -0
- package/dist/docs/SOURCE_MAP.json +6 -0
- package/dist/docs/memory/01-storage.md +233 -0
- package/dist/docs/memory/02-working-memory.md +390 -0
- package/dist/docs/memory/03-semantic-recall.md +233 -0
- package/dist/docs/memory/04-reference.md +133 -0
- package/dist/docs/processors/01-reference.md +297 -0
- package/dist/docs/rag/01-overview.md +74 -0
- package/dist/docs/rag/02-vector-databases.md +643 -0
- package/dist/docs/rag/03-retrieval.md +548 -0
- package/dist/docs/rag/04-reference.md +369 -0
- package/dist/docs/storage/01-reference.md +828 -0
- package/dist/docs/tools/01-reference.md +440 -0
- package/dist/docs/vectors/01-reference.md +307 -0
- package/dist/index.cjs +1003 -223
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1000 -225
- package/dist/index.js.map +1 -1
- package/dist/shared/config.d.ts +61 -66
- package/dist/shared/config.d.ts.map +1 -1
- package/dist/storage/client.d.ts +91 -0
- package/dist/storage/client.d.ts.map +1 -0
- package/dist/storage/db/index.d.ts +82 -17
- package/dist/storage/db/index.d.ts.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +3 -2
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/observability/index.d.ts +23 -0
- package/dist/storage/domains/observability/index.d.ts.map +1 -1
- package/dist/storage/domains/scores/index.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +1 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +44 -17
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/test-utils.d.ts.map +1 -1
- package/dist/vector/index.d.ts.map +1 -1
- package/dist/vector/sql-builder.d.ts.map +1 -1
- package/package.json +11 -11
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# @mastra/pg Documentation
|
|
2
|
+
|
|
3
|
+
> Embedded documentation for coding agents
|
|
4
|
+
|
|
5
|
+
## Quick Start
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
# Read the skill overview
|
|
9
|
+
cat docs/SKILL.md
|
|
10
|
+
|
|
11
|
+
# Get the source map
|
|
12
|
+
cat docs/SOURCE_MAP.json
|
|
13
|
+
|
|
14
|
+
# Read topic documentation
|
|
15
|
+
cat docs/<topic>/01-overview.md
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Structure
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
docs/
|
|
22
|
+
├── SKILL.md # Entry point
|
|
23
|
+
├── README.md # This file
|
|
24
|
+
├── SOURCE_MAP.json # Export index
|
|
25
|
+
├── memory/ (4 files)
|
|
26
|
+
├── processors/ (3 files)
|
|
27
|
+
├── rag/ (4 files)
|
|
28
|
+
├── storage/ (3 files)
|
|
29
|
+
├── tools/ (1 files)
|
|
30
|
+
├── vectors/ (1 files)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Version
|
|
34
|
+
|
|
35
|
+
Package: @mastra/pg
|
|
36
|
+
Version: 1.0.0
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: mastra-pg-docs
|
|
3
|
+
description: Documentation for @mastra/pg. Includes links to type definitions and readable implementation code in dist/.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# @mastra/pg Documentation
|
|
7
|
+
|
|
8
|
+
> **Version**: 1.0.0
|
|
9
|
+
> **Package**: @mastra/pg
|
|
10
|
+
|
|
11
|
+
## Quick Navigation
|
|
12
|
+
|
|
13
|
+
Use SOURCE_MAP.json to find any export:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
cat docs/SOURCE_MAP.json
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Each export maps to:
|
|
20
|
+
- **types**: `.d.ts` file with JSDoc and API signatures
|
|
21
|
+
- **implementation**: `.js` chunk file with readable source
|
|
22
|
+
- **docs**: Conceptual documentation in `docs/`
|
|
23
|
+
|
|
24
|
+
## Top Exports
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
See SOURCE_MAP.json for the complete list.
|
|
29
|
+
|
|
30
|
+
## Available Topics
|
|
31
|
+
|
|
32
|
+
- [Memory](memory/) - 4 file(s)
|
|
33
|
+
- [Processors](processors/) - 3 file(s)
|
|
34
|
+
- [Rag](rag/) - 4 file(s)
|
|
35
|
+
- [Storage](storage/) - 3 file(s)
|
|
36
|
+
- [Tools](tools/) - 1 file(s)
|
|
37
|
+
- [Vectors](vectors/) - 1 file(s)
|
|
@@ -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.
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
> Learn how to configure working memory in Mastra to store persistent user data, preferences.
|
|
2
|
+
|
|
3
|
+
# Working Memory
|
|
4
|
+
|
|
5
|
+
While [message history](https://mastra.ai/docs/v1/memory/message-history) and [semantic recall](./semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
|
|
6
|
+
|
|
7
|
+
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.
|
|
8
|
+
|
|
9
|
+
This is useful for maintaining ongoing state that's always relevant and should always be available to the agent.
|
|
10
|
+
|
|
11
|
+
Working memory can persist at two different scopes:
|
|
12
|
+
|
|
13
|
+
- **Resource-scoped** (default): Memory persists across all conversation threads for the same user
|
|
14
|
+
- **Thread-scoped**: Memory is isolated per conversation thread
|
|
15
|
+
|
|
16
|
+
**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.
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
Here's a minimal example of setting up an agent with working memory:
|
|
21
|
+
|
|
22
|
+
```typescript {11-15}
|
|
23
|
+
import { Agent } from "@mastra/core/agent";
|
|
24
|
+
import { Memory } from "@mastra/memory";
|
|
25
|
+
|
|
26
|
+
// Create agent with working memory enabled
|
|
27
|
+
const agent = new Agent({
|
|
28
|
+
id: "personal-assistant",
|
|
29
|
+
name: "PersonalAssistant",
|
|
30
|
+
instructions: "You are a helpful personal assistant.",
|
|
31
|
+
model: "openai/gpt-5.1",
|
|
32
|
+
memory: new Memory({
|
|
33
|
+
options: {
|
|
34
|
+
workingMemory: {
|
|
35
|
+
enabled: true,
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
}),
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## How it Works
|
|
43
|
+
|
|
44
|
+
Working memory is a block of Markdown text that the agent is able to update over time to store continuously relevant information:
|
|
45
|
+
|
|
46
|
+
<YouTube id="UMy_JHLf1n8" />
|
|
47
|
+
|
|
48
|
+
## Memory Persistence Scopes
|
|
49
|
+
|
|
50
|
+
Working memory can operate in two different scopes, allowing you to choose how memory persists across conversations:
|
|
51
|
+
|
|
52
|
+
### Resource-Scoped Memory (Default)
|
|
53
|
+
|
|
54
|
+
By default, working memory persists across all conversation threads for the same user (resourceId), enabling persistent user memory:
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
const memory = new Memory({
|
|
58
|
+
storage,
|
|
59
|
+
options: {
|
|
60
|
+
workingMemory: {
|
|
61
|
+
enabled: true,
|
|
62
|
+
scope: "resource", // Memory persists across all user threads
|
|
63
|
+
template: `# User Profile
|
|
64
|
+
- **Name**:
|
|
65
|
+
- **Location**:
|
|
66
|
+
- **Interests**:
|
|
67
|
+
- **Preferences**:
|
|
68
|
+
- **Long-term Goals**:
|
|
69
|
+
`,
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**Use cases:**
|
|
76
|
+
|
|
77
|
+
- Personal assistants that remember user preferences
|
|
78
|
+
- Customer service bots that maintain customer context
|
|
79
|
+
- Educational applications that track student progress
|
|
80
|
+
|
|
81
|
+
### Usage with Agents
|
|
82
|
+
|
|
83
|
+
When using resource-scoped memory, make sure to pass the `resource` parameter in the memory options:
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
// Resource-scoped memory requires resource
|
|
87
|
+
const response = await agent.generate("Hello!", {
|
|
88
|
+
memory: {
|
|
89
|
+
thread: "conversation-123",
|
|
90
|
+
resource: "user-alice-456", // Same user across different threads
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Thread-Scoped Memory
|
|
96
|
+
|
|
97
|
+
Thread-scoped memory isolates working memory to individual conversation threads. Each thread maintains its own isolated memory:
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
const memory = new Memory({
|
|
101
|
+
storage,
|
|
102
|
+
options: {
|
|
103
|
+
workingMemory: {
|
|
104
|
+
enabled: true,
|
|
105
|
+
scope: "thread", // Memory is isolated per thread
|
|
106
|
+
template: `# User Profile
|
|
107
|
+
- **Name**:
|
|
108
|
+
- **Interests**:
|
|
109
|
+
- **Current Goal**:
|
|
110
|
+
`,
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
**Use cases:**
|
|
117
|
+
|
|
118
|
+
- Different conversations about separate topics
|
|
119
|
+
- Temporary or session-specific information
|
|
120
|
+
- Workflows where each thread needs working memory but threads are ephemeral and not related to each other
|
|
121
|
+
|
|
122
|
+
## Storage Adapter Support
|
|
123
|
+
|
|
124
|
+
Resource-scoped working memory requires specific storage adapters that support the `mastra_resources` table:
|
|
125
|
+
|
|
126
|
+
### Supported Storage Adapters
|
|
127
|
+
|
|
128
|
+
- **libSQL** (`@mastra/libsql`)
|
|
129
|
+
- **PostgreSQL** (`@mastra/pg`)
|
|
130
|
+
- **Upstash** (`@mastra/upstash`)
|
|
131
|
+
- **MongoDB** (`@mastra/mongodb`)
|
|
132
|
+
|
|
133
|
+
## Custom Templates
|
|
134
|
+
|
|
135
|
+
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.
|
|
136
|
+
|
|
137
|
+
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:
|
|
138
|
+
|
|
139
|
+
```typescript {5-28}
|
|
140
|
+
const memory = new Memory({
|
|
141
|
+
options: {
|
|
142
|
+
workingMemory: {
|
|
143
|
+
enabled: true,
|
|
144
|
+
template: `
|
|
145
|
+
# User Profile
|
|
146
|
+
|
|
147
|
+
## Personal Info
|
|
148
|
+
|
|
149
|
+
- Name:
|
|
150
|
+
- Location:
|
|
151
|
+
- Timezone:
|
|
152
|
+
|
|
153
|
+
## Preferences
|
|
154
|
+
|
|
155
|
+
- Communication Style: [e.g., Formal, Casual]
|
|
156
|
+
- Project Goal:
|
|
157
|
+
- Key Deadlines:
|
|
158
|
+
- [Deadline 1]: [Date]
|
|
159
|
+
- [Deadline 2]: [Date]
|
|
160
|
+
|
|
161
|
+
## Session State
|
|
162
|
+
|
|
163
|
+
- Last Task Discussed:
|
|
164
|
+
- Open Questions:
|
|
165
|
+
- [Question 1]
|
|
166
|
+
- [Question 2]
|
|
167
|
+
`,
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Designing Effective Templates
|
|
174
|
+
|
|
175
|
+
A well-structured template keeps the information easy for the agent to parse and update. Treat the
|
|
176
|
+
template as a short form that you want the assistant to keep up to date.
|
|
177
|
+
|
|
178
|
+
- **Short, focused labels.** Avoid paragraphs or very long headings. Keep labels brief (for example
|
|
179
|
+
`## Personal Info` or `- Name:`) so updates are easy to read and less likely to be truncated.
|
|
180
|
+
- **Use consistent casing.** Inconsistent capitalization (`Timezone:` vs `timezone:`) can cause messy
|
|
181
|
+
updates. Stick to Title Case or lower case for headings and bullet labels.
|
|
182
|
+
- **Keep placeholder text simple.** Use hints such as `[e.g., Formal]` or `[Date]` to help the LLM
|
|
183
|
+
fill in the correct spots.
|
|
184
|
+
- **Abbreviate very long values.** If you only need a short form, include guidance like
|
|
185
|
+
`- Name: [First name or nickname]` or `- Address (short):` rather than the full legal text.
|
|
186
|
+
- **Mention update rules in `instructions`.** You can instruct how and when to fill or clear parts of
|
|
187
|
+
the template directly in the agent's `instructions` field.
|
|
188
|
+
|
|
189
|
+
### Alternative Template Styles
|
|
190
|
+
|
|
191
|
+
Use a shorter single block if you only need a few items:
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
const basicMemory = new Memory({
|
|
195
|
+
options: {
|
|
196
|
+
workingMemory: {
|
|
197
|
+
enabled: true,
|
|
198
|
+
template: `User Facts:\n- Name:\n- Favorite Color:\n- Current Topic:`,
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
You can also store the key facts in a short paragraph format if you prefer a more narrative style:
|
|
205
|
+
|
|
206
|
+
```typescript
|
|
207
|
+
const paragraphMemory = new Memory({
|
|
208
|
+
options: {
|
|
209
|
+
workingMemory: {
|
|
210
|
+
enabled: true,
|
|
211
|
+
template: `Important Details:\n\nKeep a short paragraph capturing the user's important facts (name, main goal, current task).`,
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Structured Working Memory
|
|
218
|
+
|
|
219
|
+
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.
|
|
220
|
+
|
|
221
|
+
**Important:** You must specify either `template` or `schema`, but not both.
|
|
222
|
+
|
|
223
|
+
### Example: Schema-Based Working Memory
|
|
224
|
+
|
|
225
|
+
```typescript
|
|
226
|
+
import { z } from "zod";
|
|
227
|
+
import { Memory } from "@mastra/memory";
|
|
228
|
+
|
|
229
|
+
const userProfileSchema = z.object({
|
|
230
|
+
name: z.string().optional(),
|
|
231
|
+
location: z.string().optional(),
|
|
232
|
+
timezone: z.string().optional(),
|
|
233
|
+
preferences: z
|
|
234
|
+
.object({
|
|
235
|
+
communicationStyle: z.string().optional(),
|
|
236
|
+
projectGoal: z.string().optional(),
|
|
237
|
+
deadlines: z.array(z.string()).optional(),
|
|
238
|
+
})
|
|
239
|
+
.optional(),
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
const memory = new Memory({
|
|
243
|
+
options: {
|
|
244
|
+
workingMemory: {
|
|
245
|
+
enabled: true,
|
|
246
|
+
schema: userProfileSchema,
|
|
247
|
+
// template: ... (do not set)
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
When a schema is provided, the agent receives the working memory as a JSON object. For example:
|
|
254
|
+
|
|
255
|
+
```json
|
|
256
|
+
{
|
|
257
|
+
"name": "Sam",
|
|
258
|
+
"location": "Berlin",
|
|
259
|
+
"timezone": "CET",
|
|
260
|
+
"preferences": {
|
|
261
|
+
"communicationStyle": "Formal",
|
|
262
|
+
"projectGoal": "Launch MVP",
|
|
263
|
+
"deadlines": ["2025-07-01"]
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Merge Semantics for Schema-Based Memory
|
|
269
|
+
|
|
270
|
+
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.
|
|
271
|
+
|
|
272
|
+
- **Object fields are deep merged:** Only provided fields are updated; others remain unchanged
|
|
273
|
+
- **Set a field to `null` to delete it:** This explicitly removes the field from memory
|
|
274
|
+
- **Arrays are replaced entirely:** When an array field is provided, it replaces the existing array (arrays are not merged element-by-element)
|
|
275
|
+
|
|
276
|
+
## Choosing Between Template and Schema
|
|
277
|
+
|
|
278
|
+
- 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.
|
|
279
|
+
- 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.
|
|
280
|
+
- Only one mode can be active at a time: setting both `template` and `schema` is not supported.
|
|
281
|
+
|
|
282
|
+
## Example: Multi-step Retention
|
|
283
|
+
|
|
284
|
+
Below is a simplified view of how the `User Profile` template updates across a short user
|
|
285
|
+
conversation:
|
|
286
|
+
|
|
287
|
+
```nohighlight
|
|
288
|
+
# User Profile
|
|
289
|
+
|
|
290
|
+
## Personal Info
|
|
291
|
+
|
|
292
|
+
- Name:
|
|
293
|
+
- Location:
|
|
294
|
+
- Timezone:
|
|
295
|
+
|
|
296
|
+
--- After user says "My name is **Sam** and I'm from **Berlin**" ---
|
|
297
|
+
|
|
298
|
+
# User Profile
|
|
299
|
+
- Name: Sam
|
|
300
|
+
- Location: Berlin
|
|
301
|
+
- Timezone:
|
|
302
|
+
|
|
303
|
+
--- After user adds "By the way I'm normally in **CET**" ---
|
|
304
|
+
|
|
305
|
+
# User Profile
|
|
306
|
+
- Name: Sam
|
|
307
|
+
- Location: Berlin
|
|
308
|
+
- Timezone: CET
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
The agent can now refer to `Sam` or `Berlin` in later responses without requesting the information
|
|
312
|
+
again because it has been stored in working memory.
|
|
313
|
+
|
|
314
|
+
If your agent is not properly updating working memory when you expect it to, you can add system
|
|
315
|
+
instructions on _how_ and _when_ to use this template in your agent's `instructions` setting.
|
|
316
|
+
|
|
317
|
+
## Setting Initial Working Memory
|
|
318
|
+
|
|
319
|
+
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.
|
|
320
|
+
|
|
321
|
+
### Setting Working Memory via Thread Metadata
|
|
322
|
+
|
|
323
|
+
When creating a thread, you can provide initial working memory through the metadata's `workingMemory` key:
|
|
324
|
+
|
|
325
|
+
```typescript title="src/app/medical-consultation.ts"
|
|
326
|
+
// Create a thread with initial working memory
|
|
327
|
+
const thread = await memory.createThread({
|
|
328
|
+
threadId: "thread-123",
|
|
329
|
+
resourceId: "user-456",
|
|
330
|
+
title: "Medical Consultation",
|
|
331
|
+
metadata: {
|
|
332
|
+
workingMemory: `# Patient Profile
|
|
333
|
+
- Name: John Doe
|
|
334
|
+
- Blood Type: O+
|
|
335
|
+
- Allergies: Penicillin
|
|
336
|
+
- Current Medications: None
|
|
337
|
+
- Medical History: Hypertension (controlled)
|
|
338
|
+
`,
|
|
339
|
+
},
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
// The agent will now have access to this information in all messages
|
|
343
|
+
await agent.generate("What's my blood type?", {
|
|
344
|
+
memory: {
|
|
345
|
+
thread: thread.id,
|
|
346
|
+
resource: "user-456",
|
|
347
|
+
},
|
|
348
|
+
});
|
|
349
|
+
// Response: "Your blood type is O+."
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
### Updating Working Memory Programmatically
|
|
353
|
+
|
|
354
|
+
You can also update an existing thread's working memory:
|
|
355
|
+
|
|
356
|
+
```typescript title="src/app/medical-consultation.ts"
|
|
357
|
+
// Update thread metadata to add/modify working memory
|
|
358
|
+
await memory.updateThread({
|
|
359
|
+
id: "thread-123",
|
|
360
|
+
title: thread.title,
|
|
361
|
+
metadata: {
|
|
362
|
+
...thread.metadata,
|
|
363
|
+
workingMemory: `# Patient Profile
|
|
364
|
+
- Name: John Doe
|
|
365
|
+
- Blood Type: O+
|
|
366
|
+
- Allergies: Penicillin, Ibuprofen // Updated
|
|
367
|
+
- Current Medications: Lisinopril 10mg daily // Added
|
|
368
|
+
- Medical History: Hypertension (controlled)
|
|
369
|
+
`,
|
|
370
|
+
},
|
|
371
|
+
});
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
### Direct Memory Update
|
|
375
|
+
|
|
376
|
+
Alternatively, use the `updateWorkingMemory` method directly:
|
|
377
|
+
|
|
378
|
+
```typescript title="src/app/medical-consultation.ts"
|
|
379
|
+
await memory.updateWorkingMemory({
|
|
380
|
+
threadId: "thread-123",
|
|
381
|
+
resourceId: "user-456", // Required for resource-scoped memory
|
|
382
|
+
workingMemory: "Updated memory content...",
|
|
383
|
+
});
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
## Examples
|
|
387
|
+
|
|
388
|
+
- [Working memory with template](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-template)
|
|
389
|
+
- [Working memory with schema](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-schema)
|
|
390
|
+
- [Per-resource working memory](https://github.com/mastra-ai/mastra/tree/main/examples/memory-per-resource-example) - Complete example showing resource-scoped memory persistence
|