Loading...
  • 建構
  • 管理
  • 模型與定價
  • 客戶端 SDK
  • API 參考
Search...
⌘K
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 能夠通過記憶文件目錄在對話之間存儲和檢索信息。Claude 可以創建、讀取、更新和刪除在會話之間持久存在的文件,允許它隨著時間的推移建立知識,而無需將所有內容保留在上下文窗口中。

這是即時上下文檢索的關鍵原語:代替預先加載所有相關信息,代理將其學到的內容存儲在記憶中,並根據需要將其拉回。這使活動上下文專注於當前相關的內容,對於長期運行的工作流至關重要,其中一次加載所有內容會使上下文窗口不堪重負。有關更廣泛的模式,請參閱有效的上下文工程。

記憶工具在客戶端運行:您通過自己的基礎設施控制數據的存儲位置和方式。

通過反饋表單分享您對此功能的反饋。

This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.

用例

  • 在多個代理執行中維護項目上下文
  • 從過去的交互、決策和反饋中學習
  • 隨著時間的推移構建知識庫
  • 啟用跨對話學習,其中 Claude 在重複工作流中改進

工作原理

啟用後,Claude 在開始任務前會自動檢查其記憶目錄。Claude 可以在 /memories 目錄中創建、讀取、更新和刪除文件,以存儲其工作時學到的內容,然後在將來的對話中引用這些記憶,以更有效地處理類似任務或從中斷的地方繼續。

由於這是一個客戶端工具,Claude 進行工具調用以執行記憶操作,您的應用程序在本地執行這些操作。這使您完全控制記憶的存儲位置和方式。出於安全考慮,您應該將所有記憶操作限制在 /memories 目錄中。

示例:記憶工具調用如何工作

當您要求 Claude 幫助完成任務時,Claude 會自動首先檢查其記憶目錄。以下是典型交互的樣子:

1. 用戶請求:

"幫我回應這個客戶服務工單。"

2. Claude 檢查記憶目錄:

"我會幫您回應客戶服務工單。讓我檢查我的記憶以獲取任何先前的上下文。"

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 使用記憶來幫助:

"根據您的客戶服務指南,我可以幫助您起草回應。請分享工單詳情..."

有關模型支持,請參閱工具參考。

入門

要使用記憶工具:

  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-7",
    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] // 可選:查看特定行
}

返回值

對於目錄: 返回一個列表,顯示文件和目錄及其大小:

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
  • 在大小和路徑之間使用製表符

對於文件: 返回帶有標題和行號的文件內容:

Here's the content of {path} with line numbers:
{line_numbers}{tab}{content}

行號格式:

  • 寬度:6 個字符,右對齐,用空格填充
  • 分隔符:行號和內容之間的製表符
  • 索引: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 創建混亂的記憶文件,您可以包含此指令:

注意:編輯記憶文件夾時,始終嘗試保持其內容最新、連貫和有組織。您可以重命名或刪除不再相關的文件。除非必要,否則不要創建新文件。

您也可以指導 Claude 寫入記憶的內容。例如:"只在您的記憶系統中寫下與 <topic> 相關的信息。"

安全考慮

以下是實現記憶存儲時的重要安全問題:

敏感信息

Claude 通常會拒絕在記憶文件中寫下敏感信息。但是,您可能想實現更嚴格的驗證,以剝離潛在的敏感信息。

文件存儲大小

考慮跟蹤記憶文件大小,並防止文件增長過大。考慮添加記憶讀取命令可以返回的最大字符數,並讓 Claude 通過內容分頁。

記憶過期

考慮定期清除在較長時間內未被訪問的記憶文件。

路徑遍歷保護

惡意路徑輸入可能會嘗試訪問 /memories 目錄外的文件。您的實現必須驗證所有路徑以防止目錄遍歷攻擊。

考慮這些保護措施:

  • 驗證所有路徑都以 /memories 開頭
  • 將路徑解析為其規範形式,並驗證它們保持在記憶目錄內
  • 拒絕包含 ../、..\ 或其他遍歷模式的路徑
  • 監視 URL 編碼的遍歷序列(%2e%2e%2f)
  • 使用您的語言的內置路徑安全實用程序(例如,Python 的 pathlib.Path.resolve() 和 relative_to())

錯誤處理

記憶工具使用與文本編輯器工具類似的錯誤處理模式。有關詳細的錯誤消息和行為,請參閱上面的各個工具命令部分。常見錯誤包括文件未找到、權限錯誤、無效路徑和重複文本匹配。

上下文編輯集成

記憶工具與上下文編輯配對以管理長期運行的對話。有關詳情,請參閱上下文編輯。

與壓縮一起使用

記憶工具也可以與壓縮配對,它提供舊對話上下文的服務器端摘要。雖然上下文編輯在客戶端清除特定工具結果,但壓縮在服務器端自動摘要整個對話,當它接近上下文窗口限制時。

對於跨越多個代理會話的長期運行工作流,考慮同時使用兩者:壓縮使活動上下文可管理,無需客戶端記錄,記憶在壓縮邊界之間持久化重要信息,以便在摘要中不會丟失任何關鍵內容。

多會話軟件開發模式

對於跨越多個代理會話的長期運行軟件項目,記憶文件需要有意引導,而不是隨著工作進展而臨時寫入。下面的模式將記憶轉變為結構化恢復機制,因此每個新會話都可以從上一個會話停止的地方繼續。

工作原理

  1. 初始化會話: 第一個會話在任何實質性工作開始之前設置記憶工件。這包括進度日誌(跟蹤已完成的內容和接下來的內容)、功能清單(定義工作範圍)以及對項目需要的任何啟動或初始化腳本的引用。

  2. 後續會話: 每個新會話通過讀取這些記憶工件來打開。這在幾秒鐘內恢復項目的完整狀態,無需重新探索代碼庫或重新追蹤早期決策。

  3. 會話結束更新: 在會話結束之前,它使用已完成的內容和剩餘內容更新進度日誌。這確保下一個會話有準確的起點。

關鍵原則

一次處理一個功能。只有在端到端驗證確認其有效後才標記功能完成,而不是在代碼編寫後。這使進度日誌值得信賴,並防止範圍蔓延在會話中複合。

有關此模式實踐中的詳細案例研究,包括初始化腳本、進度文件結構和基於 git 的恢復,請參閱長期運行代理的有效工具。

後續步驟

查看所有工具

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

上下文編輯

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

Was this page helpful?

  • view
  • create
  • str_replace
  • insert
  • delete
  • rename