@mastra/memory 1.5.1 → 1.5.2

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/{chunk-6PKWQ3GH.js → chunk-HNPAIFCZ.js} +59 -16
  3. package/dist/chunk-HNPAIFCZ.js.map +1 -0
  4. package/dist/{chunk-6XVTMLW4.cjs → chunk-PVFLHAZX.cjs} +59 -16
  5. package/dist/chunk-PVFLHAZX.cjs.map +1 -0
  6. package/dist/docs/SKILL.md +55 -0
  7. package/dist/docs/assets/SOURCE_MAP.json +103 -0
  8. package/dist/docs/references/docs-agents-agent-approval.md +558 -0
  9. package/dist/docs/references/docs-agents-agent-memory.md +209 -0
  10. package/dist/docs/references/docs-agents-network-approval.md +275 -0
  11. package/dist/docs/references/docs-agents-networks.md +299 -0
  12. package/dist/docs/references/docs-agents-supervisor-agents.md +304 -0
  13. package/dist/docs/references/docs-memory-memory-processors.md +314 -0
  14. package/dist/docs/references/docs-memory-message-history.md +260 -0
  15. package/dist/docs/references/docs-memory-observational-memory.md +248 -0
  16. package/dist/docs/references/docs-memory-overview.md +45 -0
  17. package/dist/docs/references/docs-memory-semantic-recall.md +272 -0
  18. package/dist/docs/references/docs-memory-storage.md +261 -0
  19. package/dist/docs/references/docs-memory-working-memory.md +400 -0
  20. package/dist/docs/references/reference-core-getMemory.md +50 -0
  21. package/dist/docs/references/reference-core-listMemory.md +56 -0
  22. package/dist/docs/references/reference-memory-clone-utilities.md +199 -0
  23. package/dist/docs/references/reference-memory-cloneThread.md +130 -0
  24. package/dist/docs/references/reference-memory-createThread.md +68 -0
  25. package/dist/docs/references/reference-memory-getThreadById.md +24 -0
  26. package/dist/docs/references/reference-memory-listThreads.md +145 -0
  27. package/dist/docs/references/reference-memory-memory-class.md +147 -0
  28. package/dist/docs/references/reference-memory-observational-memory.md +565 -0
  29. package/dist/docs/references/reference-processors-token-limiter-processor.md +115 -0
  30. package/dist/docs/references/reference-storage-dynamodb.md +282 -0
  31. package/dist/docs/references/reference-storage-libsql.md +135 -0
  32. package/dist/docs/references/reference-storage-mongodb.md +262 -0
  33. package/dist/docs/references/reference-storage-postgresql.md +526 -0
  34. package/dist/docs/references/reference-storage-upstash.md +160 -0
  35. package/dist/docs/references/reference-vectors-libsql.md +305 -0
  36. package/dist/docs/references/reference-vectors-mongodb.md +295 -0
  37. package/dist/docs/references/reference-vectors-pg.md +408 -0
  38. package/dist/docs/references/reference-vectors-upstash.md +294 -0
  39. package/dist/index.cjs +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/{observational-memory-AJWSMZVP.js → observational-memory-KAFD4QZK.js} +3 -3
  42. package/dist/{observational-memory-AJWSMZVP.js.map → observational-memory-KAFD4QZK.js.map} +1 -1
  43. package/dist/{observational-memory-Q5TO525O.cjs → observational-memory-Q47HN5YL.cjs} +17 -17
  44. package/dist/{observational-memory-Q5TO525O.cjs.map → observational-memory-Q47HN5YL.cjs.map} +1 -1
  45. package/dist/processors/index.cjs +15 -15
  46. package/dist/processors/index.js +1 -1
  47. package/dist/processors/observational-memory/observational-memory.d.ts +2 -2
  48. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  49. package/dist/processors/observational-memory/token-counter.d.ts.map +1 -1
  50. package/package.json +8 -8
  51. package/dist/chunk-6PKWQ3GH.js.map +0 -1
  52. package/dist/chunk-6XVTMLW4.cjs.map +0 -1
@@ -0,0 +1,248 @@
1
+ # Observational Memory
2
+
3
+ **Added in:** `@mastra/memory@1.1.0`
4
+
5
+ Observational Memory (OM) is Mastra's memory system for long-context agentic memory. Two background agents — an **Observer** and a **Reflector** — watch your agent's conversations and maintain a dense observation log that replaces raw message history as it grows.
6
+
7
+ ## Quick Start
8
+
9
+ Enable `observationalMemory` in the memory options when creating your agent:
10
+
11
+ ```typescript
12
+ import { Memory } from '@mastra/memory'
13
+ import { Agent } from '@mastra/core/agent'
14
+
15
+ export const agent = new Agent({
16
+ name: 'my-agent',
17
+ instructions: 'You are a helpful assistant.',
18
+ model: 'openai/gpt-5-mini',
19
+ memory: new Memory({
20
+ options: {
21
+ observationalMemory: true,
22
+ },
23
+ }),
24
+ })
25
+ ```
26
+
27
+ That's it. The agent now has humanlike long-term memory that persists across conversations. Setting `observationalMemory: true` uses `google/gemini-2.5-flash` by default. To use a different model or customize thresholds, pass a config object instead:
28
+
29
+ ```typescript
30
+ const memory = new Memory({
31
+ options: {
32
+ observationalMemory: {
33
+ model: 'deepseek/deepseek-reasoner',
34
+ },
35
+ },
36
+ })
37
+ ```
38
+
39
+ See [configuration options](https://mastra.ai/reference/memory/observational-memory) for full API details.
40
+
41
+ > **Note:** OM currently only supports `@mastra/pg`, `@mastra/libsql`, and `@mastra/mongodb` storage adapters. It uses background agents for managing memory. When using `observationalMemory: true`, the default model is `google/gemini-2.5-flash`. When passing a config object, a `model` must be explicitly set.
42
+
43
+ ## Benefits
44
+
45
+ - **Prompt caching**: OM's context is stable — observations append over time rather than being dynamically retrieved each turn. This keeps the prompt prefix cacheable, which reduces costs.
46
+ - **Compression**: Raw message history and tool results get compressed into a dense observation log. Smaller context means faster responses and longer coherent conversations.
47
+ - **Zero context rot**: The agent sees relevant information instead of noisy tool calls and irrelevant tokens, so the agent stays on task over long sessions.
48
+
49
+ ## How It Works
50
+
51
+ You don't remember every word of every conversation you've ever had. You observe what happened subconsciously, then your brain reflects — reorganizing, combining, and condensing into long-term memory. OM works the same way.
52
+
53
+ Every time an agent responds, it sees a context window containing its system prompt, recent message history, and any injected context. The context window is finite — even models with large token limits perform worse when the window is full. This causes two problems:
54
+
55
+ - **Context rot**: the more raw message history an agent carries, the worse it performs.
56
+ - **Context waste**: most of that history contains tokens no longer needed to keep the agent on task.
57
+
58
+ OM solves both problems by compressing old context into dense observations.
59
+
60
+ ### Observations
61
+
62
+ When message history tokens exceed a threshold (default: 30,000), the Observer creates observations — concise notes about what happened:
63
+
64
+ ```text
65
+ Date: 2026-01-15
66
+ - 🔴 12:10 User is building a Next.js app with Supabase auth, due in 1 week (meaning January 22nd 2026)
67
+ - 🔴 12:10 App uses server components with client-side hydration
68
+ - 🟡 12:12 User asked about middleware configuration for protected routes
69
+ - 🔴 12:15 User stated the app name is "Acme Dashboard"
70
+ ```
71
+
72
+ The compression is typically 5–40×. The Observer also tracks a **current task** and **suggested response** so the agent picks up where it left off.
73
+
74
+ Example: an agent using Playwright MCP might see 50,000+ tokens per page snapshot. With OM, the Observer watches the interaction and creates a few hundred tokens of observations about what was on the page and what actions were taken. The agent stays on task without carrying every raw snapshot.
75
+
76
+ ### Reflections
77
+
78
+ When observations exceed their threshold (default: 40,000 tokens), the Reflector condenses them — combining related items and reflecting on patterns.
79
+
80
+ The result is a three-tier system:
81
+
82
+ 1. **Recent messages**: Exact conversation history for the current task
83
+ 2. **Observations**: A log of what the Observer has seen
84
+ 3. **Reflections**: Condensed observations when memory becomes too long
85
+
86
+ ## Models
87
+
88
+ The Observer and Reflector run in the background. Any model that works with Mastra's model routing (e.g. `openai/...`, `google/...`, `deepseek/...`) can be used.
89
+
90
+ When using `observationalMemory: true`, the default model is `google/gemini-2.5-flash`. When passing a config object, a `model` must be explicitly set.
91
+
92
+ We recommend `google/gemini-2.5-flash` — it works well for both observation and reflection, and its 1M token context window gives the Reflector headroom.
93
+
94
+ We've also tested `deepseek`, `qwen3`, and `glm-4.7` for the Observer. For the Reflector, make sure the model's context window can fit all observations. Note that Claude 4.5 models currently don't work well as observer or reflector.
95
+
96
+ ```typescript
97
+ const memory = new Memory({
98
+ options: {
99
+ observationalMemory: {
100
+ model: 'deepseek/deepseek-reasoner',
101
+ },
102
+ },
103
+ })
104
+ ```
105
+
106
+ See [model configuration](https://mastra.ai/reference/memory/observational-memory) for using different models per agent.
107
+
108
+ ## Scopes
109
+
110
+ ### Thread scope (default)
111
+
112
+ Each thread has its own observations. This scope is well tested and works well as a general purpose memory system, especially for long horizon agentic use-cases.
113
+
114
+ ```typescript
115
+ const memory = new Memory({
116
+ options: {
117
+ observationalMemory: {
118
+ model: 'google/gemini-2.5-flash',
119
+ scope: 'thread',
120
+ },
121
+ },
122
+ })
123
+ ```
124
+
125
+ Thread scope requires a valid `threadId` to be provided when calling the agent. If `threadId` is missing, Observational Memory throws an error. This prevents multiple threads from silently sharing a single observation record, which can cause database deadlocks.
126
+
127
+ ### Resource scope (experimental)
128
+
129
+ Observations are shared across all threads for a resource (typically a user). Enables cross-conversation memory.
130
+
131
+ ```typescript
132
+ const memory = new Memory({
133
+ options: {
134
+ observationalMemory: {
135
+ model: 'google/gemini-2.5-flash',
136
+ scope: 'resource',
137
+ },
138
+ },
139
+ })
140
+ ```
141
+
142
+ Resource scope works, however it's marked as experimental for now until we prove task adherence/continuity across multiple ongoing simultaneous threads. As of today, you may need to tweak your system prompt to prevent one thread from continuing the work that another had already started (but hadn't finished).
143
+
144
+ This is because in resource scope, each thread is a perspective on _all_ threads for the resource.
145
+
146
+ For your use-case this may not be a problem, so your mileage may vary.
147
+
148
+ > **Warning:** In resource scope, unobserved messages across _all_ threads are processed together. For users with many existing threads, this can be slow. Use thread scope for existing apps.
149
+
150
+ ## Token Budgets
151
+
152
+ OM uses token thresholds to decide when to observe and reflect. See [token budget configuration](https://mastra.ai/reference/memory/observational-memory) for details.
153
+
154
+ ```typescript
155
+ const memory = new Memory({
156
+ options: {
157
+ observationalMemory: {
158
+ model: 'google/gemini-2.5-flash',
159
+ observation: {
160
+ // when to run the Observer (default: 30,000)
161
+ messageTokens: 30_000,
162
+ },
163
+ reflection: {
164
+ // when to run the Reflector (default: 40,000)
165
+ observationTokens: 40_000,
166
+ },
167
+ // let message history borrow from observation budget
168
+ // requires bufferTokens: false (temporary limitation)
169
+ shareTokenBudget: false,
170
+ },
171
+ },
172
+ })
173
+ ```
174
+
175
+ ## Async Buffering
176
+
177
+ Without async buffering, the Observer runs synchronously when the message threshold is reached — the agent pauses mid-conversation while the Observer LLM call completes. With async buffering (enabled by default), observations are pre-computed in the background as the conversation grows. When the threshold is hit, buffered observations activate instantly with no pause.
178
+
179
+ ### How it works
180
+
181
+ As the agent converses, message tokens accumulate. At regular intervals (`bufferTokens`), a background Observer call runs without blocking the agent. Each call produces a "chunk" of observations that's stored in a buffer.
182
+
183
+ When message tokens reach the `messageTokens` threshold, buffered chunks activate: their observations move into the active observation log, and the corresponding raw messages are removed from the context window. The agent never pauses.
184
+
185
+ Buffered observations also include continuation hints — a suggested next response and the current task — so the main agent maintains conversational continuity after activation shrinks the context window.
186
+
187
+ If the agent produces messages faster than the Observer can process them, a `blockAfter` safety threshold forces a synchronous observation as a last resort. Buffered activation still preserves a minimum remaining context (the smaller of \~1k tokens or the configured retention floor).
188
+
189
+ Reflection works similarly — the Reflector runs in the background when observations reach a fraction of the reflection threshold.
190
+
191
+ ### Settings
192
+
193
+ | Setting | Default | What it controls |
194
+ | ------------------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
195
+ | `observation.bufferTokens` | `0.2` | How often to buffer. `0.2` means every 20% of `messageTokens` — with the default 30k threshold, that's roughly every 6k tokens. Can also be an absolute token count (e.g. `5000`). |
196
+ | `observation.bufferActivation` | `0.8` | How aggressively to clear the message window on activation. `0.8` means remove enough messages to keep only 20% of `messageTokens` remaining. Lower values keep more message history. |
197
+ | `observation.blockAfter` | `1.2` | Safety threshold as a multiplier of `messageTokens`. At `1.2`, synchronous observation is forced at 36k tokens (1.2 × 30k). Only matters if buffering can't keep up. |
198
+ | `reflection.bufferActivation` | `0.5` | When to start background reflection. `0.5` means reflection begins when observations reach 50% of the `observationTokens` threshold. |
199
+ | `reflection.blockAfter` | `1.2` | Safety threshold for reflection, same logic as observation. |
200
+
201
+ ### Disabling
202
+
203
+ To disable async buffering and use synchronous observation/reflection instead:
204
+
205
+ ```typescript
206
+ const memory = new Memory({
207
+ options: {
208
+ observationalMemory: {
209
+ model: 'google/gemini-2.5-flash',
210
+ observation: {
211
+ bufferTokens: false,
212
+ },
213
+ },
214
+ },
215
+ })
216
+ ```
217
+
218
+ Setting `bufferTokens: false` disables both observation and reflection async buffering. See [async buffering configuration](https://mastra.ai/reference/memory/observational-memory) for the full API.
219
+
220
+ > **Note:** Async buffering is not supported with `scope: 'resource'`. It is automatically disabled in resource scope.
221
+
222
+ ## Migrating existing threads
223
+
224
+ No manual migration needed. OM reads existing messages and observes them lazily when thresholds are exceeded.
225
+
226
+ - **Thread scope**: The first time a thread exceeds `observation.messageTokens`, the Observer processes the backlog.
227
+ - **Resource scope**: All unobserved messages across all threads for a resource are processed together. For users with many existing threads, this could take significant time.
228
+
229
+ ## Viewing in Mastra Studio
230
+
231
+ Mastra Studio shows OM status in real time in the memory tab: token usage, which model is running, current observations, and reflection history.
232
+
233
+ ## Comparing OM with other memory features
234
+
235
+ - **[Message history](https://mastra.ai/docs/memory/message-history)**: High-fidelity record of the current conversation
236
+ - **[Working memory](https://mastra.ai/docs/memory/working-memory)**: Small, structured state (JSON or markdown) for user preferences, names, goals
237
+ - **[Semantic Recall](https://mastra.ai/docs/memory/semantic-recall)**: RAG-based retrieval of relevant past messages
238
+
239
+ If you're using working memory to store conversation summaries or ongoing state that grows over time, OM is a better fit. Working memory is for small, structured data; OM is for long-running event logs. OM also manages message history automatically—the `messageTokens` setting controls how much raw history remains before observation runs.
240
+
241
+ In practical terms, OM replaces both working memory and message history, and has greater accuracy (and lower cost) than Semantic Recall.
242
+
243
+ ## Related
244
+
245
+ - [Observational Memory Reference](https://mastra.ai/reference/memory/observational-memory)
246
+ - [Memory Overview](https://mastra.ai/docs/memory/overview)
247
+ - [Message History](https://mastra.ai/docs/memory/message-history)
248
+ - [Memory Processors](https://mastra.ai/docs/memory/memory-processors)
@@ -0,0 +1,45 @@
1
+ # Memory
2
+
3
+ Memory enables your agent to remember user messages, agent replies, and tool results across interactions, giving it the context it needs to stay consistent, maintain conversation flow, and produce better answers over time.
4
+
5
+ Mastra supports four complementary memory types:
6
+
7
+ - [**Message history**](https://mastra.ai/docs/memory/message-history) - keeps recent messages from the current conversation so they can be rendered in the UI and used to maintain short-term continuity within the exchange.
8
+ - [**Working memory**](https://mastra.ai/docs/memory/working-memory) - stores persistent, structured user data such as names, preferences, and goals.
9
+ - [**Semantic recall**](https://mastra.ai/docs/memory/semantic-recall) - retrieves relevant messages from older conversations based on semantic meaning rather than exact keywords, mirroring how humans recall information by association. Requires a [vector database](https://mastra.ai/docs/memory/semantic-recall) and an [embedding model](https://mastra.ai/docs/memory/semantic-recall).
10
+ - [**Observational memory**](https://mastra.ai/docs/memory/observational-memory) - uses background Observer and Reflector agents to maintain a dense observation log that replaces raw message history as it grows, keeping the context window small while preserving long-term memory across conversations.
11
+
12
+ If the combined memory exceeds the model's context limit, [memory processors](https://mastra.ai/docs/memory/memory-processors) can filter, trim, or prioritize content so the most relevant information is preserved.
13
+
14
+ ## Getting started
15
+
16
+ Choose a memory option to get started:
17
+
18
+ - [Message history](https://mastra.ai/docs/memory/message-history)
19
+ - [Working memory](https://mastra.ai/docs/memory/working-memory)
20
+ - [Semantic recall](https://mastra.ai/docs/memory/semantic-recall)
21
+ - [Observational memory](https://mastra.ai/docs/memory/observational-memory)
22
+
23
+ ## Storage
24
+
25
+ Before enabling memory, you must first configure a storage adapter. Mastra supports several databases including PostgreSQL, MongoDB, libSQL, and [more](https://mastra.ai/docs/memory/storage).
26
+
27
+ Storage can be configured at the [instance level](https://mastra.ai/docs/memory/storage) (shared across all agents) or at the [agent level](https://mastra.ai/docs/memory/storage) (dedicated per agent).
28
+
29
+ For semantic recall, you can use a separate vector database like Pinecone alongside your primary storage.
30
+
31
+ See the [Storage](https://mastra.ai/docs/memory/storage) documentation for configuration options, supported providers, and examples.
32
+
33
+ ## Debugging memory
34
+
35
+ When [tracing](https://mastra.ai/docs/observability/tracing/overview) 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.
36
+
37
+ ![Trace output showing memory context included in an agent request](https://mastra.ai/_next/image?url=%2Ftracingafter.png\&w=1920\&q=75)
38
+
39
+ This visibility helps you understand why an agent made specific decisions and verify that memory retrieval is working as expected.
40
+
41
+ ## Next steps
42
+
43
+ - Learn more about [Storage](https://mastra.ai/docs/memory/storage) providers and configuration options
44
+ - Add [Message history](https://mastra.ai/docs/memory/message-history), [Working memory](https://mastra.ai/docs/memory/working-memory), [Semantic recall](https://mastra.ai/docs/memory/semantic-recall), or [Observational memory](https://mastra.ai/docs/memory/observational-memory)
45
+ - Visit [Memory configuration reference](https://mastra.ai/reference/memory/memory-class) for all available options
@@ -0,0 +1,272 @@
1
+ # Semantic Recall
2
+
3
+ If you ask your friend what they did last weekend, they will search in their memory for events associated with "last weekend" and then tell you what they did. That's sort of like how semantic recall works in Mastra.
4
+
5
+ > **Watch 📹:** What semantic recall is, how it works, and how to configure it in Mastra → [YouTube (5 minutes)](https://youtu.be/UVZtK8cK8xQ)
6
+
7
+ ## How Semantic Recall Works
8
+
9
+ Semantic recall is RAG-based search that helps agents maintain context across longer interactions when messages are no longer within [recent message history](https://mastra.ai/docs/memory/message-history).
10
+
11
+ It uses vector embeddings of messages for similarity search, integrates with various vector stores, and has configurable context windows around retrieved messages.
12
+
13
+ ![Diagram showing Mastra Memory semantic recall](/assets/images/semantic-recall-fd7b9336a6d0d18019216cb6d3dbe710.png)
14
+
15
+ When it's enabled, new messages are used to query a vector DB for semantically similar messages.
16
+
17
+ After getting a response from the LLM, all new messages (user, assistant, and tool calls/results) are inserted into the vector DB to be recalled in later interactions.
18
+
19
+ ## Quick Start
20
+
21
+ Semantic recall is enabled by default, so if you give your agent memory it will be included:
22
+
23
+ ```typescript
24
+ import { Agent } from '@mastra/core/agent'
25
+ import { Memory } from '@mastra/memory'
26
+
27
+ const agent = new Agent({
28
+ id: 'support-agent',
29
+ name: 'SupportAgent',
30
+ instructions: 'You are a helpful support agent.',
31
+ model: 'openai/gpt-5.1',
32
+ memory: new Memory(),
33
+ })
34
+ ```
35
+
36
+ ## Using the recall() Method
37
+
38
+ While `listMessages` retrieves messages by thread ID with basic pagination, [`recall()`](https://mastra.ai/reference/memory/recall) adds support for **semantic search**. When you need to find messages by meaning rather than just recency, use `recall()` with a `vectorSearchString`:
39
+
40
+ ```typescript
41
+ const memory = await agent.getMemory()
42
+
43
+ // Basic recall - similar to listMessages
44
+ const { messages } = await memory!.recall({
45
+ threadId: 'thread-123',
46
+ perPage: 50,
47
+ })
48
+
49
+ // Semantic recall - find messages by meaning
50
+ const { messages: relevantMessages } = await memory!.recall({
51
+ threadId: 'thread-123',
52
+ vectorSearchString: 'What did we discuss about the project deadline?',
53
+ threadConfig: {
54
+ semanticRecall: true,
55
+ },
56
+ })
57
+ ```
58
+
59
+ ## Storage configuration
60
+
61
+ Semantic recall relies on a [storage and vector db](https://mastra.ai/reference/memory/memory-class) to store messages and their embeddings.
62
+
63
+ ```ts
64
+ import { Memory } from '@mastra/memory'
65
+ import { Agent } from '@mastra/core/agent'
66
+ import { LibSQLStore, LibSQLVector } from '@mastra/libsql'
67
+
68
+ const agent = new Agent({
69
+ memory: new Memory({
70
+ // this is the default storage db if omitted
71
+ storage: new LibSQLStore({
72
+ id: 'agent-storage',
73
+ url: 'file:./local.db',
74
+ }),
75
+ // this is the default vector db if omitted
76
+ vector: new LibSQLVector({
77
+ id: 'agent-vector',
78
+ url: 'file:./local.db',
79
+ }),
80
+ }),
81
+ })
82
+ ```
83
+
84
+ Each vector store page below includes installation instructions, configuration parameters, and usage examples:
85
+
86
+ - [Astra](https://mastra.ai/reference/vectors/astra)
87
+ - [Chroma](https://mastra.ai/reference/vectors/chroma)
88
+ - [Cloudflare Vectorize](https://mastra.ai/reference/vectors/vectorize)
89
+ - [Convex](https://mastra.ai/reference/vectors/convex)
90
+ - [Couchbase](https://mastra.ai/reference/vectors/couchbase)
91
+ - [DuckDB](https://mastra.ai/reference/vectors/duckdb)
92
+ - [Elasticsearch](https://mastra.ai/reference/vectors/elasticsearch)
93
+ - [LanceDB](https://mastra.ai/reference/vectors/lance)
94
+ - [libSQL](https://mastra.ai/reference/vectors/libsql)
95
+ - [MongoDB](https://mastra.ai/reference/vectors/mongodb)
96
+ - [OpenSearch](https://mastra.ai/reference/vectors/opensearch)
97
+ - [Pinecone](https://mastra.ai/reference/vectors/pinecone)
98
+ - [PostgreSQL](https://mastra.ai/reference/vectors/pg)
99
+ - [Qdrant](https://mastra.ai/reference/vectors/qdrant)
100
+ - [S3 Vectors](https://mastra.ai/reference/vectors/s3vectors)
101
+ - [Turbopuffer](https://mastra.ai/reference/vectors/turbopuffer)
102
+ - [Upstash](https://mastra.ai/reference/vectors/upstash)
103
+
104
+ ## Recall configuration
105
+
106
+ The three main parameters that control semantic recall behavior are:
107
+
108
+ 1. **topK**: How many semantically similar messages to retrieve
109
+ 2. **messageRange**: How much surrounding context to include with each match
110
+ 3. **scope**: Whether to search within the current thread or across all threads owned by a resource (the default is resource scope).
111
+
112
+ ```typescript
113
+ const agent = new Agent({
114
+ memory: new Memory({
115
+ options: {
116
+ semanticRecall: {
117
+ topK: 3, // Retrieve 3 most similar messages
118
+ messageRange: 2, // Include 2 messages before and after each match
119
+ scope: 'resource', // Search across all threads for this user (default setting if omitted)
120
+ },
121
+ },
122
+ }),
123
+ })
124
+ ```
125
+
126
+ ## Embedder configuration
127
+
128
+ Semantic recall relies on an [embedding model](https://mastra.ai/reference/memory/memory-class) to convert messages into embeddings. Mastra supports embedding models through the model router using `provider/model` strings, or you can use any [embedding model](https://sdk.vercel.ai/docs/ai-sdk-core/embeddings) compatible with the AI SDK.
129
+
130
+ ### Using the Model Router (Recommended)
131
+
132
+ The simplest way is to use a `provider/model` string with autocomplete support:
133
+
134
+ ```ts
135
+ import { Memory } from '@mastra/memory'
136
+ import { Agent } from '@mastra/core/agent'
137
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
138
+
139
+ const agent = new Agent({
140
+ memory: new Memory({
141
+ embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
142
+ }),
143
+ })
144
+ ```
145
+
146
+ Supported embedding models:
147
+
148
+ - **OpenAI**: `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002`
149
+ - **Google**: `gemini-embedding-001`
150
+
151
+ The model router automatically handles API key detection from environment variables (`OPENAI_API_KEY`, `GOOGLE_GENERATIVE_AI_API_KEY`).
152
+
153
+ ### Using AI SDK Packages
154
+
155
+ You can also use AI SDK embedding models directly:
156
+
157
+ ```ts
158
+ import { Memory } from '@mastra/memory'
159
+ import { Agent } from '@mastra/core/agent'
160
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
161
+
162
+ const agent = new Agent({
163
+ memory: new Memory({
164
+ embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
165
+ }),
166
+ })
167
+ ```
168
+
169
+ ### Using FastEmbed (Local)
170
+
171
+ To use FastEmbed (a local embedding model), install `@mastra/fastembed`:
172
+
173
+ **npm**:
174
+
175
+ ```bash
176
+ npm install @mastra/fastembed@latest
177
+ ```
178
+
179
+ **pnpm**:
180
+
181
+ ```bash
182
+ pnpm add @mastra/fastembed@latest
183
+ ```
184
+
185
+ **Yarn**:
186
+
187
+ ```bash
188
+ yarn add @mastra/fastembed@latest
189
+ ```
190
+
191
+ **Bun**:
192
+
193
+ ```bash
194
+ bun add @mastra/fastembed@latest
195
+ ```
196
+
197
+ Then configure it in your memory:
198
+
199
+ ```ts
200
+ import { Memory } from '@mastra/memory'
201
+ import { Agent } from '@mastra/core/agent'
202
+ import { fastembed } from '@mastra/fastembed'
203
+
204
+ const agent = new Agent({
205
+ memory: new Memory({
206
+ embedder: fastembed,
207
+ }),
208
+ })
209
+ ```
210
+
211
+ ## PostgreSQL Index Optimization
212
+
213
+ When using PostgreSQL as your vector store, you can optimize semantic recall performance by configuring the vector index. This is particularly important for large-scale deployments with thousands of messages.
214
+
215
+ PostgreSQL supports both IVFFlat and HNSW indexes. By default, Mastra creates an IVFFlat index, but HNSW indexes typically provide better performance, especially with OpenAI embeddings which use inner product distance.
216
+
217
+ ```typescript
218
+ import { Memory } from '@mastra/memory'
219
+ import { PgStore, PgVector } from '@mastra/pg'
220
+
221
+ const agent = new Agent({
222
+ memory: new Memory({
223
+ storage: new PgStore({
224
+ id: 'agent-storage',
225
+ connectionString: process.env.DATABASE_URL,
226
+ }),
227
+ vector: new PgVector({
228
+ id: 'agent-vector',
229
+ connectionString: process.env.DATABASE_URL,
230
+ }),
231
+ options: {
232
+ semanticRecall: {
233
+ topK: 5,
234
+ messageRange: 2,
235
+ indexConfig: {
236
+ type: 'hnsw', // Use HNSW for better performance
237
+ metric: 'dotproduct', // Best for OpenAI embeddings
238
+ m: 16, // Number of bi-directional links (default: 16)
239
+ efConstruction: 64, // Size of candidate list during construction (default: 64)
240
+ },
241
+ },
242
+ },
243
+ }),
244
+ })
245
+ ```
246
+
247
+ For detailed information about index configuration options and performance tuning, see the [PgVector configuration guide](https://mastra.ai/reference/vectors/pg).
248
+
249
+ ## Disabling
250
+
251
+ There is a performance impact to using semantic recall. New messages are converted into embeddings and used to query a vector database before new messages are sent to the LLM.
252
+
253
+ Semantic recall is enabled by default but can be disabled when not needed:
254
+
255
+ ```typescript
256
+ const agent = new Agent({
257
+ memory: new Memory({
258
+ options: {
259
+ semanticRecall: false,
260
+ },
261
+ }),
262
+ })
263
+ ```
264
+
265
+ You might want to disable semantic recall in scenarios like:
266
+
267
+ - When message history provides sufficient context for the current conversation.
268
+ - In performance-sensitive applications, like realtime two-way audio, where the added latency of creating embeddings and running vector queries is noticeable.
269
+
270
+ ## Viewing Recalled Messages
271
+
272
+ When tracing is enabled, any messages retrieved via semantic recall will appear in the agent's trace output, alongside recent message history (if configured).