記憶工具
透過在您的應用程式中實作記憶工具的檔案操作,讓 Claude 能夠跨對話儲存和擷取資訊。
記憶工具(memory tool)讓 Claude 能夠在記憶檔案目錄中跨對話儲存和擷取資訊。Claude 可以建立、讀取、更新和刪除在工作階段之間持續存在的檔案,隨著時間累積知識,而無需將所有內容保留在「context window」(上下文視窗)中。
記憶支援即時(just-in-time)上下文擷取。代理程式不會預先載入所有相關資訊,而是將所學內容記錄在記憶檔案中,並在需要時讀回。這讓作用中的上下文專注於當前任務,這對於長時間執行的工作階段非常重要,否則這些工作階段會使上下文視窗不堪負荷。請參閱有效的上下文工程以了解更廣泛的模式。
記憶工具在用戶端運作:Claude 請求檔案操作,由您的應用程式執行。您可以透過自己的基礎設施控制資料的儲存位置和方式。
使用案例
- 跨多個代理程式工作階段維護專案上下文
- 將過去互動、決策和回饋中的經驗應用於新任務
- 隨著時間建立知識庫
運作方式
啟用記憶工具後,Claude 會在開始任務前自動檢查其記憶目錄。在工作過程中,Claude 會將所學內容儲存在 /memories 下的檔案中,並在之後的對話中讀回以繼續先前的工作。
由於記憶工具是用戶端工具,Claude 只會請求記憶操作。您的應用程式會針對您控制的儲存空間執行每個請求,並在 tool_result 區塊中回傳結果(請參閱處理工具呼叫)。/memories 路徑是一個前綴,由您的處理程式對應到實際儲存空間,例如每位使用者的目錄或資料庫中的鍵。記憶完全存在於您的應用程式中。當之後的對話傳送相同的 tools 項目且您的處理程式提供相同的儲存空間時,該對話便會從相同的記憶繼續。為了安全起見,請將所有記憶操作限制在 /memories 目錄內(請參閱路徑遍歷防護)。
範例:記憶工具呼叫的運作方式
典型的互動如下所示:
1. 使用者請求:
"Help me respond to this customer service ticket."2. Claude 檢查記憶目錄:
"I'll help you respond to the customer service ticket. Let me check my memory for any previous context."Claude 呼叫記憶工具:
{
"type": "tool_use",
"id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
"name": "memory",
"input": {
"command": "view",
"path": "/memories"
}
}3. 您的應用程式回傳目錄內容:
{
"type": "tool_result",
"tool_use_id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
"content": "Here're the files and directories up to 2 levels deep in /memories, excluding hidden items and node_modules:\n4.0K\t/memories\n1.5K\t/memories/customer_service_guidelines.xml\n2.0K\t/memories/refund_policies.xml"
}4. Claude 讀取相關檔案:
{
"type": "tool_use",
"id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5",
"name": "memory",
"input": {
"command": "view",
"path": "/memories/customer_service_guidelines.xml"
}
}5. 您的應用程式回傳檔案內容:
{
"type": "tool_result",
"tool_use_id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5",
"content": "Here's the content of /memories/customer_service_guidelines.xml with line numbers:\n 1\t<guidelines>\n 2\t<addressing_customers>\n 3\t- Always address customers by their first name\n 4\t- Use empathetic language\n..."
}6. Claude 使用記憶來提供協助:
"Based on your customer service guidelines, I can help you craft a response. Please share the ticket details..."記憶工具可在所有 Claude 4 及更新的模型上使用。如需 Anthropic 提供之工具的完整清單,請參閱工具參考。
開始使用
使用記憶工具需要兩個步驟:
- 將記憶工具加入您的請求。
tools項目{"type": "memory_20250818", "name": "memory"}即為完整的設定:name必須為memory,且您不需要為 Anthropic 提供的工具定義輸入結構描述。 - 為每個記憶命令實作用戶端處理程式。您的處理程式必須拒絕
/memories以外的路徑,因此在撰寫之前請先閱讀路徑遍歷防護。
基本用法
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-5",
max_tokens=2048,
messages=[
{
"role": "user",
"content": "Help me respond to this customer service ticket.",
}
],
tools=[{"type": "memory_20250818", "name": "memory"}],
)
print(message)實作記憶處理程式
Claude 對上述請求的回覆會以一個 tool_use 區塊結尾,該區塊請求一項記憶操作,例如 view /memories。您的應用程式執行該操作並在 tool_result 區塊中回傳結果,然後將對話傳回,讓 Claude 可以繼續:這就是標準的工具使用迴圈。
有四個 SDK 提供記憶工具輔助程式,用於處理工具介面和迴圈。您可以繼承 BetaAbstractMemoryTool(Python 和 C#)、使用 betaMemoryTool(TypeScript),或實作 BetaMemoryToolHandler(Java),以您自己的儲存空間作為記憶的後端,例如磁碟上的檔案、資料庫、雲端儲存或加密檔案。Python 和 TypeScript 還附帶一個現成的本機檔案系統實作 BetaLocalFilesystemMemoryTool。即使記憶工具本身不需要 beta 標頭,輔助程式和工具執行器介面仍位於各 SDK 的 beta 命名空間中。Go 和 Ruby SDK 沒有記憶輔助程式,因此這些範例會自行執行工具使用迴圈,而 PHP 則將您的處理程式閉包包裝在其通用的 BetaRunnableTool 中。這三者都使用記憶體內儲存,您可以將其替換為自己的儲存空間。
import anthropic
from anthropic.tools import BetaLocalFilesystemMemoryTool
client = anthropic.Anthropic()
memory = BetaLocalFilesystemMemoryTool(base_path="./memory")
runner = client.beta.messages.tool_runner(
model="claude-opus-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Remember that customer Acme Corp prefers email follow-ups.",
}
],
tools=[memory],
)
final_message = runner.until_done()
print(final_message.content)Go、PHP 和 Ruby 範例中的記憶體內儲存讓它們保持獨立完整:每個範例都根據 tool_use 區塊 input 中的 command 欄位進行分派,並回傳工具命令中所述的字串。正式環境的處理程式還需要這些示範儲存所省略的路徑驗證。如需各 SDK 自己的完整範例,請參閱:
- Python:examples/memory/basic.py
- TypeScript:examples/tools-helpers-memory.ts
- C#:MemoryToolExample
- Java:BetaMemoryToolExample.java
工具命令
您的用戶端實作必須處理以下命令。這些規格描述了建議的行為和回傳字串:Claude 會讀取您的工具結果中包含的任何文字,因此如果您的應用程式需要,您可以回傳不同的字串。
view
顯示目錄內容或檔案內容,可選擇指定行範圍:
{
"command": "view",
"path": "/memories/notes.txt",
"view_range": [1, 10]
}view_range 為選用參數,適用於文字檔案檢視:[start_line, end_line] 會回傳這些行,而 [start_line, -1] 會回傳從 start_line 到檔案結尾的所有內容。
回傳值
對於目錄: 回傳一份清單,顯示檔案和目錄及其大小:
Here're the files and directories up to 2 levels deep in {path}, excluding hidden items and node_modules:
{size}\t{path}
{size}\t{path}/{filename1}
{size}\t{path}/{filename2}- 列出最多 2 層深的檔案
- 顯示人類可讀的大小(例如
5.5K、1.2M) - 排除隱藏項目(以
.開頭的檔案)和node_modules - 在大小和路徑之間使用 tab 字元
在空的儲存空間上首次對 /memories 執行 view 並不是錯誤。SDK 的本機檔案系統記憶工具(BetaLocalFilesystemMemoryTool)會在 Claude 首次呼叫之前建立記憶根目錄,並回傳清單標頭,後面接著一行代表空目錄本身的大小與路徑。
對於檔案: 回傳帶有標頭和行號的檔案內容:
Here's the content of {path} with line numbers:
{line_numbers}{tab}{content}行號格式:
- 寬度: 6 個字元,靠右對齊並以空格填補
- 分隔符號: 行號與內容之間使用 tab 字元
- 索引: 從 1 開始(第一行為第 1 行)
- 行數限制: 超過 999,999 行的檔案應回傳錯誤:
"File {path} exceeds maximum line limit of 999,999 lines."
範例輸出:
Here's the content of /memories/notes.txt with line numbers:
1 Hello World
2 This is line two
10 Line ten
100 Line one hundredClaude 的工具描述還指出 view 會顯示圖片檔案(.jpg、.jpeg 和 .png),並會截斷超過 16,000 個字元之檔案的文字檢視。請預期會有針對圖片路徑的 view 呼叫,以及對長檔案的後續範圍檢視。
錯誤處理
- 檔案或目錄不存在:
"The path {path} does not exist. Please provide a valid path."
create
建立新檔案:
{
"command": "create",
"path": "/memories/notes.txt",
"file_text": "Meeting notes:\n- Discussed project timeline\n- Next steps defined\n"
}回傳值
- 成功:
"File created successfully at: {path}"
錯誤處理
- 檔案已存在:
"Error: File {path} already exists"
Claude 的工具描述指出 create 會「建立或覆寫」檔案,因此請預期會有針對已存在路徑的 create 呼叫。回傳錯誤是參考行為,而改為覆寫也是有效的實作選擇。
str_replace
取代檔案中的文字:
{
"command": "str_replace",
"path": "/memories/preferences.txt",
"old_str": "Favorite color: blue",
"new_str": "Favorite color: green"
}new_str 對 str_replace 而言是選用的:省略時,old_str 會被刪除而不進行取代。
回傳值
- 成功:
"The memory file has been edited.",後面接著帶有行號的已編輯檔案片段
錯誤處理
- 檔案不存在:
"Error: The path {path} does not exist. Please provide a valid path." - 找不到文字:
"No replacement was performed, old_str `\{old_str}` did not appear verbatim in {path}." - 重複文字: 當
old_str出現多次時,回傳:"No replacement was performed. Multiple occurrences of old_str `\{old_str}` in lines: {line_numbers}. Please ensure it is unique"
目錄處理
如果路徑是目錄,則回傳「檔案不存在」錯誤。
insert
在特定行插入文字:
{
"command": "insert",
"path": "/memories/todo.txt",
"insert_line": 2,
"insert_text": "- Review memory tool documentation\n"
}insert_text 會插入在第 insert_line 行之後,而 0 表示插入在檔案開頭。
回傳值
- 成功:
"The file {path} has been edited."
錯誤處理
- 檔案不存在:
"Error: The path {path} does not exist" - 無效的行號:
"Error: Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: [0, {n_lines}]"
目錄處理
如果路徑是目錄,則回傳「檔案不存在」錯誤。
delete
刪除檔案或目錄:
{
"command": "delete",
"path": "/memories/old_file.txt"
}回傳值
- 成功:
"Successfully deleted {path}"
錯誤處理
- 檔案或目錄不存在:
"Error: The path {path} does not exist"
目錄處理
遞迴刪除目錄及其所有內容。工具描述告知 Claude 它無法刪除 /memories 目錄本身,因此請拒絕路徑為記憶根目錄的 delete。
rename
重新命名或移動檔案或目錄:
{
"command": "rename",
"old_path": "/memories/draft.txt",
"new_path": "/memories/final.txt"
}回傳值
- 成功:
"Successfully renamed {old_path} to {new_path}"
錯誤處理
- 來源不存在:
"Error: The path {old_path} does not exist" - 目的地已存在: 回傳錯誤(不要覆寫):
"Error: The destination {new_path} already exists"
目錄處理
重新命名目錄。工具描述告知 Claude 它無法重新命名 /memories 目錄本身,因此請拒絕 old_path 為記憶根目錄的 rename。
提示指引
當記憶工具出現在您請求的 tools 中時,API 會自動將此指示加入「system prompt」(系統提示)。您不需要自行傳送:
IMPORTANT: ALWAYS VIEW YOUR MEMORY DIRECTORY BEFORE DOING ANYTHING ELSE.
MEMORY PROTOCOL:
1. Use the `view` command of your `memory` tool to check for earlier progress.
2. ... (work on the task) ...
- As you make progress, record status / progress / thoughts etc in your memory.
ASSUME INTERRUPTION: Your context window might be reset at any moment, so you risk losing any progress that is not recorded in your memory directory.Claude 的工具描述已經告知它要保持記憶目錄井然有序,因此您不需要重複該指示。如果 Claude 仍然建立雜亂的記憶檔案,您可以在提示中加以強調:
Note: when editing your memory folder, always try to keep its content up-to-date, coherent and organized. You can rename or delete files that are no longer relevant. Do not create new files unless necessary.您也可以引導 Claude 寫入記憶的內容。例如:「Only write down information relevant to <topic> in your memory system.」
安全性考量
您的應用程式會執行 Claude 請求的每一項檔案操作,因此這些防護措施是您的責任:
敏感資訊
Claude 通常會拒絕將敏感資訊寫入記憶檔案。若需要更強的保證,請加入驗證機制,在處理程式寫入檔案之前移除敏感資料。
檔案儲存大小
追蹤記憶檔案大小並限制檔案可成長的上限。請考慮限制 view 命令回傳的字元數,並讓 Claude 使用 view_range 分頁瀏覽其餘內容。
記憶過期
定期刪除長時間未被存取的記憶檔案。
路徑遍歷防護
請考慮以下防護措施:
- 驗證所有路徑皆以
/memories開頭 - 將路徑解析為其標準形式,並驗證它們仍位於記憶目錄內
- 拒絕包含
../、..\\或其他遍歷模式等序列的路徑 - 注意 URL 編碼的遍歷序列(
%2e%2e%2f) - 使用您所用語言內建的路徑安全工具(例如 Python 的
pathlib.Path.resolve()和relative_to())
錯誤處理
記憶工具使用與文字編輯器工具類似的錯誤處理模式。每個命令的錯誤訊息列於工具命令之下。若要向 Claude 回傳錯誤,請在工具結果上將 is_error 設為 true,並將訊息放在 content 中:
{
"type": "tool_result",
"tool_use_id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
"content": "Error: The path /memories/notes.txt does not exist",
"is_error": true
}上下文編輯整合
記憶工具可與上下文編輯搭配使用,以管理長時間執行的對話。詳情請參閱上下文編輯。
與壓縮搭配使用
記憶工具也可以與壓縮(compaction)搭配使用,後者會在伺服器端摘要較舊的對話上下文。上下文編輯會在用戶端清除特定的工具結果。當對話接近上下文視窗限制時,壓縮會在伺服器上自動摘要整個對話。
對於長時間執行的代理程式,請考慮同時使用兩者:壓縮可在無需用戶端記錄的情況下保持作用中上下文精簡,而記憶則保留必須在摘要後留存的資訊。
多工作階段軟體開發模式
對於跨越多個代理程式工作階段的軟體專案,請有計畫地設定記憶檔案,而不是在工作進行中臨時撰寫。以下模式將記憶轉變為一種復原機制:每個新工作階段都從上一個工作階段記錄的狀態繼續。
模式的運作方式
-
初始化工作階段: 第一個工作階段在任何實質工作開始之前設定記憶檔案。這包括進度日誌(追蹤已完成的工作和接下來的工作)、功能檢查清單(定義工作範圍),以及對專案所需之任何啟動或初始化腳本的參照。
-
後續工作階段: 每個新工作階段一開始都會讀取這些記憶檔案。這可以還原專案狀態,而無需重新探索程式碼庫或重新追溯先前的決策。
-
工作階段結束時更新: 在工作階段結束之前,它會以已完成和剩餘的工作更新進度日誌。這確保下一個工作階段有準確的起點。
關鍵原則
一次只處理一項功能。只有在端對端驗證確認功能可運作之後才將其標記為完成,而不是在程式碼寫完時。這能讓進度日誌在各工作階段之間保持準確。
後續步驟
Was this page helpful?