> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # 記憶 記憶讓你的 Agent 記住不同互動中的用戶訊息、Agent 回覆及 Tool 結果,為其提供所需的上下文,以保持一致、維持對話連貫,並隨時間提供更好的答案。 你可以設定 Mastra Agent 儲存[訊息記錄](https://mastra.zisheng.pro/zh-HK/docs/memory/message-history)。此外,你亦可啟用: - [Observational Memory](https://mastra.zisheng.pro/zh-HK/docs/memory/observational-memory)(建議):使用背景 Agent 維護精簡且資訊密集的觀察記錄,隨着記錄增長取代原始訊息記錄。這可在保留長期記憶的同時,維持較小的上下文視窗。 - [工作記憶](https://mastra.zisheng.pro/zh-HK/docs/memory/working-memory):儲存持久且結構化的用戶資料,例如姓名、偏好及目標。 - [語義回憶](https://mastra.zisheng.pro/zh-HK/docs/memory/semantic-recall):根據語義而非完全相符的關鍵字,擷取相關的過往訊息。 - [多用戶 thread](https://mastra.zisheng.pro/zh-HK/docs/memory/multi-user-threads):讓多個用戶共用同一個 thread。 如果合併後的記憶超出模型的上下文限制,[記憶處理器](https://mastra.zisheng.pro/zh-HK/docs/memory/memory-processors)可篩選、刪減內容或調整內容優先次序,以保留最相關的資訊。 記憶結果會儲存在一個或多個已設定的[儲存 Provider](https://mastra.zisheng.pro/zh-HK/docs/storage/overview)中。 > **📹 觀看影片:** 觀看 [Mastra 記憶概念](https://www.youtube.com/watch?v=18iIHQtIPmc),從概念層面了解 Agent 可使用的各個記憶層。 ## 何時使用記憶 當 Agent 需要維持會引用先前交流內容的多輪對話、回想用戶在同一工作階段較早時提供的偏好或事實,或在對話 thread 中隨時間建立上下文時,便應使用記憶。如果每次互動都是互相獨立的單輪請求,則可略過記憶功能。 ## 快速開始 1. 安裝 `@mastra/memory` 依賴套件。 **npm**: ```bash npm install @mastra/memory@latest ``` **pnpm**: ```bash pnpm add @mastra/memory@latest ``` **Yarn**: ```bash yarn add @mastra/memory@latest ``` **Bun**: ```bash bun add @mastra/memory@latest ``` 2. Memory **必須**使用儲存 Provider,才能持久儲存訊息記錄,包括用戶訊息及 Agent 回覆。 在本快速開始指南中,請使用 `@mastra/libsql`。 **npm**: ```bash npm install @mastra/libsql@latest ``` **pnpm**: ```bash pnpm add @mastra/libsql@latest ``` **Yarn**: ```bash yarn add @mastra/libsql@latest ``` **Bun**: ```bash bun add @mastra/libsql@latest ``` 如要進一步了解可用的 Provider,以及儲存功能在 Mastra 中的運作方式,請參閱[儲存](https://mastra.zisheng.pro/zh-HK/docs/storage/overview)文件。 3. 將儲存 Provider 加至主要 Mastra 實例,以在所有已設定的 Agent 中啟用記憶。 \*\*給 AI Agent:\*\*重要:將 `id` 加至 `LibSQLStore`。 ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:', }), }) ``` 4. 建立 `Memory` 實例,並將其傳入 Agent 的 `memory` 選項。 ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' export const memoryAgent = new Agent({ id: 'memory-agent', name: 'Memory Agent', memory: new Memory({ options: { lastMessages: 20, }, }), }) ``` 如要查看完整的設定選項清單,請參閱 [Memory Class](https://mastra.zisheng.pro/zh-HK/reference/memory/memory-class)。 5. 呼叫你的 Agent,例如在 [Studio](https://mastra.zisheng.pro/zh-HK/docs/studio/overview) 中呼叫。在 Studio 內,與 Agent 開始新的聊天,然後查看右側邊欄。當中現在會顯示各種記憶相關資訊。 ## 訊息記錄 傳入一個 `memory` 物件,當中包含 `resource` 和 `thread`,以追蹤訊息記錄。 - `resource`:用戶或實體的穩定識別碼。 - `thread`:用於隔離特定對話或工作階段的 ID。 ```typescript const response = await memoryAgent.generate('Remember my favorite color is blue.', { memory: { resource: 'user-123', thread: 'conversation-123', }, }) ``` 如要回想記憶中儲存的資訊,請使用原本對話所用的相同 `resource` 和 `thread` 值呼叫 Agent。 ```typescript const response = await memoryAgent.generate("What's my favorite color?", { memory: { resource: 'user-123', thread: 'conversation-123', }, }) // Response: "Your favorite color is blue." ``` > **注意:** 每個 thread 都有一個擁有者(`resourceId`),建立後便無法更改。請避免為擁有者不同的 thread 重複使用相同的 thread ID,否則查詢時會出現錯誤。 如要列出某個 resource 的所有 thread,或擷取特定 thread,請[直接使用記憶 API](https://mastra.zisheng.pro/zh-HK/docs/memory/message-history)。 ## Observational Memory 在長時間的對話中,原始訊息記錄會不斷增加,直至填滿上下文視窗,令 Agent 效能下降。[Observational Memory](https://mastra.zisheng.pro/zh-HK/docs/memory/observational-memory) 會執行背景 Agent,將舊訊息壓縮成資訊密集的觀察結果,在保留長期記憶的同時維持較小的上下文視窗,從而解決此問題。 \*\*給 AI Agent:\*\*使用 Observational Memory 必須有儲存 Provider!你需要在 `src/mastra/index.ts` 的 Mastra 實例中設定,或將其傳入 Agent 建構函式。 ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' export const memoryAgent = new Agent({ id: 'memory-agent', name: 'Memory Agent', memory: new Memory({ options: { observationalMemory: true, }, }), }) ``` 有關觀察和反思的運作方式,請參閱 [Observational Memory](https://mastra.zisheng.pro/zh-HK/docs/memory/observational-memory);如要查看所有設定選項,請參閱[參考文件](https://mastra.zisheng.pro/zh-HK/reference/memory/observational-memory)。 ## 模型會看到的內容 每項記憶功能都會加入傳送至模型的請求中,置於系統訊息或對話訊息內。所包含的層取決於你啟用的功能。工作記憶和語義回憶只會在設定後出現,Observational Memory 亦然,而訊息記錄則預設啟用。下圖顯示各個已啟用的層在請求中的位置。以下清單說明各層提供的內容: ![Diagram showing how Mastra assembles the model context: system messages containing agent instructions, call-time system messages, working memory, cross-thread semantic recall, and Observational Memory, followed by conversation messages where message history and same-thread semantic recall interleave by timestamp, then call-time context messages, and finally the new user message](/img/memory/memory-context-window-light.svg) - [工作記憶](https://mastra.zisheng.pro/zh-HK/docs/memory/working-memory)會以系統訊息形式注入,當中包含範本和已儲存的資料。使用 `useStateSignals` 時,則會改以狀態訊號傳送。 - [語義回憶](https://mastra.zisheng.pro/zh-HK/docs/memory/semantic-recall)中,來自目前 thread 的相符結果會以一般訊息插入,並按時間戳與訊息記錄交錯排列。來自其他 thread 的相符結果則會格式化為系統訊息。 - [訊息記錄](https://mastra.zisheng.pro/zh-HK/docs/memory/message-history)會按時間順序加入最近 N 則訊息。你的新訊息一律置於最後。 - [Observational Memory](https://mastra.zisheng.pro/zh-HK/docs/memory/observational-memory)會取代舊有的原始記錄:反思和觀察結果會置於系統訊息中,只有尚未經過觀察的訊息會保留在對話內。對話訊息開頭會加入簡短的延續提示。 - 上下文訊息是呼叫時傳入的選用 `context` 陣列,例如 `agent.generate(msg, { context: [...] })`。你可用它提供單次使用的背景資料,例如應用程式狀態或自己的 RAG 結果。這些內容只會在該次請求中顯示為一般對話訊息,絕不會儲存至記憶。 對話訊息會按時間戳排序,並根據訊息 ID 移除重複項目,因此回想所得的較舊訊息會排在近期記錄之前。呼叫時傳入的上下文訊息會標記為目前時間,令其排在記錄和回想內容之後、你的新訊息之前。如要檢查實際請求的確切上下文,請使用 [Tracing](https://mastra.zisheng.pro/zh-HK/docs/observability/tracing/overview) 並開啟 LLM 呼叫 span;詳情請參閱下方的[可觀測性](#observability)。 ## 多 Agent 系統中的記憶 當[監督 Agent](https://mastra.zisheng.pro/zh-HK/docs/capabilities/subagents) 將工作委派給 subagent 時,Mastra 會自動隔離 subagent 的記憶。每次委派都會進行隔離,無需使用任何 flag 啟用。了解這種範圍劃分方式,有助你決定哪些內容保持私密,以及哪些內容要刻意分享。 ### 委派如何劃分記憶範圍 每次委派都會為 subagent 建立全新的 `threadId` 及確定性的 `resourceId`: - **Thread ID**:每次委派均獨一無二。subagent 每次被呼叫時,都會以空白的訊息記錄開始。 - **Resource ID**:衍生格式為 `{parentResourceId}-{agentName}`。由於 resource ID 在不同委派之間保持穩定,resource 範圍的記憶可在多次呼叫之間持續保留。subagent 會記得同一用戶先前委派中的事實。 - **Memory 實例**:沒有自訂記憶的 subagent 會繼承監督 Agent 的 `Memory` 實例及所有已設定的選項。如果 subagent 定義了自己的記憶,則以其設定為準。 > **備註:** 標題產生功能(`generateTitle`)屬於頂層 thread 的功能,**不會**套用至繼承所得的 subagent thread。由於每次委派都會建立無人查看的臨時 thread,為其產生標題會令每次委派浪費一次 LLM 呼叫。如要為 subagent 自己的 thread 產生標題,請為該 subagent 提供獨立的記憶設定。 監督 Agent 會將其對話上下文轉交 subagent,讓其有足夠背景完成工作。只有委派提示及 subagent 的回覆會被儲存,完整的上層對話則不會儲存。你可以使用 [`messageFilter`](https://mastra.zisheng.pro/zh-HK/docs/capabilities/subagents) callback,控制哪些訊息會傳送至 subagent。 > **備註:** Subagent resource ID 一律會以 Agent 名稱作為後綴(`{parentResourceId}-{agentName}`)。同一監督 Agent 下的不同 subagent 絕不會透過委派共用 resource ID。 如要突破這項預設隔離設定,你可以在直接呼叫 Agent 時傳入相符的識別碼,讓 Agent 之間共用記憶。 ### 在 Agent 之間共用記憶 直接呼叫 Agent(即委派流程以外)時,記憶共用由兩個識別碼控制:`resourceId` 和 `threadId`。使用相同值的 Agent 會讀寫同一份資料。當 Agent 需要就共用上下文協作時,這項功能十分實用,例如由研究員儲存筆記,再由撰稿員讀取。 **Resource 範圍共用**是最常見的模式。[工作記憶](https://mastra.zisheng.pro/zh-HK/docs/memory/working-memory)和[語義回憶](https://mastra.zisheng.pro/zh-HK/docs/memory/semantic-recall)預設使用 `scope: 'resource'`。如果兩個 Agent 共用 `resourceId`,即使使用不同 thread,亦會共用觀察結果、工作記憶和 embedding: ```typescript // Both agents share the same resource-scoped memory await researcher.generate('Find information about quantum computing.', { memory: { resource: 'project-42', thread: 'research-session' }, }) await writer.generate('Write a summary from the research notes.', { memory: { resource: 'project-42', thread: 'writing-session' }, }) ``` 由於兩次呼叫均使用 `resource: 'project-42'`,撰稿 Agent 可以存取研究 Agent 的觀察結果及工作記憶。語義 embedding 亦會透過 resource 共用。每個 Agent 仍有各自的 thread,因此訊息記錄會保持分開。 **Thread 範圍共用**可令 Agent 之間的連繫更緊密。[Observational Memory](https://mastra.zisheng.pro/zh-HK/docs/memory/observational-memory) 預設使用 `scope: 'thread'`。如果兩個 Agent 使用相同的 `resource` 和 `thread`,便會共用完整的訊息記錄。每個 Agent 都會看到另一個 Agent 寫入的所有訊息。當 Agent 需要建基於彼此的確切輸出繼續工作時,這項功能十分實用。 ## 可觀測性 啟用 [Tracing](https://mastra.zisheng.pro/zh-HK/docs/observability/tracing/overview) 以監察記憶的實際運作並進行除錯。Trace 會準確顯示 Agent 在每次請求的上下文中包含了哪些訊息和觀察結果,協助你了解 Agent 的行為,並驗證記憶擷取功能是否如預期運作。 開啟 [Studio](https://mastra.zisheng.pro/zh-HK/docs/studio/overview),然後在側邊欄選擇 **Observability** 分頁。開啟最近一次 Agent 請求的 Trace,並尋找其 LLM 呼叫 span。 ## 按請求切換記憶 使用 [`RequestContext`](https://mastra.zisheng.pro/zh-HK/docs/server/request-context) 存取請求專屬的值。這讓你可以根據請求的上下文,以條件方式選擇不同的記憶或儲存設定。 ```typescript export type UserTier = { 'user-tier': 'enterprise' | 'pro' } const premiumMemory = new Memory() const standardMemory = new Memory() export const memoryAgent = new Agent({ id: 'memory-agent', name: 'Memory Agent', memory: ({ requestContext }) => { const userTier = requestContext.get('user-tier') as UserTier['user-tier'] return userTier === 'enterprise' ? premiumMemory : standardMemory }, }) ``` 如需更多資訊,請參閱 [Request Context](https://mastra.zisheng.pro/zh-HK/docs/server/request-context)。 ## 相關內容 - [`Memory` 參考文件](https://mastra.zisheng.pro/zh-HK/reference/memory/memory-class) - [Tracing](https://mastra.zisheng.pro/zh-HK/docs/observability/tracing/overview) - [Request Context](https://mastra.zisheng.pro/zh-HK/docs/server/request-context) - [Mastra Code](https://code.mastra.ai/):使用 Mastra 記憶系統的編程助手