Skip to main content

消息记录

🌐 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

每条消息都属于一个线程(对话)和一个资源(与之关联的用户或实体)。有关更多详情,请参阅线程和资源

入门
Direct link to 入门

🌐 Getting started

安装 Mastra 内存模块,并为你的数据库配备一个 存储适配器。下面的示例使用 @mastra/libsql,它将数据存储在本地的 mastra.db 文件中。

🌐 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 install @mastra/memory@latest @mastra/libsql@latest

消息历史记录需要一个存储适配器来保存对话。如果你还没有配置存储,请在你的 Mastra 实例上进行配置:

🌐 Message history requires a storage adapter to persist conversations. Configure storage on your Mastra instance if you haven't already:

src/mastra/index.ts
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",
}),
});

给你的代理一个 Memory

🌐 Give your agent a Memory:

src/mastra/agents/your-agent.ts
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,
},
}),
});

当你调用代理时,消息会自动保存到数据库中。你可以指定 threadIdresourceId,以及可选的 metadata

🌐 When you call the agent, messages are automatically saved to the database. You can specify a threadId, resourceId, and optional metadata:

await agent.generate("Hello", {
memory: {
thread: {
id: "thread-123",
title: "Support conversation",
metadata: { category: "billing" },
},
resource: "user-456",
},
});
info

当你调用 agent.generate()agent.stream() 时,线程和消息会自动创建,但你也可以通过 createThread()saveMessages() 手动创建它们。

🌐 Threads and messages are created automatically when you call agent.generate() or agent.stream(), but you can also create them manually with createThread() and saveMessages().

使用此历史有两种方式:

🌐 There are two ways to use this history:

  • 自动包含 - Mastra 会自动获取并将最近的消息包含在上下文窗口中。默认情况下,它会包含最近的10条消息,使代理保持在对话的上下文中。你可以使用 lastMessages 来调整这个数量,但在大多数情况下,你无需特别考虑它。
  • 手动查询 - 如果需要更多控制,请使用 recall() 函数直接查询线程和消息。这样,你可以精确选择哪些内存包含在上下文窗口中,或者获取消息以在你的界面中呈现对话历史。

访问内存
Direct link to 访问内存

🌐 Accessing Memory

要访问用于查询、克隆或删除线程和消息的内存功能,请在代理上调用 getMemory()

🌐 To access memory functions for querying, cloning, or deleting threads and messages, call getMemory() on an agent:

const agent = mastra.getAgent("weatherAgent");
const memory = await agent.getMemory();

Memory 实例让你可以访问用于列出线程、回忆消息、克隆对话等功能。

🌐 The Memory instance gives you access to functions for listing threads, recalling messages, cloning conversations, and more.

查询中
Direct link to 查询中

🌐 Querying

使用这些方法来获取线程和消息,以便在你的界面中显示对话历史或实现自定义的内存检索逻辑。

🌐 Use these methods to fetch threads and messages for displaying conversation history in your UI or for custom memory retrieval logic.

warning

内存系统不强制执行访问控制。在运行任何查询之前,请在你的应用逻辑中验证当前用户是否有权访问正在查询的 resourceId

线程
Direct link to 线程

🌐 Threads

使用 listThreads() 来检索某个资源的线程:

🌐 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" },
});

要通过 ID 获取单个线程,请使用 getThreadById()

🌐 To fetch a single thread by ID, use getThreadById():

const thread = await memory.getThreadById({ threadId: "thread-123" });

消息
Direct link to 消息

🌐 Messages

一旦你有了一个线程,可以使用 recall() 来获取它的消息。它支持分页、日期筛选和语义搜索

🌐 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"),
},
},
});

通过ID获取单条消息:

🌐 Fetch a single message by ID:

const { messages } = await memory.recall({
threadId: "thread-123",
include: [{ id: "msg-123" }],
});

通过 ID 获取多条消息及其上下文:

🌐 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,
},
});

用户界面格式
Direct link to 用户界面格式

🌐 UI format

消息查询返回 MastraDBMessage[] 格式。要在前端显示消息,你可能需要将它们转换为你的 UI 库所期望的格式。例如,toAISdkV5Messages 可以将消息转换为 AI SDK UI 格式。

🌐 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.

线程克隆
Direct link to 线程克隆

🌐 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",
});

你可以筛选要克隆的消息(按数量或日期范围)、指定自定义线程ID,并使用实用方法检查克隆关系。

🌐 You can filter which messages get cloned (by count or date range), specify custom thread IDs, and use utility methods to inspect clone relationships.

请参见 cloneThread()克隆工具 获取完整 API。

🌐 See cloneThread() and clone utilities for the full API.

删除消息
Direct link to 删除消息

🌐 Deleting messages

要从线程中删除消息,请使用 deleteMessages()。你可以按消息 ID 删除消息,也可以清空线程中的所有消息。

🌐 To remove messages from a thread, use deleteMessages(). You can delete by message ID or clear all messages from a thread.