記憶工具讓 Claude 能夠透過記憶檔案目錄,在多次對話之間儲存和擷取資訊。Claude 可以建立、讀取、更新和刪除在不同工作階段之間持續存在的檔案,使其能夠隨時間累積知識,而無需將所有內容保留在「context window」(上下文視窗)中。
這是即時上下文擷取的關鍵基本元件:代理程式不需要預先載入所有相關資訊,而是將所學內容儲存在記憶中,並在需要時取回。這讓作用中的上下文專注於當前相關的內容,對於長時間執行的工作流程至關重要,因為一次載入所有內容會使上下文視窗不堪負荷。請參閱 Effective context engineering 以了解更廣泛的模式。
記憶工具在用戶端運作:您可以透過自己的基礎架構控制資料的儲存位置和方式。
請透過意見回饋表單與我們分享您對此功能的意見。
此功能符合「Zero Data Retention」(零資料保留),即 ZDR 的資格。當您的組織具有 ZDR 安排時,透過此功能傳送的資料在 API 回應返回後不會被儲存。
啟用後,Claude 會在開始任務前自動檢查其記憶目錄。Claude 可以在 /memories 目錄中建立、讀取、更新和刪除檔案,以儲存工作時所學到的內容,然後在未來的對話中參考這些記憶,以更有效地處理類似任務或從上次中斷的地方繼續。
由於這是用戶端工具,Claude 會發出工具呼叫來執行記憶操作,而您的應用程式會在本機執行這些操作。這讓您能夠完全控制記憶的儲存位置和方式。基於安全考量,您應將所有記憶操作限制在 /memories 目錄內。
當您請求 Claude 協助處理任務時,Claude 會先自動檢查其記憶目錄。以下是典型互動的樣貌:
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..."如需模型支援資訊,請參閱工具參考。
若要使用記憶工具:
若要在您的應用程式中處理記憶工具操作,您需要為每個記憶命令實作處理常式。SDK 提供了處理工具介面的記憶工具輔助程式。您可以繼承 BetaAbstractMemoryTool(Python)或使用 betaMemoryTool(TypeScript)來實作您自己的記憶後端(檔案式、資料庫、雲端儲存、加密檔案等)。
如需可運作的範例,請參閱:
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-4-8",
max_tokens=2048,
messages=[
{
"role": "user",
"content": "I'm working on a Python web scraper that keeps crashing with a timeout error. Here's the problematic function:\n\n```python\ndef fetch_page(url, retries=3):\n for i in range(retries):\n try:\n response = requests.get(url, timeout=5)\n return response.text\n except requests.exceptions.Timeout:\n if i == retries - 1:\n raise\n time.sleep(1)\n```\n\nPlease help me debug this.",
}
],
tools=[{"type": "memory_20250818", "name": "memory"}],
)
print(message)您的用戶端實作需要處理以下記憶工具命令。雖然這些規格描述的是 Claude 最熟悉的建議行為,但您可以根據您的使用案例需求修改實作並回傳字串。
顯示目錄內容或檔案內容,可選擇指定行數範圍:
{
"command": "view",
"path": "/memories",
"view_range": [1, 10] // Optional: view specific lines
}**針對目錄:**回傳顯示檔案和目錄及其大小的清單:
Here're the files and directories up to 2 levels deep in {path}, excluding hidden items and node_modules:
{size} {path}
{size} {path}/{filename1}
{size} {path}/{filename2}5.5K、1.2M). 開頭的檔案)和 node_modules**針對檔案:**回傳帶有標頭和行號的檔案內容:
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 hundred"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"取代檔案中的文字:
{
"command": "str_replace",
"path": "/memories/preferences.txt",
"old_str": "Favorite color: blue",
"new_str": "Favorite color: green"
}"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"
}"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"遞迴刪除目錄及其所有內容。
重新命名或移動檔案/目錄:
{
"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"重新命名目錄。
啟用記憶工具時,系統提示中會自動包含以下指示:
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 建立了雜亂的記憶檔案,可以加入以下指示:
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 分頁瀏覽內容。
請考慮定期清除長時間未存取的記憶檔案。
惡意的路徑輸入可能會嘗試存取 /memories 目錄以外的檔案。您的實作必須驗證所有路徑,以防止目錄遍歷攻擊。
請考慮以下防護措施:
/memories 開頭../、..\\ 或其他遍歷模式的路徑%2e%2e%2f)pathlib.Path.resolve() 和 relative_to())記憶工具使用與文字編輯器工具類似的錯誤處理模式。請參閱上方各個工具命令章節,以取得詳細的錯誤訊息和行為說明。常見錯誤包括找不到檔案、權限錯誤、無效路徑以及重複文字比對。
記憶工具可與上下文編輯搭配使用,以管理長時間執行的對話。詳情請參閱上下文編輯。
記憶工具也可以與壓縮功能搭配使用,該功能提供伺服器端對較舊對話上下文的摘要。上下文編輯會在用戶端清除特定的工具結果,而壓縮功能則會在對話接近上下文視窗限制時,自動在伺服器端摘要整個對話。
對於長時間執行的代理程式工作流程,請考慮同時使用兩者:壓縮功能可在無需用戶端記錄管理的情況下保持作用中上下文的可管理性,而記憶則可在壓縮邊界之間保留重要資訊,確保摘要中不會遺失任何關鍵內容。
對於跨越多個代理程式工作階段的長期軟體專案,記憶檔案需要經過刻意的初始化引導,而非僅在工作進行時臨時寫入。以下模式將記憶轉變為結構化的復原機制,讓每個新工作階段都能從上一個工作階段中斷的地方精確接續。
**初始化工作階段:**第一個工作階段會在任何實質性工作開始之前設定記憶產出物。這包括進度日誌(追蹤已完成的工作和接下來的工作)、功能檢查清單(定義工作範圍),以及專案所需的任何啟動或初始化指令碼的參考。
**後續工作階段:**每個新工作階段開始時都會讀取這些記憶產出物。這可在數秒內復原專案的完整狀態,無需重新探索程式碼庫或回溯先前的決策。
**工作階段結束時更新:**在工作階段結束前,更新進度日誌,記錄已完成的內容和剩餘的工作。這可確保下一個工作階段有準確的起點。
一次只處理一個功能。只有在端對端驗證確認功能正常運作後才將其標記為完成,而非僅在程式碼寫完後就標記。這可保持進度日誌的可信度,並防止範圍蔓延在多個工作階段間累積。
如需此模式實際應用的詳細案例研究,包括初始化指令碼、進度檔案結構和基於 git 的復原機制,請參閱 Effective harnesses for long-running agents。
Was this page helpful?