使用 Messages API 向 Claude 提供文字編輯器工具(名為 str_replace_based_edit_tool):
import anthropicclient = anthropic.Anthropic()response = client.messages.create( 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?"}])
使用 Messages API 向 Claude 提供文字編輯器工具(名為 str_replace_based_edit_tool):
import anthropicclient = anthropic.Anthropic()response = client.messages.create( 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?"}])
使用 Messages API 向 Claude 提供文字編輯器工具(名為 str_replace_editor):
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-3-7-sonnet-20250124", max_tokens=1024, tools=[{"type":"text_editor_20250124","name":"str_replace_editor"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])
使用 Messages API 向 Claude 提供文字編輯器工具(名為 str_replace_editor):
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, tools=[{"type":"text_editor_20241022","name":"str_replace_editor"}], 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
str_replace 命令允許 Claude 用新字串替換檔案中的特定字串。這用於進行精確的編輯。
參數:
command:必須是 “str_replace”
path:要修改的檔案路徑
old_str:要替換的文字(必須完全匹配,包括空格和縮排)
new_str:要插入替代舊文字的新文字
{"type":"tool_use","id":"toolu_01A09q90qw90lq917835lq9","name":"str_replace_editor","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):"}}
{"type":"tool_use","id":"toolu_01A09q90qw90lq917835lq9","name":"str_replace_editor","input":{"command":"insert","path":"primes.py","insert_line":0,"new_str":"\"\"\"Module for working with prime numbers.\n\nThis module provides functions to check if a number is prime\nand to generate a list of prime numbers up to a given limit.\n\"\"\"\n"}}
import anthropicclient = anthropic.Anthropic()response = client.messages.create( 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?"}])print(response)
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:
response = client.messages.create( 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()"}]}])
{"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 4 如何使用文字編輯器工具修復 Python 檔案中的語法錯誤。
首先,您的應用程式向 Claude 提供文字編輯器工具和修復語法錯誤的提示:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( 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?"}])print(response)
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:
response = client.messages.create( 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()"}]}])
{"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 Sonnet 3.7 如何使用文字編輯器工具修復 Python 檔案中的語法錯誤。
首先,您的應用程式向 Claude 提供文字編輯器工具和修復語法錯誤的提示:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-3-7-sonnet-20250219", max_tokens=1024, tools=[{"type":"text_editor_20250124","name":"str_replace_editor"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])print(response)
Claude Sonnet 3.7 示例遵循與上面 Claude 4 示例相同的格式,使用相同的工具調用和回應,但使用 text_editor_20250124 工具類型和 str_replace_editor 名稱。
文字編輯器工具被實現為無模式工具。使用此工具時,您不需要像其他工具那樣提供輸入模式;模式已內置到 Claude 的模型中,無法修改。
工具類型取決於模型版本:
Claude 4:type: "text_editor_20250429"
Claude Sonnet 3.7:type: "text_editor_20250124"
Claude Sonnet 3.5:type: "text_editor_20241022"
1
初始化您的編輯器實現
創建輔助函數來處理檔案操作,如讀取、寫入和修改檔案。考慮實現備份功能以從錯誤中恢復。
2
處理編輯器工具調用
創建一個基於命令類型處理來自 Claude 的工具調用的函數:
defhandle_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':# 讀取並返回檔案內容passelif command =='str_replace':# 替換檔案中的文字passelif command =='create':# 創建新檔案passelif command =='insert':# 在位置插入文字passelif command =='undo_edit':# 檢查是否為 Claude 4 模型if'str_replace_based_edit_tool'in model_version:return{"error":"undo_edit command is not supported in Claude 4"}# 從備份恢復 Claude 3.7/3.5pass
3
實現安全措施
添加驗證和安全檢查:
驗證檔案路徑以防止目錄遍歷
在進行更改前創建備份
優雅地處理錯誤
實現權限檢查
4
處理 Claude 的回應
從 Claude 的回應中提取並處理工具調用:
# 處理 Claude 回應中的工具使用for content in response.content:if content.type=="tool_use":# 基於命令執行工具 result = handle_editor_tool(content)# 將結果返回給 Claude tool_result ={"type":"tool_result","tool_use_id": content.id,"content": result}
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: File not found","is_error":true}]}
如果 Claude 的 str_replace 命令在檔案中匹配多個位置,返回適當的錯誤訊息:
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: Found 3 matches for replacement text. Please provide more context to make a unique match.","is_error":true}]}
如果 Claude 的 str_replace 命令在檔案中沒有匹配任何文字,返回適當的錯誤訊息:
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: No match found for replacement. Please check your text and try again.","is_error":true}]}
如果創建、讀取或修改檔案時出現權限問題,返回適當的錯誤訊息:
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: Permission denied. Cannot write to file.","is_error":true}]}