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

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

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

  • Claude 3.7 Sonnet: text_editor_20250124
  • Claude 3.5 Sonnet: text_editor_20241022 这两个版本提供相同的功能 - 你需要选择与你使用的模型相匹配的版本。

评估使用场景

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

代码调试:帮助识别和修复代码中的问题,从语法错误到逻辑问题。 代码重构:通过有针对性的编辑来改进代码结构、可读性和性能。 文档生成:为你的代码库添加文档字符串、注释或 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-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 content:")
for message in response.content:
    print(message.text)

返回示例:

{
  "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_editor",
      "input": {
        "command": "view",
        "path": "/repo/primes.py"
      }
    }
  ],
  "model": "claude-3-7-sonnet-20250219",
  "stop_reason": "tool_use",
  "usage": {
    "input_tokens": 1042,
    "output_tokens": 115
  }
}