@mastra/openai 1.0.1-alpha.8 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,314 @@
1
+ # Memory processors
2
+
3
+ Memory processors transform and filter messages as they pass through an agent with memory enabled. They manage context window limits, remove unnecessary content, and optimize the information sent to the language model.
4
+
5
+ When memory is enabled on an agent, Mastra adds memory processors to the agent's processor pipeline. These processors retrieve message history, working memory, and semantically relevant messages, then persist new messages after the model responds.
6
+
7
+ Memory processors are [processors](https://mastra.ai/docs/agents/processors) that operate specifically on memory-related messages and state.
8
+
9
+ ## Built-in memory processors
10
+
11
+ Mastra automatically adds these processors when memory is enabled:
12
+
13
+ ### `MessageHistory`
14
+
15
+ Retrieves message history and persists new messages.
16
+
17
+ **When you configure:**
18
+
19
+ ```typescript
20
+ memory: new Memory({
21
+ lastMessages: 10,
22
+ })
23
+ ```
24
+
25
+ **Mastra internally:**
26
+
27
+ 1. Creates a `MessageHistory` processor with `limit: 10`
28
+ 2. Adds it to the agent's input processors (runs before the LLM)
29
+ 3. Adds it to the agent's output processors (runs after the LLM)
30
+
31
+ **What it does:**
32
+
33
+ - **Input**: Fetches the last 10 messages from storage and prepends them to the conversation
34
+ - **Output**: Persists new messages to storage after the model responds
35
+
36
+ **Example:**
37
+
38
+ ```typescript
39
+ import { Agent } from '@mastra/core/agent'
40
+ import { Memory } from '@mastra/memory'
41
+ import { LibSQLStore } from '@mastra/libsql'
42
+ import { openai } from '@ai-sdk/openai'
43
+
44
+ const agent = new Agent({
45
+ id: 'test-agent',
46
+ name: 'Test Agent',
47
+ instructions: 'You are a helpful assistant',
48
+ model: 'openai/gpt-5.5',
49
+ memory: new Memory({
50
+ storage: new LibSQLStore({
51
+ id: 'memory-store',
52
+ url: 'file:memory.db',
53
+ }),
54
+ lastMessages: 10, // MessageHistory processor automatically added
55
+ }),
56
+ })
57
+ ```
58
+
59
+ ### `SemanticRecall`
60
+
61
+ Retrieves semantically relevant messages based on the current input and creates embeddings for new messages.
62
+
63
+ **When you configure:**
64
+
65
+ ```typescript
66
+ memory: new Memory({
67
+ semanticRecall: { enabled: true },
68
+ vector: myVectorStore,
69
+ embedder: myEmbedder,
70
+ })
71
+ ```
72
+
73
+ **Mastra internally:**
74
+
75
+ 1. Creates a `SemanticRecall` processor
76
+ 2. Adds it to the agent's input processors (runs before the LLM)
77
+ 3. Adds it to the agent's output processors (runs after the LLM)
78
+ 4. Requires both a vector store and embedder to be configured
79
+
80
+ **What it does:**
81
+
82
+ - **Input**: Performs vector similarity search to find relevant past messages and prepends them to the conversation
83
+ - **Output**: Creates embeddings for new messages and stores them in the vector store for future retrieval
84
+
85
+ **Example:**
86
+
87
+ ```typescript
88
+ import { Agent } from '@mastra/core/agent'
89
+ import { Memory } from '@mastra/memory'
90
+ import { LibSQLStore } from '@mastra/libsql'
91
+ import { PineconeVector } from '@mastra/pinecone'
92
+ import { OpenAIEmbedder } from '@mastra/openai'
93
+ import { openai } from '@ai-sdk/openai'
94
+
95
+ const agent = new Agent({
96
+ name: 'semantic-agent',
97
+ instructions: 'You are a helpful assistant with semantic memory',
98
+ model: 'openai/gpt-5.5',
99
+ memory: new Memory({
100
+ storage: new LibSQLStore({
101
+ id: 'memory-store',
102
+ url: 'file:memory.db',
103
+ }),
104
+ vector: new PineconeVector({
105
+ id: 'memory-vector',
106
+ apiKey: process.env.PINECONE_API_KEY!,
107
+ }),
108
+ embedder: new OpenAIEmbedder({
109
+ model: 'text-embedding-3-small',
110
+ apiKey: process.env.OPENAI_API_KEY!,
111
+ }),
112
+ semanticRecall: { enabled: true }, // SemanticRecall processor automatically added
113
+ }),
114
+ })
115
+ ```
116
+
117
+ ### `WorkingMemory`
118
+
119
+ Manages working memory state across conversations.
120
+
121
+ **When you configure:**
122
+
123
+ ```typescript
124
+ memory: new Memory({
125
+ workingMemory: { enabled: true },
126
+ })
127
+ ```
128
+
129
+ **Mastra internally:**
130
+
131
+ 1. Creates a `WorkingMemory` processor
132
+ 2. Adds it to the agent's input processors (runs before the LLM)
133
+ 3. Requires a storage adapter to be configured
134
+
135
+ **What it does:**
136
+
137
+ - **Input**: Retrieves working memory state for the current thread and prepends it to the conversation
138
+ - **Output**: No output processing
139
+
140
+ **Example:**
141
+
142
+ ```typescript
143
+ import { Agent } from '@mastra/core/agent'
144
+ import { Memory } from '@mastra/memory'
145
+ import { LibSQLStore } from '@mastra/libsql'
146
+ import { openai } from '@ai-sdk/openai'
147
+
148
+ const agent = new Agent({
149
+ name: 'working-memory-agent',
150
+ instructions: 'You are an assistant with working memory',
151
+ model: 'openai/gpt-5.5',
152
+ memory: new Memory({
153
+ storage: new LibSQLStore({
154
+ id: 'memory-store',
155
+ url: 'file:memory.db',
156
+ }),
157
+ workingMemory: { enabled: true }, // WorkingMemory processor automatically added
158
+ }),
159
+ })
160
+ ```
161
+
162
+ ## Manual control and deduplication
163
+
164
+ If you manually add a memory processor to `inputProcessors` or `outputProcessors`, Mastra **won't** automatically add it. This gives you full control over processor ordering:
165
+
166
+ ```typescript
167
+ import { Agent } from '@mastra/core/agent'
168
+ import { Memory } from '@mastra/memory'
169
+ import { MessageHistory } from '@mastra/core/processors'
170
+ import { TokenLimiter } from '@mastra/core/processors'
171
+ import { LibSQLStore } from '@mastra/libsql'
172
+ import { openai } from '@ai-sdk/openai'
173
+
174
+ // Custom MessageHistory with different configuration
175
+ const customMessageHistory = new MessageHistory({
176
+ storage: new LibSQLStore({ id: 'memory-store', url: 'file:memory.db' }),
177
+ lastMessages: 20,
178
+ })
179
+
180
+ const agent = new Agent({
181
+ name: 'custom-memory-agent',
182
+ instructions: 'You are a helpful assistant',
183
+ model: 'openai/gpt-5.5',
184
+ memory: new Memory({
185
+ storage: new LibSQLStore({ id: 'memory-store', url: 'file:memory.db' }),
186
+ lastMessages: 10, // This would normally add MessageHistory(10)
187
+ }),
188
+ inputProcessors: [
189
+ customMessageHistory, // Your custom one is used instead
190
+ new TokenLimiter({ limit: 4000 }), // Runs after your custom MessageHistory
191
+ ],
192
+ })
193
+ ```
194
+
195
+ ## Processor execution order
196
+
197
+ Understanding the execution order is important when combining guardrails with memory:
198
+
199
+ ### Input Processors
200
+
201
+ ```text
202
+ [Memory Processors] → [Your inputProcessors]
203
+ ```
204
+
205
+ 1. **Memory processors run FIRST**: `WorkingMemory`, `MessageHistory`, `SemanticRecall`
206
+ 2. **Your input processors run AFTER**: guardrails, filters, validators
207
+
208
+ This means memory loads message history before your processors can validate or filter the input.
209
+
210
+ ### Output Processors
211
+
212
+ ```text
213
+ [Your outputProcessors] → [Memory Processors]
214
+ ```
215
+
216
+ 1. **Your output processors run FIRST**: guardrails, filters, validators
217
+ 2. **Memory processors run AFTER**: `SemanticRecall` (embeddings), `MessageHistory` (persistence)
218
+
219
+ This ordering is designed to be **safe by default**: if your output guardrail calls `abort()`, the memory processors never run and **no messages are saved**.
220
+
221
+ ## Guardrails and memory
222
+
223
+ The default execution order provides safe guardrail behavior:
224
+
225
+ ### Output guardrails (recommended)
226
+
227
+ Output guardrails run **before** memory processors save messages. If a guardrail aborts:
228
+
229
+ - The tripwire is triggered
230
+ - Memory processors are skipped
231
+ - **No messages are persisted to storage**
232
+
233
+ ```typescript
234
+ import { Agent } from '@mastra/core/agent'
235
+ import { Memory } from '@mastra/memory'
236
+ import { openai } from '@ai-sdk/openai'
237
+
238
+ // Output guardrail that blocks inappropriate content
239
+ const contentBlocker = {
240
+ id: 'content-blocker',
241
+ processOutputResult: async ({ messages, abort }) => {
242
+ const hasInappropriateContent = messages.some(msg => containsBadContent(msg))
243
+ if (hasInappropriateContent) {
244
+ abort('Content blocked by guardrail')
245
+ }
246
+ return messages
247
+ },
248
+ }
249
+
250
+ const agent = new Agent({
251
+ name: 'safe-agent',
252
+ instructions: 'You are a helpful assistant',
253
+ model: 'openai/gpt-5.5',
254
+ memory: new Memory({ lastMessages: 10 }),
255
+ // Your guardrail runs BEFORE memory saves
256
+ outputProcessors: [contentBlocker],
257
+ })
258
+
259
+ // If the guardrail aborts, nothing is saved to memory
260
+ const result = await agent.generate('Hello')
261
+ if (result.tripwire) {
262
+ console.log('Blocked:', result.tripwire.reason)
263
+ // Memory is empty - no messages were persisted
264
+ }
265
+ ```
266
+
267
+ ### Input guardrails
268
+
269
+ Input guardrails run **after** memory processors load history. If a guardrail aborts:
270
+
271
+ - The tripwire is triggered
272
+ - The LLM is never called
273
+ - Output processors (including memory persistence) are skipped
274
+ - **No messages are persisted to storage**
275
+
276
+ ```typescript
277
+ // Input guardrail that validates user input
278
+ const inputValidator = {
279
+ id: 'input-validator',
280
+ processInput: async ({ messages, abort }) => {
281
+ const lastUserMessage = messages.findLast(m => m.role === 'user')
282
+ if (isInvalidInput(lastUserMessage)) {
283
+ abort('Invalid input detected')
284
+ }
285
+ return messages
286
+ },
287
+ }
288
+
289
+ const agent = new Agent({
290
+ name: 'validated-agent',
291
+ instructions: 'You are a helpful assistant',
292
+ model: 'openai/gpt-5.5',
293
+ memory: new Memory({ lastMessages: 10 }),
294
+ // Your guardrail runs AFTER memory loads history
295
+ inputProcessors: [inputValidator],
296
+ })
297
+ ```
298
+
299
+ ### Summary
300
+
301
+ | Guardrail Type | When it runs | If it aborts |
302
+ | -------------- | -------------------------- | ----------------------------- |
303
+ | Input | After memory loads history | LLM not called, nothing saved |
304
+ | Output | Before memory saves | Nothing saved to storage |
305
+
306
+ Both scenarios are safe - guardrails prevent inappropriate content from being persisted to memory
307
+
308
+ ## Related documentation
309
+
310
+ - [Processors](https://mastra.ai/docs/agents/processors): General processor concepts and custom processor creation
311
+ - [Guardrails](https://mastra.ai/docs/agents/guardrails): Security and validation processors
312
+ - [Memory Overview](https://mastra.ai/docs/memory/overview): Memory types and configuration
313
+
314
+ When creating custom processors avoid mutating the input `messages` array or its objects directly.