跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

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.

Usage example
Usage example的直接链接

import { MessageHistory } from '@mastra/core/processors'

const processor = new MessageHistory({
storage: memoryStorage,
lastMessages: 50,
})

Constructor parameters
Constructor parameters的直接链接

options:

MessageHistoryOptions
Configuration options for the message history processor
MessageHistoryOptions

storage:

MemoryStorage
Storage instance for retrieving and persisting messages

lastMessages?:

number
Maximum number of historical messages to retrieve. If not specified, retrieves all messages

Returns
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

Extended usage example
Extended usage example的直接链接

src/mastra/agents/memory-agent.ts
import { Agent } from '@mastra/core/agent'
import { MessageHistory } from '@mastra/core/processors'
import { PostgresStore } from '@mastra/pg'

const storage = new PostgresStore({
id: 'pg-storage',
connectionString: process.env.DATABASE_URL,
})

export const agent = new Agent({
id: 'memory-agent',
name: 'memory-agent',
instructions: 'You are a helpful assistant with conversation memory',
model: 'openai/gpt-5.6-sol',
inputProcessors: [
new MessageHistory({
storage,
lastMessages: 100,
}),
],
outputProcessors: [
new MessageHistory({
storage,
}),
],
})

Behavior
Behavior的直接链接

Input processing
Input processing的直接链接

  1. Retrieves threadId from the request context
  2. Fetches historical messages from storage (ordered by creation date, descending)
  3. Filters out system messages (they shouldn't be stored in the database)
  4. Merges historical messages with incoming messages, avoiding duplicates by ID
  5. Adds historical messages with source: 'memory' tag

Output processing
Output processing的直接链接

  1. Retrieves threadId from the request context
  2. Skips persistence if readOnly is set in memory config
  3. Filters out incomplete tool calls from messages
  4. Persists new user input and assistant response messages to storage
  5. Updates the thread's updatedAt timestamp