MessageHistory
MessageHistory 是一个 混合处理器,负责消息历史的检索和存储。在输入时,它会从存储中获取历史消息并将其添加到对话前面。在输出时,它会将新消息保存到存储中。
🌐 The MessageHistory is a hybrid processor that handles both retrieval and persistence of message history. On input, it fetches historical messages from storage and prepends them to the conversation. On output, it persists new messages to storage.
使用示例Direct link to 使用示例
🌐 Usage example
import { MessageHistory } from "@mastra/core/processors";
const processor = new MessageHistory({
storage: memoryStorage,
lastMessages: 50,
});
构造函数参数Direct link to 构造函数参数
🌐 Constructor parameters
options:
MessageHistoryOptions
Configuration options for the message history processor
选项Direct link to 选项
🌐 Options
storage:
MemoryStorage
Storage instance for retrieving and persisting messages
lastMessages?:
number
Maximum number of historical messages to retrieve. If not specified, retrieves all messages
返回Direct link to 返回
🌐 Returns
id:
string
Processor identifier set to 'message-history'
name:
string
Processor display name set to 'MessageHistory'
processInput:
(args: { messages: MastraDBMessage[]; messageList: MessageList; abort: (reason?: string) => never; tracingContext?: TracingContext; requestContext?: RequestContext }) => Promise<MessageList | MastraDBMessage[]>
Fetches historical messages from storage and adds them to the message list
processOutputResult:
(args: { messages: MastraDBMessage[]; messageList: MessageList; abort: (reason?: string) => never; tracingContext?: TracingContext; requestContext?: RequestContext }) => Promise<MessageList>
Persists new messages (user input and assistant response) to storage, excluding system messages
扩展使用示例Direct link to 扩展使用示例
🌐 Extended usage example
src/mastra/agents/memory-agent.ts
import { Agent } from "@mastra/core/agent";
import { MessageHistory } from "@mastra/core/processors";
import { PostgresStorage } from "@mastra/pg";
const storage = new PostgresStorage({
connectionString: process.env.DATABASE_URL,
});
export const agent = new Agent({
name: "memory-agent",
instructions: "You are a helpful assistant with conversation memory",
model: "openai:gpt-4o",
inputProcessors: [
new MessageHistory({
storage,
lastMessages: 100,
}),
],
outputProcessors: [
new MessageHistory({
storage,
}),
],
});
行为Direct link to 行为
🌐 Behavior
输入处理Direct link to 输入处理
🌐 Input processing
- 从请求上下文中获取
threadId - 从存储中获取历史消息(按创建日期降序排列)
- 过滤系统消息(它们不应存储在数据库中)
- 将历史消息与新消息合并,通过 ID 避免重复
- 添加带有
source: 'memory'标签的历史消息
输出处理Direct link to 输出处理
🌐 Output processing
- 从请求上下文中获取
threadId - 如果内存配置中设置了
readOnly,则跳过持久化 - 从消息中过滤不完整的工具调用
- 将新的用户输入和助手响应消息保存到存储
- 更新线程的
updatedAt时间戳
相关Direct link to 相关
🌐 Related