Skip to main content

WorkingMemory

WorkingMemory 是一个输入处理器,用于将工作内存数据注入为系统消息。它从存储中检索持久信息,并将其格式化为对大语言模型的指令,使代理能够在对话中保持对用户的上下文理解。

🌐 The WorkingMemory is an input processor that injects working memory data as a system message. It retrieves persistent information from storage and formats it as instructions for the LLM, enabling the agent to maintain context about users across conversations.

使用示例
Direct link to 使用示例

🌐 Usage example

import { WorkingMemory } from "@mastra/core/processors";

const processor = new WorkingMemory({
storage: memoryStorage,
scope: "resource",
template: {
format: "markdown",
content: `# User Profile
- **Name**:
- **Preferences**:
- **Goals**:
`,
},
});

构造函数参数
Direct link to 构造函数参数

🌐 Constructor parameters

options:

Options
Configuration options for the working memory processor

选项
Direct link to 选项

🌐 Options

storage:

MemoryStorage
Storage instance for retrieving working memory data

template?:

WorkingMemoryTemplate
Template defining the format and structure of working memory

scope?:

'thread' | 'resource'
Scope of working memory. 'thread' scopes to current thread, 'resource' shares across all threads for the resource

useVNext?:

boolean
Use the next-generation instruction format with improved guidelines

readOnly?:

boolean
When true, working memory is provided as read-only context. The data is injected into the conversation but without the updateWorkingMemory tool or update instructions. Useful for agents that should reference working memory without modifying it.

templateProvider?:

{ getWorkingMemoryTemplate(args: { memoryConfig?: MemoryConfig }): Promise<WorkingMemoryTemplate | null> }
Dynamic template provider for runtime template resolution

logger?:

IMastraLogger
Optional logger instance for structured logging

WorkingMemoryTemplate
Direct link to WorkingMemoryTemplate

format:

'markdown' | 'json'
Format of the working memory content

content:

string
Template content defining the structure of working memory data

返回
Direct link to 返回

🌐 Returns

id:

string
Processor identifier set to 'working-memory'

name:

string
Processor display name set to 'WorkingMemory'

defaultWorkingMemoryTemplate:

string
The default markdown template used when no custom template is provided

processInput:

(args: { messages: MastraDBMessage[]; messageList: MessageList; abort: (reason?: string) => never; requestContext?: RequestContext }) => Promise<MessageList | MastraDBMessage[]>
Retrieves working memory and adds it as a system message to the message list

扩展使用示例
Direct link to 扩展使用示例

🌐 Extended usage example

src/mastra/agents/personalized-agent.ts
import { Agent } from "@mastra/core/agent";
import { WorkingMemory, 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: "personalized-agent",
instructions: "You are a helpful assistant that remembers user preferences",
model: "openai:gpt-4o",
inputProcessors: [
new WorkingMemory({
storage,
scope: "resource",
template: {
format: "markdown",
content: `# User Information
- **Name**:
- **Location**:
- **Preferences**:
- **Communication Style**:
- **Current Projects**:
`,
},
}),
new MessageHistory({ storage, lastMessages: 50 }),
],
outputProcessors: [
new MessageHistory({ storage }),
],
});

JSON 格式示例
Direct link to JSON 格式示例

🌐 JSON format example

import { WorkingMemory } from "@mastra/core/processors";

const processor = new WorkingMemory({
storage: memoryStorage,
scope: "resource",
template: {
format: "json",
content: JSON.stringify({
user: {
name: { type: "string" },
preferences: { type: "object" },
goals: { type: "array" },
},
}),
},
});

行为
Direct link to 行为

🌐 Behavior

输入处理
Direct link to 输入处理

🌐 Input processing

  1. 从请求上下文中获取 threadIdresourceId
  2. 根据作用域,从以下位置获取工作内存:
    • 线程元数据 (scope: 'thread')
    • 资源记录 (scope: 'resource')
  3. 解析模板(来自提供商、选项或默认)
  4. 根据模式生成系统指令:
    • 普通模式:包括存储/更新信息的指南、模板结构以及当前数据
    • 只读模式readOnly: true):仅包含当前数据作为上下文,不包含更新指令
  5. 将该指令作为带有 source: 'memory' 标签的系统消息添加

工作内存更新
Direct link to 工作内存更新

🌐 Working memory updates

工作内存的更新是通过 Memory 类提供的 updateWorkingMemory 工具完成的,而不是通过这个处理器。该处理器仅负责将当前的工作内存状态注入到对话中。

🌐 Working memory updates happen through the updateWorkingMemory tool provided by the Memory class, not through this processor. The processor only handles injecting the current working memory state into conversations.

默认模板
Direct link to 默认模板

🌐 Default template

如果未提供模板,处理器将使用带有以下字段的默认 Markdown 模板:

🌐 If no template is provided, the processor uses a default markdown template with fields for:

  • 名, 姓
  • 地点,职业
  • 兴趣,目标
  • 事件、事实、项目

🌐 Related