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

Memory

A file-based agent gets memory from a memory.ts file that default-exports a Memory instance. Use this page for the file-based convention; use the memory docs for message history, semantic recall, storage, and processors.

Without memory.ts or config.memory, the agent has no memory by default. Each generate() or stream() call starts without remembered conversation state unless you pass the prior context yourself.

Quickstart
Quickstart的直接链接

Create memory.ts next to the agent's config.ts:

src/mastra/agents/weather/memory.ts
import { Memory } from '@mastra/memory'

export default new Memory()

The exported instance becomes the agent's memory. If your app configures a storage provider on the main Mastra instance, memory data is stored there. See storage for more information.

Use the same resource and thread values when calling the agent to continue a conversation:

src/app/weather-chat.ts
const response = await weatherAgent.generate('Remember that I prefer Celsius.', {
memory: {
resource: 'user-123',
thread: 'weather-chat',
},
})

Configure memory
Configure memory的直接链接

Pass options to new Memory() when the default behavior isn't enough.

src/mastra/agents/weather/memory.ts
import { Memory } from '@mastra/memory'

export default new Memory({
options: {
lastMessages: 20,
workingMemory: {
enabled: true,
scope: 'resource',
},
},
})

Visit the Memory reference for constructor options. Use these pages for related memory features:

  • Storage: configure persistence for memory data.
  • Semantic recall: retrieve relevant past messages by semantic meaning.
  • Memory processors: filter, trim, or transform messages before memory adds them to model context.

Precedence with config
Precedence with config的直接链接

config.memory wins over memory.ts. If neither is present, the assembled file-based agent has no memory. See config.ts precedence for the full merge table.

On this page