@mastra/memory 0.0.0-afterToolExecute-20250414225911

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/src/index.ts ADDED
@@ -0,0 +1,537 @@
1
+ import { deepMerge } from '@mastra/core';
2
+ import type { AiMessageType, CoreMessage, CoreTool } from '@mastra/core';
3
+ import { MastraMemory } from '@mastra/core/memory';
4
+ import type { MessageType, MemoryConfig, SharedMemoryConfig, StorageThreadType } from '@mastra/core/memory';
5
+ import type { StorageGetMessagesArg } from '@mastra/core/storage';
6
+ import { embedMany } from 'ai';
7
+ import { Tiktoken } from 'js-tiktoken/lite';
8
+ import o200k_base from 'js-tiktoken/ranks/o200k_base';
9
+ import xxhash from 'xxhash-wasm';
10
+ import { updateWorkingMemoryTool } from './tools/working-memory';
11
+
12
+ const encoder = new Tiktoken(o200k_base);
13
+
14
+ /**
15
+ * Concrete implementation of MastraMemory that adds support for thread configuration
16
+ * and message injection.
17
+ */
18
+ export class Memory extends MastraMemory {
19
+ constructor(config: SharedMemoryConfig = {}) {
20
+ super({ name: 'Memory', ...config });
21
+
22
+ const mergedConfig = this.getMergedThreadConfig({
23
+ workingMemory: config.options?.workingMemory || {
24
+ enabled: false,
25
+ template: this.defaultWorkingMemoryTemplate,
26
+ },
27
+ });
28
+ this.threadConfig = mergedConfig;
29
+ }
30
+
31
+ private async validateThreadIsOwnedByResource(threadId: string, resourceId: string) {
32
+ const thread = await this.storage.getThreadById({ threadId });
33
+ if (!thread) {
34
+ throw new Error(`No thread found with id ${threadId}`);
35
+ }
36
+ if (thread.resourceId !== resourceId) {
37
+ throw new Error(
38
+ `Thread with id ${threadId} is for resource with id ${thread.resourceId} but resource ${resourceId} was queried.`,
39
+ );
40
+ }
41
+ }
42
+
43
+ async query({
44
+ threadId,
45
+ resourceId,
46
+ selectBy,
47
+ threadConfig,
48
+ }: StorageGetMessagesArg & {
49
+ threadConfig?: MemoryConfig;
50
+ }): Promise<{ messages: CoreMessage[]; uiMessages: AiMessageType[] }> {
51
+ if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId);
52
+
53
+ const vectorResults: {
54
+ id: string;
55
+ score: number;
56
+ metadata?: Record<string, any>;
57
+ vector?: number[];
58
+ }[] = [];
59
+
60
+ this.logger.debug(`Memory query() with:`, {
61
+ threadId,
62
+ selectBy,
63
+ threadConfig,
64
+ });
65
+
66
+ const config = this.getMergedThreadConfig(threadConfig || {});
67
+
68
+ const vectorConfig =
69
+ typeof config?.semanticRecall === `boolean`
70
+ ? {
71
+ topK: 2,
72
+ messageRange: { before: 2, after: 2 },
73
+ }
74
+ : {
75
+ topK: config?.semanticRecall?.topK ?? 2,
76
+ messageRange: config?.semanticRecall?.messageRange ?? { before: 2, after: 2 },
77
+ };
78
+
79
+ if (config?.semanticRecall && selectBy?.vectorSearchString && this.vector && !!selectBy.vectorSearchString) {
80
+ const { embeddings, dimension } = await this.embedMessageContent(selectBy.vectorSearchString!);
81
+ const { indexName } = await this.createEmbeddingIndex(dimension);
82
+
83
+ await Promise.all(
84
+ embeddings.map(async embedding => {
85
+ if (typeof this.vector === `undefined`) {
86
+ throw new Error(
87
+ `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`,
88
+ );
89
+ }
90
+
91
+ vectorResults.push(
92
+ ...(await this.vector.query({
93
+ indexName,
94
+ queryVector: embedding,
95
+ topK: vectorConfig.topK,
96
+ filter: {
97
+ thread_id: threadId,
98
+ },
99
+ })),
100
+ );
101
+ }),
102
+ );
103
+ }
104
+
105
+ // Get raw messages from storage
106
+ const rawMessages = await this.storage.__getMessages({
107
+ threadId,
108
+ selectBy: {
109
+ ...selectBy,
110
+ ...(vectorResults?.length
111
+ ? {
112
+ include: vectorResults.map(r => ({
113
+ id: r.metadata?.message_id,
114
+ withNextMessages:
115
+ typeof vectorConfig.messageRange === 'number'
116
+ ? vectorConfig.messageRange
117
+ : vectorConfig.messageRange.after,
118
+ withPreviousMessages:
119
+ typeof vectorConfig.messageRange === 'number'
120
+ ? vectorConfig.messageRange
121
+ : vectorConfig.messageRange.before,
122
+ })),
123
+ }
124
+ : {}),
125
+ },
126
+ threadConfig: config,
127
+ });
128
+
129
+ // Parse and convert messages
130
+ const messages = this.parseMessages(rawMessages);
131
+ const uiMessages = this.convertToUIMessages(rawMessages);
132
+
133
+ return { messages, uiMessages };
134
+ }
135
+
136
+ async rememberMessages({
137
+ threadId,
138
+ resourceId,
139
+ vectorMessageSearch,
140
+ config,
141
+ }: {
142
+ threadId: string;
143
+ resourceId?: string;
144
+ vectorMessageSearch?: string;
145
+ config?: MemoryConfig;
146
+ }): Promise<{
147
+ threadId: string;
148
+ messages: CoreMessage[];
149
+ uiMessages: AiMessageType[];
150
+ }> {
151
+ if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId);
152
+ const threadConfig = this.getMergedThreadConfig(config || {});
153
+
154
+ if (!threadConfig.lastMessages && !threadConfig.semanticRecall) {
155
+ return {
156
+ messages: [],
157
+ uiMessages: [],
158
+ threadId,
159
+ };
160
+ }
161
+
162
+ const messagesResult = await this.query({
163
+ threadId,
164
+ selectBy: {
165
+ last: threadConfig.lastMessages,
166
+ vectorSearchString: threadConfig.semanticRecall && vectorMessageSearch ? vectorMessageSearch : undefined,
167
+ },
168
+ threadConfig: config,
169
+ });
170
+
171
+ this.logger.debug(`Remembered message history includes ${messagesResult.messages.length} messages.`);
172
+ return {
173
+ threadId,
174
+ messages: messagesResult.messages,
175
+ uiMessages: messagesResult.uiMessages,
176
+ };
177
+ }
178
+
179
+ async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {
180
+ return this.storage.__getThreadById({ threadId });
181
+ }
182
+
183
+ async getThreadsByResourceId({ resourceId }: { resourceId: string }): Promise<StorageThreadType[]> {
184
+ return this.storage.__getThreadsByResourceId({ resourceId });
185
+ }
186
+
187
+ async saveThread({
188
+ thread,
189
+ memoryConfig,
190
+ }: {
191
+ thread: StorageThreadType;
192
+ memoryConfig?: MemoryConfig;
193
+ }): Promise<StorageThreadType> {
194
+ const config = this.getMergedThreadConfig(memoryConfig || {});
195
+
196
+ if (config.workingMemory?.enabled && !thread?.metadata?.workingMemory) {
197
+ // if working memory is enabled but the thread doesn't have it, we need to set it
198
+ return this.storage.__saveThread({
199
+ thread: deepMerge(thread, {
200
+ metadata: {
201
+ workingMemory: config.workingMemory.template || this.defaultWorkingMemoryTemplate,
202
+ },
203
+ }),
204
+ });
205
+ }
206
+
207
+ return this.storage.__saveThread({ thread });
208
+ }
209
+
210
+ async updateThread({
211
+ id,
212
+ title,
213
+ metadata,
214
+ }: {
215
+ id: string;
216
+ title: string;
217
+ metadata: Record<string, unknown>;
218
+ }): Promise<StorageThreadType> {
219
+ return this.storage.__updateThread({
220
+ id,
221
+ title,
222
+ metadata,
223
+ });
224
+ }
225
+
226
+ async deleteThread(threadId: string): Promise<void> {
227
+ await this.storage.__deleteThread({ threadId });
228
+ }
229
+
230
+ private chunkText(text: string, size = 4096) {
231
+ const tokens = encoder.encode(text);
232
+ const chunks: string[] = [];
233
+ let currentChunk: number[] = [];
234
+
235
+ for (const token of tokens) {
236
+ currentChunk.push(token);
237
+
238
+ // If current chunk reaches size limit, add it to chunks and start a new one
239
+ if (currentChunk.length >= size) {
240
+ chunks.push(encoder.decode(currentChunk));
241
+ currentChunk = [];
242
+ }
243
+ }
244
+
245
+ // Add any remaining tokens as the final chunk
246
+ if (currentChunk.length > 0) {
247
+ chunks.push(encoder.decode(currentChunk));
248
+ }
249
+
250
+ return chunks;
251
+ }
252
+
253
+ private hasher = xxhash();
254
+
255
+ // embedding is computationally expensive so cache content -> embeddings/chunks
256
+ private embeddingCache = new Map<
257
+ number,
258
+ {
259
+ chunks: string[];
260
+ embeddings: Awaited<ReturnType<typeof embedMany>>['embeddings'];
261
+ dimension: number | undefined;
262
+ }
263
+ >();
264
+ private firstEmbed: Promise<any> | undefined;
265
+ private async embedMessageContent(content: string) {
266
+ // use fast xxhash for lower memory usage. if we cache by content string we will store all messages in memory for the life of the process
267
+ const key = (await this.hasher).h32(content);
268
+ const cached = this.embeddingCache.get(key);
269
+ if (cached) return cached;
270
+ const chunks = this.chunkText(content);
271
+
272
+ if (typeof this.embedder === `undefined`) {
273
+ throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
274
+ }
275
+ // for fastembed multiple initial calls to embed will fail if the model hasn't been downloaded yet.
276
+ const isFastEmbed = this.embedder.provider === `fastembed`;
277
+ if (isFastEmbed && this.firstEmbed instanceof Promise) {
278
+ // so wait for the first one
279
+ await this.firstEmbed;
280
+ }
281
+
282
+ const promise = embedMany({
283
+ values: chunks,
284
+ model: this.embedder,
285
+ maxRetries: 3,
286
+ });
287
+
288
+ if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;
289
+ const { embeddings } = await promise;
290
+
291
+ const result = {
292
+ embeddings,
293
+ chunks,
294
+ dimension: embeddings[0]?.length,
295
+ };
296
+ this.embeddingCache.set(key, result);
297
+ return result;
298
+ }
299
+
300
+ async saveMessages({
301
+ messages,
302
+ memoryConfig,
303
+ }: {
304
+ messages: MessageType[];
305
+ memoryConfig?: MemoryConfig;
306
+ }): Promise<MessageType[]> {
307
+ // First save working memory from any messages
308
+ await this.saveWorkingMemory(messages);
309
+
310
+ // Then strip working memory tags from all messages
311
+ this.mutateMessagesToHideWorkingMemory(messages);
312
+
313
+ const config = this.getMergedThreadConfig(memoryConfig);
314
+
315
+ const result = this.storage.__saveMessages({ messages });
316
+
317
+ if (this.vector && config.semanticRecall) {
318
+ let indexName: Promise<string>;
319
+ await Promise.all(
320
+ messages.map(async message => {
321
+ if (typeof message.content !== `string` || message.content === '') return;
322
+
323
+ const { embeddings, chunks, dimension } = await this.embedMessageContent(message.content);
324
+
325
+ if (typeof indexName === `undefined`) {
326
+ indexName = this.createEmbeddingIndex(dimension).then(result => result.indexName);
327
+ }
328
+
329
+ if (typeof this.vector === `undefined`) {
330
+ throw new Error(
331
+ `Tried to upsert embeddings to index ${indexName} but this Memory instance doesn't have an attached vector db.`,
332
+ );
333
+ }
334
+
335
+ await this.vector.upsert({
336
+ indexName: await indexName,
337
+ vectors: embeddings,
338
+ metadata: chunks.map(() => ({
339
+ message_id: message.id,
340
+ thread_id: message.threadId,
341
+ resource_id: message.resourceId,
342
+ })),
343
+ });
344
+ }),
345
+ );
346
+ }
347
+
348
+ return result;
349
+ }
350
+
351
+ protected mutateMessagesToHideWorkingMemory(messages: MessageType[]) {
352
+ const workingMemoryRegex = /<working_memory>([^]*?)<\/working_memory>/g;
353
+
354
+ for (const [index, message] of messages.entries()) {
355
+ if (typeof message?.content === `string`) {
356
+ message.content = message.content.replace(workingMemoryRegex, ``).trim();
357
+ } else if (Array.isArray(message?.content)) {
358
+ for (const content of message.content) {
359
+ if (content.type === `text`) {
360
+ content.text = content.text.replace(workingMemoryRegex, ``).trim();
361
+ }
362
+
363
+ if (
364
+ (content.type === `tool-call` || content.type === `tool-result`) &&
365
+ content.toolName === `updateWorkingMemory`
366
+ ) {
367
+ delete messages[index];
368
+ }
369
+ }
370
+ }
371
+ }
372
+ }
373
+
374
+ protected parseWorkingMemory(text: string): string | null {
375
+ if (!this.threadConfig.workingMemory?.enabled) return null;
376
+
377
+ const workingMemoryRegex = /<working_memory>([^]*?)<\/working_memory>/g;
378
+ const matches = text.match(workingMemoryRegex);
379
+ const match = matches?.[0];
380
+
381
+ if (match) {
382
+ return match.replace(/<\/?working_memory>/g, '').trim();
383
+ }
384
+
385
+ return null;
386
+ }
387
+
388
+ public async getWorkingMemory({ threadId }: { threadId: string }): Promise<string | null> {
389
+ if (!this.threadConfig.workingMemory?.enabled) return null;
390
+
391
+ // Get thread from storage
392
+ const thread = await this.storage.__getThreadById({ threadId });
393
+ if (!thread) return this.threadConfig?.workingMemory?.template || this.defaultWorkingMemoryTemplate;
394
+
395
+ // Return working memory from metadata
396
+ const memory =
397
+ (thread.metadata?.workingMemory as string) ||
398
+ this.threadConfig.workingMemory.template ||
399
+ this.defaultWorkingMemoryTemplate;
400
+
401
+ return memory.trim();
402
+ }
403
+
404
+ private async saveWorkingMemory(messages: MessageType[]) {
405
+ const latestMessage = messages[messages.length - 1];
406
+
407
+ if (!latestMessage || !this.threadConfig.workingMemory?.enabled) {
408
+ return;
409
+ }
410
+
411
+ const latestContent = !latestMessage?.content
412
+ ? null
413
+ : typeof latestMessage.content === 'string'
414
+ ? latestMessage.content
415
+ : latestMessage.content
416
+ .filter(c => c.type === 'text')
417
+ .map(c => c.text)
418
+ .join('\n');
419
+
420
+ const threadId = latestMessage?.threadId;
421
+ if (!latestContent || !threadId) {
422
+ return;
423
+ }
424
+
425
+ const newMemory = this.parseWorkingMemory(latestContent);
426
+ if (!newMemory) {
427
+ return;
428
+ }
429
+
430
+ const thread = await this.storage.__getThreadById({ threadId });
431
+ if (!thread) return;
432
+
433
+ // Update thread metadata with new working memory
434
+ await this.storage.__updateThread({
435
+ id: thread.id,
436
+ title: thread.title || '',
437
+ metadata: deepMerge(thread.metadata || {}, {
438
+ workingMemory: newMemory,
439
+ }),
440
+ });
441
+ return newMemory;
442
+ }
443
+
444
+ public async getSystemMessage({
445
+ threadId,
446
+ memoryConfig,
447
+ }: {
448
+ threadId: string;
449
+ memoryConfig?: MemoryConfig;
450
+ }): Promise<string | null> {
451
+ const config = this.getMergedThreadConfig(memoryConfig);
452
+ if (!config.workingMemory?.enabled) {
453
+ return null;
454
+ }
455
+
456
+ const workingMemory = await this.getWorkingMemory({ threadId });
457
+ if (!workingMemory) {
458
+ return null;
459
+ }
460
+
461
+ if (config.workingMemory.use === 'tool-call') {
462
+ return this.getWorkingMemoryToolInstruction(workingMemory);
463
+ }
464
+
465
+ return this.getWorkingMemoryWithInstruction(workingMemory);
466
+ }
467
+
468
+ public defaultWorkingMemoryTemplate = `
469
+ # User Information
470
+ - **First Name**:
471
+ - **Last Name**:
472
+ - **Location**:
473
+ - **Occupation**:
474
+ - **Interests**:
475
+ - **Goals**:
476
+ - **Events**:
477
+ - **Facts**:
478
+ - **Projects**:
479
+ `;
480
+
481
+ private getWorkingMemoryWithInstruction(workingMemoryBlock: string) {
482
+ return `WORKING_MEMORY_SYSTEM_INSTRUCTION:
483
+ Store and update any conversation-relevant information by including "<working_memory>text</working_memory>" in your responses. Updates replace existing memory while maintaining this structure. If information might be referenced again - store it!
484
+
485
+ Guidelines:
486
+ 1. Store anything that could be useful later in the conversation
487
+ 2. Update proactively when information changes, no matter how small
488
+ 3. Use Markdown for all data
489
+ 4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for "information about yourself"
490
+
491
+ Memory Structure:
492
+ <working_memory>
493
+ ${workingMemoryBlock}
494
+ </working_memory>
495
+
496
+ Notes:
497
+ - Update memory whenever referenced information changes
498
+ - If you're unsure whether to store something, store it (eg if the user tells you their name or other information, output the <working_memory> block immediately to update it)
499
+ - This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history
500
+ - REMEMBER: the way you update your working memory is by outputting the entire "<working_memory>text</working_memory>" block in your response. The system will pick this up and store it for you. The user will not see it.
501
+ - IMPORTANT: You MUST output the <working_memory> block in every response to a prompt where you received relevant information.
502
+ - IMPORTANT: Preserve the Markdown formatting structure above while updating the content.`;
503
+ }
504
+
505
+ private getWorkingMemoryToolInstruction(workingMemoryBlock: string) {
506
+ return `WORKING_MEMORY_SYSTEM_INSTRUCTION:
507
+ Store and update any conversation-relevant information by calling the updateWorkingMemory tool. If information might be referenced again - store it!
508
+
509
+ Guidelines:
510
+ 1. Store anything that could be useful later in the conversation
511
+ 2. Update proactively when information changes, no matter how small
512
+ 3. Use Markdown format for all data
513
+ 4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for "information about yourself"
514
+
515
+ Memory Structure:
516
+ ${workingMemoryBlock}
517
+
518
+ Notes:
519
+ - Update memory whenever referenced information changes
520
+ - If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)
521
+ - This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history
522
+ - Do not remove empty sections - you must include the empty sections along with the ones you're filling in
523
+ - REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the entire Markdown content. The system will store it for you. The user will not see it.
524
+ - IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information.
525
+ - IMPORTANT: Preserve the Markdown formatting structure above while updating the content.`;
526
+ }
527
+
528
+ public getTools(config?: MemoryConfig): Record<string, CoreTool> {
529
+ const mergedConfig = this.getMergedThreadConfig(config);
530
+ if (mergedConfig.workingMemory?.enabled && mergedConfig.workingMemory.use === 'tool-call') {
531
+ return {
532
+ updateWorkingMemory: updateWorkingMemoryTool,
533
+ };
534
+ }
535
+ return {};
536
+ }
537
+ }