跳至主要內容

Memory

檔案式 Agent 會從 default export Memory instance 的 memory.ts 檔案取得 Memory。本頁說明檔案式慣例;如需訊息歷史、語意回憶、Storage 與 processor 的資訊,請參閱 Memory 文件。

若沒有 memory.tsconfig.memory,Agent 預設不具備 Memory。除非你自行傳入先前的 context,否則每次 generate()stream() 呼叫開始時,都不會有已記住的對話 state。

快速開始
「快速開始」的直接連結

在 Agent 的 config.ts 旁建立 memory.ts

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

export default new Memory()

這個預設匯出的 instance 會成為 Agent 的 memory。如果你的應用程式在主要 Mastra instance 上設定了 Storage Provider,Memory 資料就會儲存在該處。詳情請參閱 Storage

呼叫 Agent 時使用相同的 resourcethread 值,即可延續對話:

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

設定 Memory
「設定 Memory」的直接連結

若預設行為不足以滿足需求,請將選項傳給 new Memory()

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

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

constructor 選項請參閱 Memory 參考文件。相關 Memory 功能請參閱以下頁面:

  • Storage:設定 Memory 資料的持久化方式。
  • 語意回憶:依語意擷取相關的過往訊息。
  • Memory processor:在 Memory 將訊息加入模型 context 前,進行篩選、裁剪或轉換。

與 config 的優先順序
「與 config 的優先順序」的直接連結

config.memory 優先於 memory.ts。如果兩者都不存在,組合完成的檔案式 Agent 將不具備 Memory。完整合併表請參閱 config.ts 優先順序