記憶工具讓 Claude 能夠在記憶檔案目錄中跨對話儲存和檢索資訊。Claude 可以建立、讀取、更新和刪除在工作階段之間持續存在的檔案,隨著時間累積知識,而無需將所有內容保留在上下文視窗中。
記憶支援即時(just-in-time)的上下文檢索。代理程式不是預先載入所有相關資訊,而是將其學到的內容記錄在記憶檔案中,並在需要時讀取回來。這使活躍的上下文能夠專注於當前任務,這對於長時間執行的工作階段非常重要,否則這些工作階段會使上下文視窗不堪負荷。請參閱有效的上下文工程以了解更廣泛的模式。
記憶工具在用戶端運作:Claude 請求檔案操作,而您的應用程式執行這些操作。您可以透過自己的基礎設施控制資料的儲存位置和方式。
請透過意見回饋表單分享您對此功能的意見回饋。
關於「zero data retention」(零資料保留),即 ZDR 如何適用於此功能,請參閱 API 與資料保留。
啟用記憶工具後,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 提供的工具完整清單,請參閱工具參考。
記憶工具已在 Messages API 上正式推出:不需要 beta 標頭。使用它需要兩個步驟:
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。即使記憶工具本身已正式推出,輔助程式和工具執行器的介面仍位於每個 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 本身的完整範例,請參閱:
您的用戶端實作必須處理以下命令。這些規格描述了建議的行為和回傳字串:Claude 會讀取您的工具結果中包含的任何文字,因此如果您的應用程式有需要,可以回傳不同的字串。
顯示目錄內容或檔案內容,可選擇指定行範圍:
{
"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}5.5K、1.2M). 開頭的檔案)和 node_modules對空儲存空間的 /memories 進行第一次 view 不是錯誤。SDK 的本機檔案系統記憶工具(BetaLocalFilesystemMemoryTool)會在 Claude 第一次呼叫之前建立記憶根目錄,並回傳清單標頭,後面接著空目錄本身的單一大小和路徑行。
對於檔案: 回傳帶有標頭和行號的檔案內容:
Here's the content of {path} with line numbers:
{line_numbers}{tab}{content}行號格式:
"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."建立新檔案:
{
"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 呼叫。回傳錯誤是參考行為,改為覆寫也是有效的實作選擇。
取代檔案中的文字:
{
"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"如果路徑是目錄,回傳「檔案不存在」錯誤。
在特定行插入文字:
{
"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}]"如果路徑是目錄,回傳「檔案不存在」錯誤。
刪除檔案或目錄:
{
"command": "delete",
"path": "/memories/old_file.txt"
}"Successfully deleted {path}""Error: The path {path} does not exist"遞迴刪除目錄及其所有內容。工具描述告訴 Claude 它不能刪除 /memories 目錄本身,因此請拒絕路徑為記憶根目錄的 delete。
重新命名或移動檔案或目錄:
{
"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 會自動將此指示加入系統提示。您不需要自行傳送:
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 寫入記憶的內容。例如:「只在您的記憶系統中記錄與 <topic> 相關的資訊。」
您的應用程式會執行 Claude 請求的每個檔案操作,因此這些防護措施是您的責任:
Claude 通常會拒絕將敏感資訊寫入記憶檔案。為了獲得更強的保證,請加入驗證機制,在您的處理常式寫入檔案之前移除敏感資料。
追蹤記憶檔案大小並限制檔案可成長的上限。考慮限制 view 命令回傳的字元數,並讓 Claude 使用 view_range 分頁瀏覽其餘內容。
定期刪除長時間未被存取的記憶檔案。
像 /memories/../../secrets.env 這樣的惡意路徑可以存取 /memories 目錄以外的檔案。您的實作必須驗證每個命令中的每個路徑,以防止目錄遍歷攻擊。
請考慮以下防護措施:
/memories 開頭../、..\\ 或其他遍歷模式等序列的路徑%2e%2e%2f)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
}記憶工具可與上下文編輯搭配使用,以管理長時間執行的對話。如需詳細資訊,請參閱上下文編輯。
記憶工具也可以與壓縮搭配使用,壓縮會在伺服器端摘要較舊的對話上下文。上下文編輯會在用戶端清除特定的工具結果。當對話接近上下文視窗限制時,壓縮會在伺服器上自動摘要整個對話。
對於長時間執行的代理程式,請考慮同時使用兩者:壓縮可在無需用戶端記錄的情況下保持活躍上下文的精簡,而記憶則保留必須在摘要後仍然存在的資訊。
對於跨越多個代理程式工作階段的軟體專案,請刻意設定記憶檔案,而不是隨著工作進展臨時撰寫。以下模式將記憶轉變為一種復原機制:每個新的工作階段都從上一個工作階段記錄的狀態繼續。
初始化工作階段: 第一個工作階段在任何實質工作開始之前設定記憶檔案。這包括進度日誌(追蹤已完成的工作和接下來的工作)、功能檢查清單(定義工作範圍),以及專案所需的任何啟動或初始化指令碼的參考。
後續工作階段: 每個新的工作階段都從讀取這些記憶檔案開始。這可以還原專案狀態,而無需重新探索程式碼庫或重新追溯先前的決策。
工作階段結束更新: 在工作階段結束之前,更新進度日誌,記錄已完成的內容和剩餘的內容。這確保下一個工作階段有準確的起點。
一次只處理一個功能。只有在端對端驗證確認功能正常運作後才將其標記為完成,而不是在程式碼撰寫完成時。這可以讓進度日誌在各個工作階段之間保持準確。
如需此模式實際應用的詳細案例研究,包括初始化指令碼、進度檔案結構和基於 git 的復原,請參閱長時間執行代理程式的有效框架。
在持續的 bash 工作階段中執行 shell 命令。
使用上下文編輯自動管理隨著成長的對話上下文。
伺服器端上下文壓縮,用於管理接近上下文視窗限制的長對話。
Anthropic 提供的工具目錄,以及選用工具定義屬性的參考。
Was this page helpful?