跳至主要內容

Memory

檔案式 Agent 會從 default-export Memory instance 的 memory.ts 檔案取得 memory。本頁說明檔案式慣例;如需了解訊息記錄、語意回憶、storage 及 processors,請參閱 memory 文件。

如果沒有 memory.tsconfig.memory,Agent 預設不會有 memory。除非你自行傳入先前的 context,否則每次 generate()stream() 調用開始時,都不會保留對話狀態。

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

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

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

export default new Memory()

這個 default export 的 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',
},
},
})

如需建構函數選項,請瀏覽 Memory 參考文件。相關 memory 功能請參閱以下頁面:

  • Storage:設定 memory 資料的持久儲存。
  • 語意回憶:按語意擷取相關的過往訊息。
  • Memory processors:在 memory 將訊息加入模型 context 前,篩選、裁剪或轉換訊息。

與 config 的優先次序
與 config 的優先次序 的直接連結

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