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

使用文本编辑器工具之前

使用兼容的模型

Anthropic的文本编辑器工具适用于多个Claude模型:

  • Claude 4 Opus & Sonnet: text_editor_20250429
  • Claude Sonnet 3.7: text_editor_20250124
  • Claude Sonnet 3.5: text_editor_20241022

Claude Sonnet 3.5在使用文本编辑器工具时需要computer-use-2024-10-22 beta头部。

文本编辑器工具在Claude 4和Sonnet 3.7中普遍可用。

Claude 4模型的较新版本text_editor_20250429不包含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

执行view命令并返回结果

  • 从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 4: type: "text_editor_20250429"
  • Claude Sonnet 3.7: type: "text_editor_20250124"
  • Claude Sonnet 3.5: type: "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的功能来增强您的开发工作流程和生产力。