Skip to main content

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

  1. 从请求上下文中获取 threadId
  2. 从存储中获取历史消息(按创建日期降序排列)
  3. 过滤系统消息(它们不应存储在数据库中)
  4. 将历史消息与新消息合并,通过 ID 避免重复
  5. 添加带有 source: 'memory' 标签的历史消息

输出处理
Direct link to 输出处理

🌐 Output processing

  1. 从请求上下文中获取 threadId
  2. 如果内存配置中设置了 readOnly,则跳过持久化
  3. 从消息中过滤不完整的工具调用
  4. 将新的用户输入和助手响应消息保存到存储
  5. 更新线程的 updatedAt 时间戳

🌐 Related