Claude 可以使用 Anthropic 定义的文本编辑工具来查看和修改文本文件,帮助你调试、修复和改进代码或其他文本文档。这使得 Claude 能够直接与你的文件进行交互,提供实际的操作帮助,而不仅仅是提出建议。

使用文本编辑工具前的准备

选择兼容的模型 Anthropic 的文本编辑工具支持以下 Claude 模型:

  • Claude 4 系列模型 (claude-opus-4-20250514, claude-sonnet-4-20250514): text_editor_20250429
  • Claude 3.7 Sonnet (claude-3-7-sonnet-20250219): text_editor_20250124
  • Claude 3.5 Sonnet (claude-3-5-sonnet-20241022): text_editor_20241022

Claude 4 模型使用了全新的文本编辑工具,与旧版本不兼容。请确保使用正确的工具类型和名称。

模型对应的工具配置

模型版本工具类型工具名称支持的功能
Claude 4 (Opus/Sonnet)text_editor_20250429str_replace_based_edit_toolview, str_replace, create
Claude 3.7 Sonnettext_editor_20250124str_replace_editorview, str_replace, create, undo_edit
Claude 3.5 Sonnettext_editor_20241022str_replace_editorview, str_replace, create, undo_edit

重要变化: Claude 4 模型不再支持 undo_edit 命令,请在代码中移除对此功能的依赖。

评估使用场景

以下是使用文本编辑工具的一些典型场景:

  • 代码调试:帮助识别和修复代码中的问题,从语法错误到逻辑问题。
  • 代码重构:通过有针对性的编辑来改进代码结构、可读性和性能。
  • 文档生成:为你的代码库添加文档字符串、注释或 README 文件。
  • 测试创建:根据对实现的理解创建单元测试。

使用文本编辑工具

通过 Messages API 向 Claude 提供文本编辑工具(命名为 str_replace_editor): 需要安装 anthropic 包:

pip install anthropic

调用示例:

import anthropic

client = anthropic.Anthropic(
    api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
    base_url="https://aihubmix.com"
)

response = client.messages.create(
    model="claude-sonnet-4-20250514",  # 或 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 content:")
for message in response.content:
    print(message.text)

迁移到 Claude 4

如果您正在从 Claude 3.7 Sonnet 迁移到 Claude 4 模型,请注意以下变化:

更新工具配置

python
# Claude 3.7 Sonnet
tools=[
    {
        "type": "text_editor_20250124",
        "name": "str_replace_editor"
    }
]

# Claude 4 (Opus/Sonnet)
tools=[
    {
        "type": "text_editor_20250429",
        "name": "str_replace_based_edit_tool"
    }
]

移除不支持的功能

  • undo_edit 命令:Claude 4 模型不再支持撤销编辑功能
  • 请从您的代码中移除任何依赖 undo_edit 的逻辑

返回示例:

{
  "id": "msg_bdrk_012xyNaFCQg4zsVcTk5VkDAe",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'd be happy to 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",
      "text": "",
      "id": "toolu_bdrk_01P6jQG6suDSsDjzugqGVHWC",
      "name": "str_replace_based_edit_tool",
      "input": {
        "command": "view",
        "path": "/repo/primes.py"
      }
    }
  ],
  "model": "claude-sonnet-4-20250514",
  "stop_reason": "tool_use",
  "usage": {
    "input_tokens": 1042,
    "output_tokens": 115
  }
}