Message history
Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference
Published: 2026-05-10 · Source: crawler_authoritative
Tình huống
Guide for configuring and using Mastra’s message history memory system, enabling LLM agents to reference prior conversation exchanges and UI applications to display conversation history.
Insight
Message history is the fundamental memory type in Mastra, providing LLM context through recent messages. Messages belong to threads (conversations) and resources (users/entities). The Memory class uses options.lastMessages (default 10) to automatically include recent messages in the context window. Key APIs include: Memory class (instantiated with options object), agent.getMemory() to access memory functions, recall() for querying messages with support for pagination, date filtering, semantic search via vectorSearchString, and context inclusion with withPreviousMessages/withNextMessages. Thread operations include listThreads() for resource-scoped thread listing with filtering by resourceId and metadata, orderBy sorting options, and pagination via page/perPage. getThreadById() retrieves single threads. cloneThread() creates copies with optional message filtering by count or date range. deleteMessages() removes messages by ID or clears entire threads. Thread cloning supports custom thread IDs, titles, and metadata. The memory system doesn’t enforce access control—applications must verify user authorization before querying by resourceId. Client applications should send only new messages, not full history, to avoid timestamp conflicts with stored messages.
Hành động
- Install memory module: npm install @mastra/memory@latest @mastra/libsql@latest (or pnpm/yarn/bun equivalents). 2. Configure storage adapter on Mastra instance using LibSQLStore with id and url options. 3. Instantiate Memory class in Agent with options.lastMessages to control context window size. 4. Call agent.generate() or agent.stream() with memory.thread.id, memory.thread.title, memory.thread.metadata, and memory.resource parameters to automatically save messages. 5. Access memory functions via agent.getMemory() for querying. 6. Use listThreads() with filter.resourceId, pagination (page/perPage), and orderBy options. 7. Use recall() with threadId, perPage pagination, filter.dateRange for time-based queries, include array for specific message IDs with optional surrounding context via withPreviousMessages/withNextMessages. 8. Use vectorSearchString with threadConfig.semanticRecall=true for semantic search. 9. Use cloneThread() with sourceThreadId and title to branch conversations. 10. Use toAISdkV5Messages helper for converting MastraDBMessage format to AI SDK UI format.
Kết quả
Messages are automatically saved to storage on agent.generate() or agent.stream(). Mastra automatically fetches and includes lastMessages in context window. listThreads() returns paginated threads with hasMore indicator. recall() returns MastraDBMessage[] format. cloneThread() returns thread and clonedMessages objects. deleteMessages() removes specified messages.
Điều kiện áp dụng
Requires @mastra/memory@latest and a storage adapter (e.g., @mastra/libsql). Uses LibSQLStore for local file-based storage. Semantic search requires additional vector search setup.
Nội dung gốc (Original)
Message history
Message history is the most basic and important form of memory. It gives the LLM a view of recent messages in the context window, enabling your agent to reference earlier exchanges and respond coherently.
You can also retrieve message history to display past conversations in your UI.
Info: Each message belongs to a thread (the conversation) and a resource (the user or entity it’s associated with). See Threads and resources for more detail.
Warning: When you use memory with a client application, send only the new message from the client instead of the full conversation history.
Sending the full history is redundant because Mastra loads messages from storage, and it can cause message ordering bugs when client-side timestamps conflict with stored timestamps.
For an AI SDK example, see Using Mastra Memory.
Getting started
Install the Mastra memory module along with a storage adapter for your database. The examples below use @mastra/libsql, which stores data locally in a mastra.db file.
npm:
npm install @mastra/memory@latest @mastra/libsql@latestpnpm:
pnpm add @mastra/memory@latest @mastra/libsql@latestYarn:
yarn add @mastra/memory@latest @mastra/libsql@latestBun:
bun add @mastra/memory@latest @mastra/libsql@latestMessage history requires a storage adapter to persist conversations. Configure storage on your Mastra instance if you haven’t already:
import { Mastra } from '@mastra/core'
import { LibSQLStore } from '@mastra/libsql'
export const mastra = new Mastra({
storage: new LibSQLStore({
id: 'mastra-storage',
url: 'file:./mastra.db',
}),
})Instantiate a Memory instance in your agent:
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
export const agent = new Agent({
id: 'test-agent',
memory: new Memory({
options: {
lastMessages: 10,
},
}),
})When you call the agent, messages are automatically saved to the database. You can specify a threadId, resourceId, and optional metadata:
.generate():
await agent.generate('Hello', {
memory: {
thread: {
id: 'thread-123',
title: 'Support conversation',
metadata: { category: 'billing' },
},
resource: 'user-456',
},
}).stream():
await agent.stream('Hello', {
memory: {
thread: {
id: 'thread-123',
title: 'Support conversation',
metadata: { category: 'billing' },
},
resource: 'user-456',
},
})Info: Threads and messages are created automatically when you call
agent.generate()oragent.stream(), but you can also create them manually withcreateThread()andsaveMessages().
You can use this history in two ways:
- Automatic inclusion: Mastra automatically fetches and includes recent messages in the context window. By default, it includes the last 10 messages, keeping agents grounded in the conversation. You can adjust this number with
lastMessages, but in most cases you don’t need to think about it. - Manual querying: For more control, use the
recall()function to query threads and messages directly. This lets you choose exactly which memories are included in the context window, or fetch messages to render conversation history in your UI.
Tip: When memory is enabled, Studio uses message history to display past conversations in the chat sidebar.
Accessing memory
To access memory functions for querying, cloning, or deleting threads and messages, call getMemory() on an agent:
const agent = mastra.getAgentById('test-agent')
const memory = await agent.getMemory()The Memory instance gives you access to functions for listing threads, recalling messages, cloning conversations, and more.
Querying
Use these methods to fetch threads and messages for displaying conversation history in your UI or for custom memory retrieval logic.
Warning: The memory system doesn’t enforce access control. Before running any query, verify in your application logic that the current user is authorized to access the
resourceIdbeing queried.
Threads
Use listThreads() to retrieve threads for a resource:
const result = await memory.listThreads({
filter: { resourceId: 'user-123' },
perPage: false,
})Paginate through threads:
const result = await memory.listThreads({
filter: { resourceId: 'user-123' },
page: 0,
perPage: 10,
})
console.log(result.threads) // thread objects
console.log(result.hasMore) // more pages available?You can also filter by metadata and control sort order:
const result = await memory.listThreads({
filter: {
resourceId: 'user-123',
metadata: { status: 'active' },
},
orderBy: { field: 'createdAt', direction: 'DESC' },
})To fetch a single thread by ID, use getThreadById():
const thread = await memory.getThreadById({ threadId: 'thread-123' })Messages
Once you have a thread, use recall() to retrieve its messages. It supports pagination, date filtering, and semantic search.
Basic recall returns all messages from a thread:
const { messages } = await memory.recall({
threadId: 'thread-123',
perPage: false,
})Paginate through messages:
const { messages } = await memory.recall({
threadId: 'thread-123',
page: 0,
perPage: 50,
})Filter by date range:
const { messages } = await memory.recall({
threadId: 'thread-123',
filter: {
dateRange: {
start: new Date('2025-01-01'),
end: new Date('2025-06-01'),
},
},
})Fetch a single message by ID:
const { messages } = await memory.recall({
threadId: 'thread-123',
include: [{ id: 'msg-123' }],
})Fetch multiple messages by ID with surrounding context:
const { messages } = await memory.recall({
threadId: 'thread-123',
include: [
{ id: 'msg-123' },
{
id: 'msg-456',
withPreviousMessages: 3,
withNextMessages: 1,
},
],
})Search by meaning (see Semantic recall for setup):
const { messages } = await memory.recall({
threadId: 'thread-123',
vectorSearchString: 'project deadline discussion',
threadConfig: {
semanticRecall: true,
},
})UI format
Message queries return MastraDBMessage[] format. To display messages in a frontend, you may need to convert them to a format your UI library expects. For example, toAISdkV5Messages converts messages to AI SDK UI format.
Thread cloning
Thread cloning creates a copy of an existing thread with its messages. This is useful for branching conversations, creating checkpoints before a potentially destructive operation, or testing variations of a conversation.
const { thread, clonedMessages } = await memory.cloneThread({
sourceThreadId: 'thread-123',
title: 'Branched conversation',
})You can filter which messages get cloned (by count or date range), specify custom thread IDs, and use utility methods to inspect clone relationships.
See cloneThread() and clone utilities for the full API.
Deleting messages
To remove messages from a thread, use deleteMessages(). You can delete by message ID or clear all messages from a thread.
Liên kết
- Nền tảng: Dev Framework · Mastra
- Nguồn: https://mastra.ai/docs/memory/message-history
Xem thêm: