Was this page helpful?
此功能符合零数据保留(ZDR)的条件。当您的组织签订了 ZDR 协议时,通过此功能发送的数据在 API 响应返回后不会被存储。
Claude 可以使用 Anthropic 定义的文本编辑器工具来查看和修改文本文件,帮助您调试、修复和改进代码或其他文本文档。这使 Claude 能够直接与您的文件交互,提供实际操作的协助,而不仅仅是建议更改。
有关模型支持信息,请参阅工具参考。
以下是一些使用文本编辑器工具的示例场景:
通过 Messages API 向 Claude 提供文本编辑器工具(名为 str_replace_based_edit_tool)。
您可以选择性地指定 max_characters 参数,以控制查看大文件时的截断行为。
max_characters 仅与 text_editor_20250728 及更高版本的文本编辑器工具兼容。
文本编辑器工具可以按以下方式使用:
文本编辑器工具支持多个用于查看和修改文件的命令:
view 命令允许 Claude 检查文件内容或列出目录内容。它可以读取整个文件或特定范围的行。
参数:
command:必须为 "view"path:要查看的文件或目录的路径view_range(可选):一个包含两个整数的数组,指定要查看的起始和结束行号。行号从 1 开始计数,结束行号为 -1 表示读取到文件末尾。此参数仅在查看文件时适用,不适用于目录。str_replace 命令允许 Claude 将文件中的特定字符串替换为新字符串。这用于进行精确的编辑。
参数:
command:必须为 "str_replace"path:要修改的文件的路径old_str:要替换的文本(必须完全匹配,包括空白字符和缩进)new_str:用于替换旧文本的新文本create 命令允许 Claude 创建一个包含指定内容的新文件。
参数:
command:必须为 "create"path:新文件应创建的路径file_text:要写入新文件的内容insert 命令允许 Claude 在文件的特定位置插入文本。
参数:
command:必须为 "insert"path:要修改的文件的路径insert_line:在其后插入文本的行号(0 表示文件开头)insert_text:要插入的文本此示例演示 Claude 如何使用文本编辑器工具修复 Python 文件中的语法错误。
首先,您的应用程序向 Claude 提供文本编辑器工具和一个修复语法错误的提示:
Claude 首先使用文本编辑器工具查看文件:
{
"id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
"model": "claude-opus-4-8",
"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:
行号
在上面的示例中,view 工具结果包含在每行前添加了行号的文件内容(例如 "1: def is_prime(n):")。行号不是必需的,但对于成功使用 view_range 参数检查文件的特定部分以及使用 insert_line 参数在精确位置添加内容至关重要。
Claude 识别出语法错误并使用 str_replace 命令修复它:
{
"id": "msg_01VwXyZAbCdEfGhIjKlMnO",
"model": "claude-opus-4-8",
"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):"
}
}
]
}然后,您的应用程序应执行编辑并返回结果:
最后,Claude 提供对修复的完整解释:
{
"id": "msg_01IjKlMnOpQrStUvWxYzAb",
"model": "claude-opus-4-8",
"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."
}
]
}文本编辑器工具是作为无模式(schema-less)工具实现的。使用此工具时,您无需像其他工具那样提供输入模式;该模式已内置于 Claude 的模型中,无法修改。
对于 Claude 4 模型,工具类型为 type: "text_editor_20250728"。
在实现文本编辑器工具时,请注意以下事项:
使用文本编辑器工具时,可能会发生各种错误。以下是处理这些错误的指导:
文本编辑器工具采用与 Claude 使用的其他工具相同的定价结构。它遵循基于您所使用的 Claude 模型的标准输入和输出 "token"(令牌)定价。
除基础令牌外,文本编辑器工具还需要以下额外的输入令牌:
| 工具 | 额外输入令牌 |
|---|---|
text_editor_20250429(Claude 4.x) | 700 个令牌 |
有关工具定价的更多详细信息,请参阅工具使用定价。
文本编辑器工具可以与其他 Claude 工具一起使用。在组合工具时,请确保:
| 日期 | 版本 | 更改 |
|---|---|---|
| 2025 年 7 月 28 日 | text_editor_20250728 | 发布更新版文本编辑器工具,修复了一些问题并添加了可选的 max_characters 参数。其他方面与 text_editor_20250429 相同。 |
| 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(已停用)首次发布文本编辑器工具。通过 view、create、、 和 命令提供查看、创建和编辑文件的功能。 |
以下是一些以更便捷、更强大的方式使用文本编辑器工具的想法:
文本编辑器工具使 Claude 能够直接处理您的代码库,支持从调试到自动化文档编写的各种工作流程。
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
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)向 Claude 提供文本编辑器工具和用户提示
Claude 使用该工具检查文件或目录
view 命令检查文件内容或列出目录内容view 命令的 tool_use 内容块执行 view 命令并返回结果
max_characters 参数,则将文件内容截断至该长度tool_result 内容块的新 user 消息,将结果返回给 ClaudeClaude 使用该工具修改文件
str_replace 等命令进行更改,或使用 insert 在特定行号处添加文本。str_replace 命令,Claude 会构建一个格式正确的工具使用请求,其中包含旧文本和用于替换的新文本执行编辑并返回结果
Claude 提供分析和解释
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
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)response = client.messages.create(
model="claude-opus-4-8",
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)response = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
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)初始化您的编辑器实现
创建辅助函数来处理文件操作,如读取、写入和修改文件。考虑实现备份功能以便从错误中恢复。
处理编辑器工具调用
创建一个函数,根据命令类型处理来自 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":
# 读取并返回文件内容
pass
elif command == "str_replace":
# 替换文件中的文本
pass
elif command == "create":
# 创建新文件
pass
elif command == "insert":
# 在指定位置插入文本
pass实施安全措施
添加验证和安全检查:
处理 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,
}str_replaceinsertundo_edit