Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示詞最佳實踐
    上下文管理
    上下文視窗壓縮上下文編輯
    功能
    提示詞快取延伸思考自適應思考思考力度串流訊息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實作工具使用細粒度工具串流Bash 工具程式碼執行工具程式化工具呼叫電腦使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐企業級 Skills透過 API 使用 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽版)Python SDK遷移指南
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞產生器使用提示詞範本提示詞改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 Claude 角色(系統提示詞)串聯複雜提示詞長上下文技巧延伸思考技巧
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    強化防護機制
    減少幻覺提高輸出一致性防範越獄攻擊串流拒絕減少提示詞洩漏讓 Claude 保持角色
    管理與監控
    Admin API 概覽資料駐留工作區用量與成本 APIClaude Code Analytics API零資料保留
    Console
    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
    • Catalog
    • 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
    • Catalog
    • 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 可以建立、讀取、更新和刪除在工作階段之間持久保存的檔案,讓它能夠隨時間累積知識,而無需將所有內容保留在上下文視窗中。

    記憶工具在客戶端運作——您可以透過自己的基礎設施控制資料的儲存位置和方式。

    記憶工具目前處於測試階段。要啟用它,請在您的 API 請求中使用測試版標頭 context-management-2025-06-27。

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

    使用案例

    • 在多次代理執行之間維護專案上下文
    • 從過去的互動、決策和回饋中學習
    • 隨時間建立知識庫
    • 實現跨對話學習,讓 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..."

    支援的模型

    記憶工具可在以下模型上使用:

    • Claude Opus 4.6 (claude-opus-4-6)
    • Claude Opus 4.5 (claude-opus-4-5-20251101)
    • Claude Opus 4.1 (claude-opus-4-1-20250805)
    • Claude Opus 4 (claude-opus-4-20250514)
    • Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)
    • Claude Sonnet 4 (claude-sonnet-4-20250514)
    • Claude Haiku 4.5 (claude-haiku-4-5-20251001)

    開始使用

    要使用記憶工具:

    1. 在您的 API 請求中包含測試版標頭 context-management-2025-06-27
    2. 將記憶工具新增到您的請求中
    3. 實作客戶端的記憶操作處理程式

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

    如需工作範例,請參閱:

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

    基本用法

    curl https://api.anthropic.com/v1/messages \
        --header "x-api-key: $ANTHROPIC_API_KEY" \
        --header "anthropic-version: 2023-06-01" \
        --header "content-type: application/json" \
        --header "anthropic-beta: context-management-2025-06-27" \
        --data '{
            "model": "claude-opus-4-6",
            "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"
            }]
        }'

    工具命令

    您的客戶端實作需要處理這些記憶工具命令。雖然這些規格描述了 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
    • 在大小和路徑之間使用 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 建立了雜亂的記憶檔案,您可以加入以下指令:

    注意:編輯記憶資料夾時,請始終保持其內容最新、連貫且有組織。您可以重新命名或刪除不再相關的檔案。除非必要,否則不要建立新檔案。

    您也可以引導 Claude 寫入記憶的內容,例如「只在您的記憶系統中記錄與 <topic> 相關的資訊。」

    安全考量

    以下是實作記憶儲存時的重要安全考量:

    敏感資訊

    Claude 通常會拒絕在記憶檔案中寫入敏感資訊。但是,您可能需要實作更嚴格的驗證來過濾潛在的敏感資訊。

    檔案儲存大小

    考慮追蹤記憶檔案大小並防止檔案過大。考慮為記憶讀取命令新增最大字元數限制,並讓 Claude 分頁瀏覽內容。

    記憶過期

    考慮定期清除長時間未存取的記憶檔案。

    路徑遍歷保護

    惡意路徑輸入可能嘗試存取 /memories 目錄之外的檔案。您的實作必須驗證所有路徑以防止目錄遍歷攻擊。

    考慮以下防護措施:

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

    錯誤處理

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

    與上下文編輯搭配使用

    記憶工具可以與上下文編輯結合使用,當對話上下文超過設定的閾值時,上下文編輯會自動清除舊的工具結果。這種組合可以實現長時間運行的代理工作流程,否則這些工作流程會超出上下文限制。

    它們如何協同運作

    當啟用上下文編輯且您的對話接近清除閾值時,Claude 會自動收到警告通知。這會提示 Claude 在工具結果從上下文視窗中被清除之前,將任何重要資訊保存到記憶檔案中。

    在工具結果被清除後,Claude 可以在需要時從記憶檔案中檢索儲存的資訊,有效地將記憶作為其工作上下文的延伸。這使 Claude 能夠:

    • 在不遺失關鍵資訊的情況下繼續複雜的多步驟工作流程
    • 即使在工具結果被移除後仍能參考過去的工作和決策
    • 在超出典型上下文限制的對話中維持連貫的上下文
    • 隨時間建立知識庫,同時保持活動上下文視窗的可管理性

    範例工作流程

    考慮一個包含許多檔案操作的程式碼重構專案:

    1. Claude 對檔案進行大量編輯,產生許多工具結果
    2. 當上下文增長並接近您的閾值時,Claude 收到警告
    3. Claude 將目前為止所做的變更摘要到記憶檔案中(例如 /memories/refactoring_progress.xml)
    4. 上下文編輯自動清除較舊的工具結果
    5. Claude 繼續工作,在需要回顧已完成的變更時參考記憶檔案
    6. 工作流程可以無限期地繼續,Claude 同時管理活動上下文和持久記憶

    設定

    要同時使用這兩個功能:

    response = client.beta.messages.create(
        model="claude-opus-4-6",
        max_tokens=4096,
        messages=[...],
        tools=[
            {
                "type": "memory_20250818",
                "name": "memory"
            },
            # Your other tools
        ],
        betas=["context-management-2025-06-27"],
        context_management={
            "edits": [
                {
                    "type": "clear_tool_uses_20250919",
                    "trigger": {
                        "type": "input_tokens",
                        "value": 100000
                    },
                    "keep": {
                        "type": "tool_uses",
                        "value": 3
                    }
                }
            ]
        }
    )

    您也可以排除記憶工具呼叫不被清除,以確保 Claude 始終能存取最近的記憶操作:

    context_management={
        "edits": [
            {
                "type": "clear_tool_uses_20250919",
                "exclude_tools": ["memory"]
            }
        ]
    }

    與壓縮搭配使用

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

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

    Was this page helpful?

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