使用 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)
{"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()"}]}])
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 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)
{"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()"}]}])
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 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.5 从备份恢复pass
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}]}