Text editor tool


Note

此功能符合零数据保留 (ZDR) 资格。当你的组织有 ZDR 安排时,通过此功能发送的数据在 API 响应返回后不会被存储。

Claude 可以使用 Anthropic schema 的 text editor tool 来查看和修改文本文件,帮助你调试、修复和改进代码或其他文本文档。这允许 Claude 直接与你的文件交互,提供实际操作帮助而非仅仅建议更改。

模型支持参见工具参考

何时使用 text editor tool

使用 text editor tool 的一些场景示例:

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

使用 text editor tool

使用 Messages API 将 text editor tool(命名为 str_replace_based_edit_tool)提供给 Claude。

你可以选择性地指定 max_characters 参数来控制查看大文件时的截断行为。

Note

max_characters 仅兼容 text_editor_20250728 及更高版本的 text editor 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-7",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250728",
        "name": "str_replace_based_edit_tool",
        "max_characters": 10000
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
      }
    ]
  }'
ant messages create \
  --model claude-opus-4-7 \
  --max-tokens 1024 \
  --tool '{type: text_editor_20250728, name: str_replace_based_edit_tool, max_characters: 10000}' \
  --message '{role: user, content: There is a syntax error in my primes.py file. Can you help me fix it?}'
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    tools=[
        {
            "type": "text_editor_20250728",
            "name": "str_replace_based_edit_tool",
            "max_characters": 10000,
        }
    ],
    messages=[
        {
            "role": "user",
            "content": "There's a syntax error in my primes.py file. Can you help me fix it?",
        }
    ],
)

print(response)
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

const response = await anthropic.messages.create({
  model: "claude-opus-4-7",
  max_tokens: 1024,
  tools: [
    {
      type: "text_editor_20250728",
      name: "str_replace_based_edit_tool",
      max_characters: 10000
    }
  ],
  messages: [
    {
      role: "user",
      content: "There's a syntax error in my primes.py file. Can you help me fix it?"
    }
  ]
});

console.log(response);
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.ToolTextEditor20250728;

void main() {
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  ToolTextEditor20250728 editorTool =
    ToolTextEditor20250728.builder()
      .maxCharacters(10000L)
      .build();

  MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_4_7)
    .maxTokens(1024)
    .addTool(editorTool)
    .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")
    .build();

  Message message = client.messages().create(params);
  IO.println(message);
}

text editor tool 可按以下方式使用:

  1. 为 Claude 提供 text editor tool 和用户提示

    • 在 API 请求中包含 text editor tool
    • 提供可能需要检查或修改文件的用户提示,例如"你能修复我代码中的语法错误吗?"
  2. Claude 使用工具检查文件或目录

    • Claude 评估需要查看的内容,并使用 view 命令检查文件内容或列出目录内容
    • API 响应将包含一个带有 view 命令的 tool_use 内容块
  3. 执行 view 命令并返回结果

    • 从 Claude 的工具使用请求中提取文件或目录路径
    • 读取文件内容或列出目录内容
    • 如果在工具配置中指定了 max_characters 参数,将文件内容截断到该长度
    • 通过使用包含 tool_result 内容块的新 user 消息继续对话,将结果返回给 Claude
  4. Claude 使用工具修改文件

    • 检查文件或目录后,Claude 可能会使用 str_replace 等命令进行更改,或使用 insert 在特定行号添加文本。
    • 如果 Claude 使用 str_replace 命令,Claude 会构建格式正确的工具使用请求,包含旧文本和替换的新文本
  5. 执行编辑并返回结果

    • 从 Claude 的工具使用请求中提取文件路径、旧文本和新文本
    • 在文件中执行文本替换
    • 将结果返回给 Claude
  6. Claude 提供分析和解释

    • 检查并可能编辑文件后,Claude 提供关于发现内容和所做更改的完整解释

Text editor tool 命令

text editor tool 支持多个用于查看和修改文件的命令:

view

view 命令允许 Claude 检查文件内容或列出目录内容。它可以读取整个文件或特定行范围。

参数:

  • command:必须为 "view"
  • path:要查看的文件或目录路径
  • view_range(可选):一个包含两个整数的数组,指定要查看的起始和结束行号。行号从 1 开始,结束行号为 -1 表示读取到文件末尾。此参数仅适用于查看文件,不适用于目录。

view 命令示例

查看文件的示例:

{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_based_edit_tool",
  "input": {
    "command": "view",
    "path": "primes.py"
  }
}

查看目录的示例:

{
  "type": "tool_use",
  "id": "toolu_02B19r91rw91mr917835mr9",
  "name": "str_replace_based_edit_tool",
  "input": {
    "command": "view",
    "path": "src/"
  }
}

str_replace

str_replace 命令允许 Claude 将文件中的特定字符串替换为新字符串。这用于进行精确编辑。

参数:

  • command:必须为 "str_replace"
  • path:要修改的文件路径
  • old_str:要替换的文本(必须精确匹配,包括空格和缩进)
  • new_str:用于替换旧文本的新文本

str_replace 命令示例

{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "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):"
  }
}

create

create 命令允许 Claude 创建一个包含指定内容的新文件。

参数:

  • command:必须为 "create"
  • path:新文件的创建路径
  • file_text:写入新文件的内容

create 命令示例

{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_based_edit_tool",
  "input": {
    "command": "create",
    "path": "test_primes.py",
    "file_text": "import unittest\nimport primes\n\nclass TestPrimes(unittest.TestCase):\n    def test_is_prime(self):\n        self.assertTrue(primes.is_prime(2))\n        self.assertTrue(primes.is_prime(3))\n        self.assertFalse(primes.is_prime(4))\n\nif __name__ == '__main__':\n    unittest.main()"
  }
}

insert

insert 命令允许 Claude 在文件的特定位置插入文本。

参数:

  • command:必须为 "insert"
  • path:要修改的文件路径
  • insert_line:在其后插入文本的行号(0 表示文件开头)
  • insert_text:要插入的文本

insert 命令示例

{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_based_edit_tool",
  "input": {
    "command": "insert",
    "path": "primes.py",
    "insert_line": 0,
    "insert_text": "\"\"\"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"
  }
}

示例:使用 text editor tool 修复语法错误

此示例演示 Claude 如何使用 text editor tool 修复 Python 文件中的语法错误。

首先,你的应用程序为 Claude 提供 text editor 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-7",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250728",
        "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?"
      }
    ]
  }'
ant messages create \
  --model claude-opus-4-7 \
  --max-tokens 1024 \
  --tool '{type: text_editor_20250728, name: str_replace_based_edit_tool}' \
  --message '{role: user, content: There is a syntax error in my primes.py file. Can you help me fix it?}'
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    tools=[{"type": "text_editor_20250728", "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)
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

const response = await anthropic.messages.create({
  model: "claude-opus-4-7",
  max_tokens: 1024,
  tools: [
    {
      type: "text_editor_20250728",
      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?"
    }
  ]
});

console.log(response);
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.ToolTextEditor20250728;

void main() {
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  ToolTextEditor20250728 editorTool =
    ToolTextEditor20250728.builder().build();

  MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_4_7)
    .maxTokens(1024)
    .addTool(editorTool)
    .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")
    .build();

  Message message = client.messages().create(params);
  IO.println(message);
}

Claude 首先使用 text editor tool 查看文件:

{
  "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
  "model": "claude-opus-4-7",
  "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-7",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250728",
        "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()"
                }
            ]
        }
    ]
  }'
ant messages create <<'YAML'
model: claude-opus-4-7
max_tokens: 1024
tools:
  - type: text_editor_20250728
    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):
          2:     """Check if a number is prime."""
          3:     if n <= 1:
          4:         return False
          5:     if n <= 3:
          6:         return True
          7:     if n % 2 == 0 or n % 3 == 0:
          8:         return False
          9:     i = 5
          10:     while i * i <= n:
          11:         if n % i == 0 or n % (i + 2) == 0:
          12:             return False
          13:         i += 6
          14:     return True
          15:
          16: def get_primes(limit):
          17:     """Generate a list of prime numbers up to the given limit."""
          18:     primes = []
          19:     for num in range(2, limit + 1)
          20:         if is_prime(num):
          21:             primes.append(num)
          22:     return primes
          23:
          24: def main():
          25:     """Main function to demonstrate prime number generation."""
          26:     limit = 100
          27:     prime_list = get_primes(limit)
          28:     print(f"Prime numbers up to {limit}:")
          29:     print(prime_list)
          30:     print(f"Found {len(prime_list)} prime numbers.")
          31:
          32: if __name__ == "__main__":
          33:     main()
YAML
response = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    tools=[{"type": "text_editor_20250728", "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()',
                }
            ],
        },
    ],
)

print(response)
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

const response = await anthropic.messages.create({
  model: "claude-opus-4-7",
  max_tokens: 1024,
  tools: [
    {
      type: "text_editor_20250728",
      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()'
        }
      ]
    }
  ]
});

console.log(response);
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.TextBlockParam;
import com.anthropic.models.messages.ToolResultBlockParam;
import com.anthropic.models.messages.ToolTextEditor20250728;
import com.anthropic.models.messages.ToolUseBlockParam;
import java.util.List;

public class TextEditorToolResultExample {

  public static void main(String[] args) {
    AnthropicClient client = AnthropicOkHttpClient.fromEnv();

    MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_4_7)
      .maxTokens(1024)
      .addTool(ToolTextEditor20250728.builder().build())
      .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")
      .addAssistantMessageOfBlockParams(
        List.of(
          ContentBlockParam.ofText(
            TextBlockParam.builder()
              .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.")
              .build()
          ),
          ContentBlockParam.ofToolUse(
            ToolUseBlockParam.builder()
              .id("toolu_01AbCdEfGhIjKlMnOpQrStU")
              .name("str_replace_based_edit_tool")
              .input(
                ToolUseBlockParam.Input.builder()
                  .putAdditionalProperty("command", JsonValue.from("view"))
                  .putAdditionalProperty("path", JsonValue.from("primes.py"))
                  .build()
              )
              .build()
          )
        )
      )
      .addUserMessageOfBlockParams(
        List.of(
          ContentBlockParam.ofToolResult(
            ToolResultBlockParam.builder()
              .toolUseId("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()")
              .build()
          )
        )
      )
      .build();

    Message message = client.messages().create(params);
    System.out.println(message);
  }
}
Tip

行号

在上面的示例中,view 工具结果包含在每行前面添加了行号的文件内容(例如 "1: def is_prime(n):")。行号不是必需的,但对于成功使用 view_range 参数查看文件的特定部分和 insert_line 参数在精确位置添加内容至关重要。

Claude 识别语法错误并使用 str_replace 命令修复它:

{
  "id": "msg_01VwXyZAbCdEfGhIjKlMnO",
  "model": "claude-opus-4-7",
  "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):"
      }
    }
  ]
}

然后你的应用程序应执行编辑并返回结果:

ant messages create <<'YAML'
model: claude-opus-4-7
max_tokens: 1024
tools:
  - type: text_editor_20250728
    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.
YAML
response = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    tools=[{"type": "text_editor_20250728", "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.",
                }
            ],
        },
    ],
)

print(response)
const response = await client.messages.create({
  model: "claude-opus-4-7",
  max_tokens: 1024,
  tools: [
    {
      type: "text_editor_20250728",
      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."
        }
      ]
    }
  ]
});

console.log(response);
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.TextBlockParam;
import com.anthropic.models.messages.ToolResultBlockParam;
import com.anthropic.models.messages.ToolTextEditor20250728;
import com.anthropic.models.messages.ToolUseBlockParam;
import java.util.List;

public class TextEditorConversationExample {

  public static void main(String[] args) {
    AnthropicClient client = AnthropicOkHttpClient.fromEnv();

    MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_4_7)
      .maxTokens(1024)
      .addTool(ToolTextEditor20250728.builder().build())
      // Previous messages would go here
      .addAssistantMessageOfBlockParams(
        List.of(
          ContentBlockParam.ofText(
            TextBlockParam.builder()
              .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."
              )
              .build()
          ),
          ContentBlockParam.ofToolUse(
            ToolUseBlockParam.builder()
              .id("toolu_01PqRsTuVwXyZAbCdEfGh")
              .name("str_replace_based_edit_tool")
              .input(
                ToolUseBlockParam.Input.builder()
                  .putAdditionalProperty("command", JsonValue.from("str_replace"))
                  .putAdditionalProperty("path", JsonValue.from("primes.py"))
                  .putAdditionalProperty(
                    "old_str",
                    JsonValue.from("    for num in range(2, limit + 1)")
                  )
                  .putAdditionalProperty(
                    "new_str",
                    JsonValue.from("    for num in range(2, limit + 1):")
                  )
                  .build()
              )
              .build()
          )
        )
      )
      .addUserMessageOfBlockParams(
        List.of(
          ContentBlockParam.ofToolResult(
            ToolResultBlockParam.builder()
              .toolUseId("toolu_01PqRsTuVwXyZAbCdEfGh")
              .content("Successfully replaced text at exactly one location.")
              .build()
          )
        )
      )
      .build();

    Message message = client.messages().create(params);
    System.out.println(message);
  }
}

最后,Claude 提供关于修复的完整解释:

{
  "id": "msg_01IjKlMnOpQrStUvWxYzAb",
  "model": "claude-opus-4-7",
  "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."
    }
  ]
}

实现 text editor tool

text editor tool 作为无 schema 工具实现。使用此工具时,你不需要像其他工具那样提供输入 schema;schema 内置在 Claude 的模型中且无法修改。

对于 Claude 4 模型,工具类型为 type: "text_editor_20250728"

  1. 初始化编辑器实现

    创建辅助函数来处理文件操作,如读取、写入和修改文件。考虑实现备份功能以便从错误中恢复。

  2. 处理编辑器工具调用

    创建一个根据命令类型处理来自 Claude 的工具调用的函数:

    def handle_editor_tool(tool_call):
        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
    
  3. 实现安全措施

    添加验证和安全检查:

    • 验证文件路径以防止目录遍历
    • 在进行更改前创建备份
    • 优雅地处理错误
    • 实现权限检查
  4. 处理 Claude 的响应

    从 Claude 的响应中提取和处理工具调用:

    from types import SimpleNamespace as _SN
    
    response = _SN(
        content=[
            _SN(
                type="tool_use", name="str_replace_based_edit_tool", input={}, id="toolu_01"
            )
        ]
    )
    
    
    def handle_editor_tool(tc):
        return "ok"
    
    
    # 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,
            }
    
Warning

实现 text editor tool 时,请注意:

  1. 安全性: 该工具可以访问你的本地文件系统,因此请实施适当的安全措施。
  2. 备份: 在允许编辑重要文件之前,始终创建备份。
  3. 验证: 验证所有输入以防止意外更改。
  4. 唯一匹配: 确保替换只匹配一个位置以避免意外编辑。

处理错误

使用 text editor tool 时,可能会发生各种错误。以下是处理建议:

文件未找到

如果 Claude 尝试查看或修改不存在的文件,在 tool_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
    }
  ]
}

遵循实现最佳实践

提供清晰的上下文

要求 Claude 修复或修改代码时,请具体说明需要检查哪些文件或需要解决哪些问题。清晰的上下文帮助 Claude 识别正确的文件并做出适当的更改。

不太有用的提示:"你能修复我的代码吗?"

更好的提示:"我的 primes.py 文件中有一个语法错误导致它无法运行。你能修复它吗?"

明确指定文件路径

需要时请清楚地指定文件路径,特别是在处理多个文件或不同目录中的文件时。

不太有用的提示:"检查我的辅助文件"

更好的提示:"你能检查我的 utils/helpers.py 文件是否有性能问题吗?"

编辑前创建备份

在你的应用程序中实现备份系统,在允许 Claude 编辑文件之前创建文件副本,特别是对于重要或生产代码。

import os


def backup_file(file_path):
    """Create a backup of a file before editing."""
    backup_path = f"\{file_path\}.backup"
    if os.path.exists(file_path):
        with open(file_path, "r") as src, open(backup_path, "w") as dst:
            dst.write(src.read())

谨慎处理唯一文本替换

str_replace 命令要求被替换的文本精确匹配。你的应用程序应确保旧文本恰好有一个匹配项,或提供适当的错误消息。

def safe_replace(file_path, old_text, new_text):
    """Replace text only if there's exactly one match."""
    with open(file_path, "r") as f:
        content = f.read()

    count = content.count(old_text)
    if count == 0:
        return "Error: No match found"
    elif count > 1:
        return f"Error: Found \{count\} matches"
    else:
        new_content = content.replace(old_text, new_text)
        with open(file_path, "w") as f:
            f.write(new_content)
        return "Successfully replaced text"

验证更改

Claude 修改文件后,通过运行测试或检查代码是否仍然按预期工作来验证更改。

def verify_changes(file_path):
    """Run tests or checks after making changes."""
    try:
        # For Python files, check for syntax errors
        if file_path.endswith(".py"):
            import ast

            with open(file_path, "r") as f:
                ast.parse(f.read())
            return "Syntax check passed"
    except Exception as e:
        return f"Verification failed: {str(e)}"

定价和 token 用量

text editor tool 使用与 Claude 其他工具相同的定价结构。它根据你使用的 Claude 模型遵循标准的输入和输出 token 定价。

除了基础 token 外,text editor tool 还需要以下额外输入 token:

工具额外输入 token
text_editor_20250429(Claude 4.x)700 token

有关工具定价的更多详细信息,请参阅工具使用定价

将 text editor tool 与其他工具集成

text editor tool 可以与其他 Claude 工具一起使用。组合工具时,请确保:

  • 工具版本与你使用的模型匹配
  • 考虑请求中包含的所有工具的额外 token 用量

更新日志

日期版本更改
2025 年 7 月 28 日text_editor_20250728发布了更新的 text editor tool,修复了一些问题并添加了可选的 max_characters 参数。其他方面与 text_editor_20250429 相同。
2025 年 4 月 29 日text_editor_20250429为 Claude 4 发布 text editor tool。此版本移除了 undo_edit 命令,但保留了所有其他功能。工具名称已更新以反映其基于 str_replace 的架构。
2025 年 3 月 13 日text_editor_20250124引入独立的 text editor tool 文档。此版本针对 Claude Sonnet 3.7 优化,但功能与之前版本相同。
2024 年 10 月 22 日text_editor_20241022随 Claude Sonnet 3.5 首次发布 text editor tool(已退役)。提供通过 viewcreatestr_replaceinsertundo_edit 命令查看、创建和编辑文件的能力。

下一步

以下是一些关于如何更方便、更强大地使用 text editor tool 的建议:

  • 集成到开发工作流中:将 text editor tool 构建到你的开发工具或 IDE 中
  • 创建代码审查系统:让 Claude 审查你的代码并提出改进
  • 构建调试助手:创建一个系统,让 Claude 帮助你诊断和修复代码中的问题
  • 实现文件格式转换:让 Claude 帮助你将文件从一种格式转换为另一种格式
  • 自动化文档:设置工作流让 Claude 自动为你的代码编写文档

text editor tool 使 Claude 能够直接操作你的代码库,支持从调试到自动化文档的各种工作流。