• 訊息
  • 託管代理
  • 管理
Search...
⌘K
第一步
Claude 簡介快速入門
使用 Claude 進行建構
功能概覽使用 Messages API停止原因與備援拒絕與備援備援額度
模型能力
擴展思考自適應思考努力程度任務預算(測試版)快速模式(研究預覽)結構化輸出引用串流訊息批次處理搜尋結果串流拒絕多語言支援嵌入
工具
概覽工具使用的運作方式教學:建構使用工具的代理定義工具處理工具呼叫平行工具使用工具執行器(SDK)嚴格工具使用搭配提示快取的工具使用伺服器工具疑難排解網頁搜尋工具網頁擷取工具程式碼執行工具顧問工具記憶體工具Bash 工具電腦使用工具文字編輯器工具
工具基礎架構
工具參考管理工具上下文工具組合工具搜尋程式化工具呼叫細粒度工具串流
上下文管理
上下文視窗壓縮上下文編輯提示快取對話中系統訊息建構協調模式快取診斷(測試版)Token 計數
處理檔案
Files APIPDF 支援圖片與視覺
技能
概覽快速入門最佳實務企業技能API 中的技能
MCP
遠端 MCP 伺服器MCP 連接器
雲端平台上的 Claude
Amazon BedrockAmazon Bedrock(舊版)AWS 上的 Claude PlatformMicrosoft FoundryVertex AI
Log in
記憶體工具
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
訊息/工具

記憶工具

記憶工具讓 Claude 能夠透過記憶檔案目錄,在多次對話之間儲存和擷取資訊。Claude 可以建立、讀取、更新和刪除在不同工作階段之間持續存在的檔案,使其能夠隨時間累積知識,而無需將所有內容保留在「context window」(上下文視窗)中。

這是即時上下文擷取的關鍵基本元件:代理程式不需要預先載入所有相關資訊,而是將所學內容儲存在記憶中,並在需要時取回。這讓作用中的上下文專注於當前相關的內容,對於長時間執行的工作流程至關重要,因為一次載入所有內容會使上下文視窗不堪負荷。請參閱 Effective context engineering 以了解更廣泛的模式。

記憶工具在用戶端運作:您可以透過自己的基礎架構控制資料的儲存位置和方式。

請透過意見回饋表單與我們分享您對此功能的意見。

此功能符合「Zero Data Retention」(零資料保留),即 ZDR 的資格。當您的組織具有 ZDR 安排時,透過此功能傳送的資料在 API 回應返回後不會被儲存。

使用案例

  • 在多次代理程式執行之間維持專案上下文
  • 從過去的互動、決策和回饋中學習
  • 隨時間建立知識庫
  • 實現跨對話學習,讓 Claude 在重複性工作流程中持續改進

運作方式

啟用後,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..."

如需模型支援資訊,請參閱工具參考。

開始使用

若要使用記憶工具:

  1. 將記憶工具新增至您的請求
  2. 實作用戶端處理常式以處理記憶操作

若要在您的應用程式中處理記憶工具操作,您需要為每個記憶命令實作處理常式。SDK 提供了處理工具介面的記憶工具輔助程式。您可以繼承 BetaAbstractMemoryTool(Python)或使用 betaMemoryTool(TypeScript)來實作您自己的記憶後端(檔案式、資料庫、雲端儲存、加密檔案等)。

如需可運作的範例,請參閱:

  • Python:examples/memory/basic.py
  • TypeScript:examples/tools-helpers-memory.ts

基本用法

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 最熟悉的建議行為,但您可以根據您的使用案例需求修改實作並回傳字串。

view

顯示目錄內容或檔案內容,可選擇指定行數範圍:

{
  "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}
  • 列出最多 2 層深度的檔案
  • 顯示人類可讀的大小(例如 5.5K、1.2M)
  • 排除隱藏項目(以 . 開頭的檔案)和 node_modules
  • 在大小和路徑之間使用 Tab 字元

**針對檔案:**回傳帶有標頭和行號的檔案內容:

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 hundred

錯誤處理

  • 檔案/目錄不存在:"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"

str_replace

取代檔案中的文字:

{
  "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"

目錄處理

如果路徑是目錄,則回傳「檔案不存在」錯誤。

insert

在特定行插入文字:

{
  "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}]"

目錄處理

如果路徑是目錄,則回傳「檔案不存在」錯誤。

delete

刪除檔案或目錄:

{
  "command": "delete",
  "path": "/memories/old_file.txt"
}

回傳值

  • 成功:"Successfully deleted {path}"

錯誤處理

  • 檔案/目錄不存在:"Error: The path {path} does not exist"

目錄處理

遞迴刪除目錄及其所有內容。

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"

目錄處理

重新命名目錄。

提示指引

啟用記憶工具時,系統提示中會自動包含以下指示:

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 開頭
  • 將路徑解析為其標準形式,並驗證其仍位於記憶目錄內
  • 拒絕包含 ../、..\\ 或其他遍歷模式的路徑
  • 留意 URL 編碼的遍歷序列(%2e%2e%2f)
  • 使用您所用程式語言內建的路徑安全工具(例如 Python 的 pathlib.Path.resolve() 和 relative_to())

錯誤處理

記憶工具使用與文字編輯器工具類似的錯誤處理模式。請參閱上方各個工具命令章節,以取得詳細的錯誤訊息和行為說明。常見錯誤包括找不到檔案、權限錯誤、無效路徑以及重複文字比對。

上下文編輯整合

記憶工具可與上下文編輯搭配使用,以管理長時間執行的對話。詳情請參閱上下文編輯。

與壓縮功能搭配使用

記憶工具也可以與壓縮功能搭配使用,該功能提供伺服器端對較舊對話上下文的摘要。上下文編輯會在用戶端清除特定的工具結果,而壓縮功能則會在對話接近上下文視窗限制時,自動在伺服器端摘要整個對話。

對於長時間執行的代理程式工作流程,請考慮同時使用兩者:壓縮功能可在無需用戶端記錄管理的情況下保持作用中上下文的可管理性,而記憶則可在壓縮邊界之間保留重要資訊,確保摘要中不會遺失任何關鍵內容。

多工作階段軟體開發模式

對於跨越多個代理程式工作階段的長期軟體專案,記憶檔案需要經過刻意的初始化引導,而非僅在工作進行時臨時寫入。以下模式將記憶轉變為結構化的復原機制,讓每個新工作階段都能從上一個工作階段中斷的地方精確接續。

運作方式

  1. **初始化工作階段:**第一個工作階段會在任何實質性工作開始之前設定記憶產出物。這包括進度日誌(追蹤已完成的工作和接下來的工作)、功能檢查清單(定義工作範圍),以及專案所需的任何啟動或初始化指令碼的參考。

  2. **後續工作階段:**每個新工作階段開始時都會讀取這些記憶產出物。這可在數秒內復原專案的完整狀態,無需重新探索程式碼庫或回溯先前的決策。

  3. **工作階段結束時更新:**在工作階段結束前,更新進度日誌,記錄已完成的內容和剩餘的工作。這可確保下一個工作階段有準確的起點。

關鍵原則

一次只處理一個功能。只有在端對端驗證確認功能正常運作後才將其標記為完成,而非僅在程式碼寫完後就標記。這可保持進度日誌的可信度,並防止範圍蔓延在多個工作階段間累積。

如需此模式實際應用的詳細案例研究,包括初始化指令碼、進度檔案結構和基於 git 的復原機制,請參閱 Effective harnesses for long-running agents。

後續步驟

查看所有工具

Anthropic 提供的工具及其屬性目錄。

上下文編輯

與記憶一起管理對話長度。

Was this page helpful?

  • 使用案例
  • 運作方式
  • 範例:記憶工具呼叫的運作方式
  • 開始使用
  • 基本用法
  • 工具命令
  • view
  • create
  • str_replace
  • insert
  • delete
  • rename
  • 提示指引
  • 安全考量
  • 敏感資訊
  • 檔案儲存大小
  • 記憶過期
  • 路徑遍歷防護
  • 錯誤處理
  • 上下文編輯整合
  • 與壓縮功能搭配使用
  • 多工作階段軟體開發模式
  • 運作方式
  • 關鍵原則
  • 後續步驟