query
Retrieves messages from a specific thread, with support for pagination and filtering options.
Usage Example
import { Memory } from "@mastra/memory";
const memory = new Memory({
/* config */
});
// Get last 50 messages
const { messages, uiMessages } = await memory.query({
threadId: "thread-123",
selectBy: {
last: 50,
},
});
// Get messages with context around specific messages
const { messages: contextMessages } = await memory.query({
threadId: "thread-123",
selectBy: {
include: [
{
id: "msg-123", // Get just this message (no context)
},
{
id: "msg-456", // Get this message with custom context
withPreviousMessages: 3, // 3 messages before
withNextMessages: 1, // 1 message after
},
],
},
});
// Semantic search in messages
const { messages } = await memory.query({
threadId: "thread-123",
selectBy: {
vectorSearchString: "What was discussed about deployment?",
},
threadConfig: {
historySearch: true,
},
});
Parameters
threadId:
string
The unique identifier of the thread to retrieve messages from
selectBy?:
object
Options for filtering messages
threadConfig?:
MemoryConfig
Configuration options for message retrieval
selectBy
vectorSearchString?:
string
Search string for finding semantically similar messages
last?:
number | false
= 40
Number of most recent messages to retrieve. Set to false to disable limit. Note: threadConfig.lastMessages (default: 40) will override this if smaller.
include?:
array
Array of message IDs to include with context
include
id:
string
ID of the message to include
withPreviousMessages?:
number
Number of messages to include before this message. Defaults to 2 when using vector search, 0 otherwise.
withNextMessages?:
number
Number of messages to include after this message. Defaults to 2 when using vector search, 0 otherwise.
Returns
messages:
CoreMessage[]
Array of retrieved messages in their core format
uiMessages:
AiMessage[]
Array of messages formatted for UI display
Additional Notes
The query
function returns two different message formats:
messages
: Core message format used internallyuiMessages
: Formatted messages suitable for UI display, including proper threading of tool calls and results