跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Memory API

The Memory API provides methods to manage conversation threads and message history in Mastra.

Get all threads
Get all threads的直接链接

Retrieve all memory threads for a specific resource:

const threads = await mastraClient.listMemoryThreads({
resourceId: 'resource-1',
agentId: 'agent-1', // Optional - can be omitted if storage is configured
})

When agentId is omitted and storage is configured on the server, threads will be retrieved using storage directly. This is useful when multiple agents share the same threads (e.g., in workflows with multiple agent steps).

Create a new thread
Create a new thread的直接链接

Create a new memory thread:

const thread = await mastraClient.createMemoryThread({
title: 'New Conversation',
metadata: { category: 'support' },
resourceId: 'resource-1',
agentId: 'agent-1',
})

Working with a specific thread
Working with a specific thread的直接链接

Get an instance of a specific memory thread:

const thread = mastraClient.getMemoryThread({ threadId: 'thread-id', agentId: 'agent-id' })

Thread methods
Thread methods的直接链接

Get Thread Details
Get Thread Details的直接链接

Retrieve details about a specific thread:

const details = await thread.get()

Update Thread
Update Thread的直接链接

Update thread properties:

const updated = await thread.update({
title: 'Updated Title',
metadata: { status: 'resolved' },
resourceId: 'resource-1',
})

Delete Thread
Delete Thread的直接链接

Delete a thread and its messages:

await thread.delete()

Clone Thread
Clone Thread的直接链接

Create a copy of a thread with all its messages:

const { thread: clonedThread, clonedMessages } = await thread.clone()

Clone with options:

const { thread: clonedThread, clonedMessages } = await thread.clone({
newThreadId: 'custom-clone-id',
title: 'Cloned Conversation',
metadata: { branch: 'experiment-1' },
options: {
messageLimit: 10, // Only clone last 10 messages
},
})

Clone with message filtering:

const { thread: clonedThread } = await thread.clone({
options: {
messageFilter: {
startDate: new Date('2024-01-01'),
endDate: new Date('2024-01-31'),
},
},
})

The clone response includes:

  • thread: The newly created cloned thread with clone metadata
  • clonedMessages: Array of the cloned messages with new IDs

Message operations
Message operations的直接链接

Save Messages
Save Messages的直接链接

Save messages to memory:

const result = await mastraClient.saveMessageToMemory({
messages: [
{
role: 'user',
content: 'Hello!',
id: '1',
threadId: 'thread-1',
resourceId: 'resource-1',
createdAt: new Date(),
format: 2,
},
],
agentId: 'agent-1',
})

// result.messages contains the saved messages
console.log(result.messages)

Retrieve Thread Messages
Retrieve Thread Messages的直接链接

Get messages associated with a memory thread:

// Get all messages in the thread (paginated)
const result = await thread.listMessages()
console.log(result.messages) // Array of messages
console.log(result.total) // Total count
console.log(result.hasMore) // Whether more pages exist

// Get messages with pagination
const result = await thread.listMessages({
page: 0,
perPage: 20,
})

// Get messages with ordering
const result = await thread.listMessages({
orderBy: { field: 'createdAt', direction: 'ASC' },
})

// Get messages with shallow metadata filters
const result = await thread.listMessages({
filter: {
metadata: {
category: 'billing',
escalated: true,
priority: 2,
archivedAt: null,
},
},
})

Metadata filters match shallow scalar values only: string, finite number, boolean, and null. Every key-value pair must match with AND semantics. null matches only keys explicitly set to null. Metadata keys must start with a letter or underscore and contain only alphanumeric or underscore characters. The limit is 128 characters. Reserved prototype keys such as __proto__, constructor, and prototype aren't allowed. Performance depends on the server storage backend, and arbitrary metadata filters may scan candidate messages.

Delete Messages
Delete Messages的直接链接

Delete one or more messages from a thread:

// Delete a single message
const result = await thread.deleteMessages('message-id')

// Delete multiple messages
const result = await thread.deleteMessages(['message-1', 'message-2', 'message-3'])

// Returns: { success: true, message: "Message deleted successfully" }

Working memory
Working memory的直接链接

Working memory allows agents to maintain persistent information about users across interactions. It can be scoped to either a specific thread or across all threads for a resource (user).

Get Working Memory
Get Working Memory的直接链接

Retrieve the current working memory for a thread:

const workingMemory = await mastraClient.getWorkingMemory({
agentId: 'agent-1',
threadId: 'thread-1',
resourceId: 'user-123', // Optional, required for resource-scoped memory
})

The response includes:

  • workingMemory: The current working memory content (a string or null). When using a JSON or schema-based working memory template, the content is a JSON-encoded string
  • source: Whether the memory is from "thread" or "resource" scope
  • workingMemoryTemplate: The template used for working memory (if configured)
  • threadExists: Whether the thread exists

Update Working Memory
Update Working Memory的直接链接

Update the working memory content for a thread:

await mastraClient.updateWorkingMemory({
agentId: 'agent-1',
threadId: 'thread-1',
workingMemory: `# User Profile
- Name: John Doe
- Location: New York
- Preferences: Prefers formal communication
`,
resourceId: 'user-123', // Optional, required for resource-scoped memory
})

// Returns: { success: true }

For resource-scoped working memory, you must provide the resourceId parameter. It allows the memory to persist across all conversation threads for that user.

By default the call replaces the whole record. For schema-based, resource-scoped working memory, pass mode: 'merge' with a JSON object string to deep-merge only the provided fields atomically. The server returns 400 if the storage adapter doesn't support atomic merges (currently only @mastra/pg does).

await mastraClient.updateWorkingMemory({
agentId: 'agent-1',
threadId: 'thread-1',
resourceId: 'user-123',
workingMemory: JSON.stringify({ city: 'Berlin' }),
mode: 'merge',
})

Get Memory Status
Get Memory Status的直接链接

Check the status of the memory system:

const status = await mastraClient.getMemoryStatus('agent-id')