Claude 可以使用 Anthropic 定義的文字編輯器工具來檢視和修改文字檔案,協助您除錯、修復和改善程式碼或其他文字文件。這讓 Claude 能夠直接與您的檔案互動,提供實際操作的協助,而不只是建議變更。

使用文字編輯器工具之前

使用相容的模型

Anthropic 的文字編輯器工具適用於多個 Claude 模型:

  • Claude 4 Opus & Sonnettext_editor_20250429
  • Claude Sonnet 3.7text_editor_20250124
  • Claude Sonnet 3.5text_editor_20241022

Claude Sonnet 3.5 在使用文字編輯器工具時需要 computer-use-2024-10-22 beta 標頭。

文字編輯器工具在 Claude 4 和 Sonnet 3.7 中已正式推出。

較新的 text_editor_20250429 適用於 Claude 4 模型,但不包含 undo_edit 指令。如果您需要此功能,您需要使用 Claude 3.7 或 Sonnet 3.5 及其相應的工具版本。

評估您的使用案例適合性

以下是一些使用文字編輯器工具的範例:

  • 程式碼除錯:讓 Claude 識別並修復程式碼中的錯誤,從語法錯誤到邏輯問題。
  • 程式碼重構:讓 Claude 透過有針對性的編輯來改善程式碼結構、可讀性和效能。
  • 文件生成:要求 Claude 為您的程式碼庫新增文件字串、註解或 README 檔案。
  • 測試建立:讓 Claude 根據對實作的理解為您的程式碼建立單元測試。

使用文字編輯器工具

使用 Messages API 向 Claude 提供文字編輯器工具(名為 str_replace_based_edit_tool):

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250429",
        "name": "str_replace_based_edit_tool"
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
      }
    ]
  }'

文字編輯器工具可以按以下方式使用:

1

向 Claude 提供文字編輯器工具和使用者提示

  • 在您的 API 請求中包含文字編輯器工具
  • 提供可能需要檢查或修改檔案的使用者提示,例如「您能修復我程式碼中的語法錯誤嗎?」
2

Claude 使用工具檢查檔案或目錄

  • Claude 評估需要查看的內容,並使用 view 指令檢查檔案內容或列出目錄內容
  • API 回應將包含帶有 view 指令的 tool_use 內容區塊
3

執行檢視指令並回傳結果

  • 從 Claude 的工具使用請求中提取檔案或目錄路徑
  • 讀取檔案內容或列出目錄內容並將其回傳給 Claude
  • 透過包含 tool_result 內容區塊的新 user 訊息繼續對話,將結果回傳給 Claude
4

Claude 使用工具修改檔案

  • 檢查檔案或目錄後,Claude 可能會使用 str_replace 等指令進行變更,或使用 insert 在特定行號新增文字。
  • 如果 Claude 使用 str_replace 指令,Claude 會建構一個格式正確的工具使用請求,包含舊文字和要替換的新文字
5

執行編輯並回傳結果

  • 從 Claude 的工具使用請求中提取檔案路徑、舊文字和新文字
  • 在檔案中執行文字替換
  • 將結果回傳給 Claude
6

Claude 提供分析和說明

  • 檢查並可能編輯檔案後,Claude 提供完整的說明,說明發現的內容和所做的變更

文字編輯器工具指令

文字編輯器工具支援多個用於檢視和修改檔案的指令:

view

view 指令允許 Claude 檢查檔案內容或列出目錄內容。它可以讀取整個檔案或特定行範圍。

參數:

  • command:必須是 “view”
  • path:要檢視的檔案或目錄路徑
  • view_range(可選):包含兩個整數的陣列,指定要檢視的開始和結束行號。行號從 1 開始索引,結束行的 -1 表示讀取到檔案末尾。此參數僅適用於檢視檔案,不適用於目錄。

str_replace

str_replace 指令允許 Claude 將檔案中的特定字串替換為新字串。這用於進行精確編輯。

參數:

  • command:必須是 “str_replace”
  • path:要修改的檔案路徑
  • old_str:要替換的文字(必須完全匹配,包括空白和縮排)
  • new_str:要插入以替代舊文字的新文字

create

create 指令允許 Claude 建立包含指定內容的新檔案。

參數:

  • command:必須是 “create”
  • path:應建立新檔案的路徑
  • file_text:要寫入新檔案的內容

insert

insert 指令允許 Claude 在檔案中的特定位置插入文字。

參數:

  • command:必須是 “insert”
  • path:要修改的檔案路徑
  • insert_line:要在其後插入文字的行號(0 表示檔案開頭)
  • new_str:要插入的文字

undo_edit

undo_edit 指令允許 Claude 撤銷對檔案所做的最後一次編輯。

此指令僅在 Claude Sonnet 3.7 和 Claude Sonnet 3.5 中可用。使用 text_editor_20250429 的 Claude 4 模型不支援此功能。

參數:

  • command:必須是 “undo_edit”
  • path:應撤銷最後一次編輯的檔案路徑

範例:使用文字編輯器工具修復語法錯誤

此範例示範 Claude 4 如何使用文字編輯器工具修復 Python 檔案中的語法錯誤。

首先,您的應用程式向 Claude 提供文字編輯器工具和修復語法錯誤的提示:

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250429",
        "name": "str_replace_based_edit_tool"
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
      }
    ]
  }'

Claude 將首先使用文字編輯器工具檢視檔案:

{
  "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
  "model": "claude-opus-4-20250514",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."
    },
    {
      "type": "tool_use",
      "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
      "name": "str_replace_based_edit_tool",
      "input": {
        "command": "view",
        "path": "primes.py"
      }
    }
  ]
}

您的應用程式應該讀取檔案並將其內容回傳給 Claude:

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250429",
        "name": "str_replace_based_edit_tool"
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
      },
      {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "I'\''ll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."
                },
                {
                    "type": "tool_use",
                    "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
                    "name": "str_replace_based_edit_tool",
                    "input": {
                        "command": "view",
                        "path": "primes.py"
                    }
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
                    "content": "1: def is_prime(n):\n2:     \"\"\"Check if a number is prime.\"\"\"\n3:     if n <= 1:\n4:         return False\n5:     if n <= 3:\n6:         return True\n7:     if n % 2 == 0 or n % 3 == 0:\n8:         return False\n9:     i = 5\n10:     while i * i <= n:\n11:         if n % i == 0 or n % (i + 2) == 0:\n12:             return False\n13:         i += 6\n14:     return True\n15: \n16: def get_primes(limit):\n17:     \"\"\"Generate a list of prime numbers up to the given limit.\"\"\"\n18:     primes = []\n19:     for num in range(2, limit + 1)\n20:         if is_prime(num):\n21:             primes.append(num)\n22:     return primes\n23: \n24: def main():\n25:     \"\"\"Main function to demonstrate prime number generation.\"\"\"\n26:     limit = 100\n27:     prime_list = get_primes(limit)\n28:     print(f\"Prime numbers up to {limit}:\")\n29:     print(prime_list)\n30:     print(f\"Found {len(prime_list)} prime numbers.\")\n31: \n32: if __name__ == \"__main__\":\n33:     main()"
                }
            ]
        }
    ]
  }'

行號

在上面的範例中,view 工具結果包含每行前面都有行號的檔案內容(例如,“1: def is_prime(n):”)。行號不是必需的,但對於成功使用 view_range 參數檢查檔案的特定部分和使用 insert_line 參數在精確位置新增內容至關重要。

Claude 將識別語法錯誤並使用 str_replace 指令修復它:

{
  "id": "msg_01VwXyZAbCdEfGhIjKlMnO",
  "model": "claude-opus-4-20250514",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."
    },
    {
      "type": "tool_use",
      "id": "toolu_01PqRsTuVwXyZAbCdEfGh",
      "name": "str_replace_based_edit_tool",
      "input": {
        "command": "str_replace",
        "path": "primes.py",
        "old_str": "    for num in range(2, limit + 1)",
        "new_str": "    for num in range(2, limit + 1):"
      }
    }
  ]
}

您的應用程式應該進行編輯並回傳結果:

response = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    tools=[
        {
            "type": "text_editor_20250429",
            "name": "str_replace_based_edit_tool"
        }
    ],
    messages=[
        # Previous messages...
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."
                },
                {
                    "type": "tool_use",
                    "id": "toolu_01PqRsTuVwXyZAbCdEfGh",
                    "name": "str_replace_based_edit_tool",
                    "input": {
                        "command": "str_replace",
                        "path": "primes.py",
                        "old_str": "    for num in range(2, limit + 1)",
                        "new_str": "    for num in range(2, limit + 1):"
                    }
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",
                    "content": "Successfully replaced text at exactly one location."
                }
            ]
        }
    ]
)

最後,Claude 將提供修復的完整說明:

{
  "id": "msg_01IjKlMnOpQrStUvWxYzAb",
  "model": "claude-opus-4-20250514",
  "stop_reason": "end_turn",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I've fixed the syntax error in your primes.py file. The issue was in the `get_primes` function at line 19. There was a missing colon (:) at the end of the for loop line.\n\nHere's what I changed:\n\nFrom:\n```python\nfor num in range(2, limit + 1)\n```\n\nTo:\n```python\nfor num in range(2, limit + 1):\n```\n\nIn Python, a colon is required at the end of statements that start a new code block, such as for loops, if statements, function definitions, etc. Without the colon, Python raises a syntax error because it doesn't know where the code block begins.\n\nYour code should now run correctly. The function will properly generate a list of prime numbers up to the specified limit."
    }
  ]
}

實作文字編輯器工具

文字編輯器工具實作為無結構描述工具。使用此工具時,您不需要像其他工具一樣提供輸入結構描述;結構描述內建於 Claude 的模型中且無法修改。

工具類型取決於模型版本:

  • Claude 4type: "text_editor_20250429"
  • Claude Sonnet 3.7type: "text_editor_20250124"
  • Claude Sonnet 3.5type: "text_editor_20241022"
1

初始化您的編輯器實作

建立輔助函數來處理檔案操作,如讀取、寫入和修改檔案。考慮實作備份功能以從錯誤中恢復。

2

處理編輯器工具呼叫

建立一個根據指令類型處理 Claude 工具呼叫的函數:

def handle_editor_tool(tool_call, model_version):
    input_params = tool_call.input
    command = input_params.get('command', '')
    file_path = input_params.get('path', '')
    
    if command == 'view':
        # Read and return file contents
        pass
    elif command == 'str_replace':
        # Replace text in file
        pass
    elif command == 'create':
        # Create new file
        pass
    elif command == 'insert':
        # Insert text at location
        pass
    elif command == 'undo_edit':
        # Check if it's a Claude 4 model
        if 'str_replace_based_edit_tool' in model_version:
            return {"error": "undo_edit command is not supported in Claude 4"}
        # Restore from backup for Claude 3.7/3.5
        pass
3

實作安全措施

新增驗證和安全檢查:

  • 驗證檔案路徑以防止目錄遍歷
  • 在進行變更前建立備份
  • 優雅地處理錯誤
  • 實作權限檢查
4

處理 Claude 的回應

從 Claude 的回應中提取和處理工具呼叫:

# Process tool use in Claude's response
for content in response.content:
    if content.type == "tool_use":
        # Execute the tool based on command
        result = handle_editor_tool(content)
        
        # Return result to Claude
        tool_result = {
            "type": "tool_result",
            "tool_use_id": content.id,
            "content": result
        }

實作文字編輯器工具時,請記住:

  1. 安全性:該工具可以存取您的本地檔案系統,因此請實作適當的安全措施。
  2. 備份:在允許編輯重要檔案之前,請務必建立備份。
  3. 驗證:驗證所有輸入以防止意外變更。
  4. 唯一匹配:確保替換完全匹配一個位置,以避免意外編輯。

處理錯誤

使用文字編輯器工具時,可能會發生各種錯誤。以下是處理這些錯誤的指導:

遵循實作最佳實務


定價和代幣使用

The text editor tool uses the same pricing structure as other tools used with Claude. It follows the standard input and output token pricing based on the Claude model you’re using.

In addition to the base tokens, the following additional input tokens are needed for the text editor tool:

ToolAdditional input tokens
text_editor_20250429 (Claude 4)700 tokens
text_editor_20250124 (Claude Sonnet 3.7)700 tokens
text_editor_20241022 (Claude Sonnet 3.5)700 tokens

有關工具定價的更詳細資訊,請參閱工具使用定價

將文字編輯器工具與其他工具整合

文字編輯器工具可以與其他 Claude 工具一起使用。組合工具時,請確保您:

  • 將工具版本與您使用的模型匹配
  • 考慮請求中包含的所有工具的額外代幣使用量

變更日誌

日期版本變更
2025年4月29日text_editor_20250429發布 Claude 4 的文字編輯器工具。此版本移除了 undo_edit 指令,但保持所有其他功能。工具名稱已更新以反映其基於 str_replace 的架構。
2025年3月13日text_editor_20250124引入獨立文字編輯器工具文件。此版本針對 Claude Sonnet 3.7 進行了最佳化,但與先前版本具有相同的功能。
2024年10月22日text_editor_20241022與 Claude Sonnet 3.5 一起初次發布文字編輯器工具。透過 viewcreatestr_replaceinsertundo_edit 指令提供檢視、建立和編輯檔案的功能。

後續步驟

以下是一些如何以更方便和強大的方式使用文字編輯器工具的想法:

  • 與您的開發工作流程整合:將文字編輯器工具建置到您的開發工具或 IDE 中
  • 建立程式碼審查系統:讓 Claude 審查您的程式碼並進行改善
  • 建置除錯助手:建立一個系統,讓 Claude 可以幫助您診斷和修復程式碼中的問題
  • 實作檔案格式轉換:讓 Claude 幫助您將檔案從一種格式轉換為另一種格式
  • 自動化文件:設定工作流程讓 Claude 自動為您的程式碼建立文件

當您使用文字編輯器工具建置應用程式時,我們很興奮看到您如何利用 Claude 的功能來增強您的開發工作流程和生產力。