Công cụ Text Editor Tool của Claude API
Trust: ★★★☆☆ (0.90) · 0 validations · factual
Published: 2026-05-09 · Source: crawler_authoritative
Tình huống
Tài liệu kỹ thuật về Anthropic Claude API dành cho nhà phát triển muốn tích hợp công cụ chỉnh sửa file vào ứng dụng. Công cụ cho phép Claude tương tác trực tiếp với file code thay vì chỉ đề xuất thay đổi.
Insight
Text editor tool (str_replace_based_edit_tool) là công cụ schema-less cho phép Claude đọc, xem, tạo mới và chỉnh sửa file text/code. Công cụ hỗ trợ 4 lệnh chính: (1) view - xem nội dung file hoặc liệt kê thư mục, có thể chỉ định view_range để xem một phần (line numbers 1-indexed, -1 cho cuối file); (2) str_replace - thay thế chính xác một đoạn text bằng đoạn mới, yêu cầu old_str khớp hoàn toàn bao gồm whitespace và indentation; (3) create - tạo file mới với nội dung chỉ định; (4) insert - chèn text tại vị trí cụ thể với insert_line (0 cho đầu file). Tool type là text_editor_20250728 cho Claude 4 models. Tùy chọn max_characters kiểm soát truncation khi xem file lớn (chỉ tương thích với phiên bản text_editor_20250728 trở lên). Zero Data Retention (ZDR) available - dữ liệu không được lưu trữ sau khi API response được trả về. Token usage thêm 700 input tokens cho text_editor_20250429. Có thể kết hợp với các Claude tools khác nhưng cần đảm bảo khớp tool version với model.
Hành động
Quy trình 6 bước để implement: (1) Include text_editor_20250728 tool trong API request với name ‘str_replace_based_edit_tool’; (2) Gửi user prompt mô tả rõ vấn đề cần xử lý (ví dụ: ‘There’s a syntax error in my primes.py file’); (3) Khi Claude gửi tool_use với command ‘view’, đọc file và trả về nội dung qua tool_result content block; (4) Claude phân tích và gửi lệnh str_replace với old_str và new_str chính xác; (5) Thực hiện replacement trong file và trả kết quả; (6) Claude cung cấp giải thích hoàn chỉnh. Security measures: validate file paths chống directory traversal, tạo backup trước khi edit, kiểm tra permissions, đảm bảo old_str khớp đúng 1 location. Error handling: ‘Error: File not found’ (is_error: true), ‘Error: Found N matches - need more context’ khi multiple matches, ‘Error: No match found’ khi không khớp, ‘Error: Permission denied’ khi không có quyền ghi. Best practices: cung cấp context cụ thể và file paths rõ ràng, implement backup system, verify changes sau khi edit (syntax check cho .py files).
Điều kiện áp dụng
Dành cho developers tích hợp Claude AI vào IDE/development workflow, xây dựng code Reviews system, debugging assistant, hoặc automation cho documentation. Không áp dụng cho các nền tảng thương mại điện tử Shopee/TikTok/Lazada.
Nội dung gốc (Original)
Text editor tool
Claude can use an Anthropic-schema text editor tool to view and modify text files, helping you debug, fix, and improve your code or other text documents. This allows Claude to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
For model support, see the Tool reference.
When to use the text editor tool
Some examples of when to use the text editor tool are:
- Code debugging: Have Claude identify and fix bugs in your code, from syntax errors to logic issues.
- Code refactoring: Let Claude improve your code structure, readability, and performance through targeted edits.
- Documentation generation: Ask Claude to add docstrings, comments, or README files to your codebase.
- Test creation: Have Claude create unit tests for your code based on its understanding of the implementation.
Use the text editor tool
Provide the text editor tool (named str_replace_based_edit_tool) to Claude using the Messages API.
You can optionally specify a max_characters parameter to control truncation when viewing large files.
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);
}The text editor tool can be used in the following way:
Text editor tool commands
The text editor tool supports several commands for viewing and modifying files:
view
The view command allows Claude to examine the contents of a file or list the contents of a directory. It can read the entire file or a specific range of lines.
Parameters:
command: Must be “view”path: The path to the file or directory to viewview_range(optional): An array of two integers specifying the start and end line numbers to view. Line numbers are 1-indexed, and -1 for the end line means read to the end of the file. This parameter only applies when viewing files, not directories.
Example for viewing a file:
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "view",
"path": "primes.py"
}
}Example for viewing a directory:
{
"type": "tool_use",
"id": "toolu_02B19r91rw91mr917835mr9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "view",
"path": "src/"
}
}str_replace
The str_replace command allows Claude to replace a specific string in a file with a new string. This is used for making precise edits.
Parameters:
command: Must be “str_replace”path: The path to the file to modifyold_str: The text to replace (must match exactly, including whitespace and indentation)new_str: The new text to insert in place of the old text
{
"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
The create command allows Claude to create a new file with specified content.
Parameters:
command: Must be “create”path: The path where the new file should be createdfile_text: The content to write to the new file
{
"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
The insert command allows Claude to insert text at a specific location in a file.
Parameters:
command: Must be “insert”path: The path to the file to modifyinsert_line: The line number after which to insert the text (0 for beginning of file)insert_text: The text to 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"
}
}Example: Fixing a syntax error with the text editor tool
This example demonstrates how Claude uses the text editor tool to fix a syntax error in a Python file.
First, your application provides Claude with the text editor tool and a prompt to fix a syntax error:
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 uses the text editor tool first to view the file:
{
"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"
}
}
]
}Your application should then read the file and return its contents to Claude:
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()
YAMLresponse = 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);
}
}In the example above, the view tool result includes file contents with line numbers prepended to each line (e.g., “1: def is_prime(n):”). Line numbers are not required, but they are essential for successfully using the view_range parameter to examine specific sections of files and the insert_line parameter to add content at precise locations.
Claude identifies the syntax error and uses the str_replace command to fix it:
{
"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):"
}
}
]
}Your application should then make the edit and return the result:
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.
YAMLresponse = 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);
}
}Finally, Claude provides a complete explanation of the fix:
{
"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."
}
]
}Implement the text editor tool
The text editor tool is implemented as a schema-less tool. When using this tool, you don’t need to provide an input schema as with other tools; the schema is built into Claude’s model and can’t be modified.
The tool type is type: "text_editor_20250728" for Claude 4 models.
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
```
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,
}
```
- Security: The tool has access to your local filesystem, so implement proper security measures.
- Backup: Always create backups before allowing edits to important files.
- Validation: Validate all inputs to prevent unintended changes.
- Unique matching: Make sure replacements match exactly one location to avoid unintended edits.
Handle errors
When using the text editor tool, various errors may occur. Here is guidance on how to handle them:
If Claude tries to view or modify a file that doesn’t exist, return an appropriate error message in the tool_result:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "Error: File not found",
"is_error": true
}
]
}If Claude’s str_replace command matches multiple locations in the file, return an appropriate error message:
{
"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
}
]
}If Claude’s str_replace command doesn’t match any text in the file, return an appropriate error message:
{
"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
}
]
}If there are permission issues with creating, reading, or modifying files, return an appropriate error message:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "Error: Permission denied. Cannot write to file.",
"is_error": true
}
]
}Follow implementation best practices
When asking Claude to fix or modify code, be specific about what files need to be examined or what issues need to be addressed. Clear context helps Claude identify the right files and make appropriate changes.
Less helpful prompt: “Can you fix my code?”
Better prompt: “There’s a syntax error in my primes.py file that prevents it from running. Can you fix it?”
Specify file paths clearly when needed, especially if you’re working with multiple files or files in different directories.
Less helpful prompt: “Review my helper file”
Better prompt: “Can you check my utils/helpers.py file for any performance issues?”
Implement a backup system in your application that creates copies of files before allowing Claude to edit them, especially for important or production code.
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())The str_replace command requires an exact match for the text to be replaced. Your application should ensure that there is exactly one match for the old text or provide appropriate error messages.
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"After Claude makes changes to a file, verify the changes by running tests or checking that the code still works as expected.
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)}"Pricing and token usage
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:
| Tool | Additional input tokens |
|---|---|
text_editor_20250429 (Claude 4.x) | 700 tokens |
text_editor_20250124 (Claude Sonnet 3.7 (deprecated)) | 700 tokens |
For more detailed information about tool pricing, see Tool use pricing.
Integrate the text editor tool with other tools
The text editor tool can be used alongside other Claude tools. When combining tools, ensure you:
- Match the tool version with the model you’re using
- Account for the additional token usage for all tools included in your request
Change log
| Date | Version | Changes |
|---|---|---|
| July 28, 2025 | text_editor_20250728 | Release of an updated text editor Tool that fixes some issues and adds an optional max_characters parameter. It is otherwise identical to text_editor_20250429. |
| April 29, 2025 | text_editor_20250429 | Release of the text editor Tool for Claude 4. This version removes the undo_edit command but maintains all other capabilities. The tool name has been updated to reflect its str_replace-based architecture. |
| March 13, 2025 | text_editor_20250124 | Introduction of standalone text editor Tool documentation. This version is optimized for Claude Sonnet 3.7 but has identical capabilities to the previous version. |
| October 22, 2024 | text_editor_20241022 | Initial release of the text editor Tool with Claude Sonnet 3.5 (retired). Provides capabilities for viewing, creating, and editing files through the view, create, str_replace, insert, and undo_edit commands. |
Next steps
Here are some ideas for how to use the text editor tool in more convenient and powerful ways:
- Integrate with your development workflow: Build the text editor tool into your development tools or IDE
- Create a code review system: Have Claude review your code and make improvements
- Build a debugging assistant: Create a system where Claude can help you diagnose and fix issues in your code
- Implement file format conversion: Let Claude help you convert files from one format to another
- Automate documentation: Set up workflows for Claude to automatically document your code
The text editor tool enables Claude to work directly with your codebase, supporting workflows from debugging to automated documentation.
<Card title=“Bash tool” icon=“terminal” href=“/docs/en/agents-and-tools/tool-use/bash-tool”
Execute shell commands with Claude.
Liên kết
- Nền tảng: Anthropic
- Nguồn: https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool.md
Xem thêm:
- Tham số Effort trong Claude API - Kiểm soát mức độ chi tiết phản hồi
- Memory Tool - Lưu trữ và truy xuất thông tin xuyên phiên cho Claude
- Message Batches API - Xử lý hàng loạt yêu cầu API với chi phí giảm 50%
- Strict Tool Use - Đảm Bảo Tuân Thủ JSON Schema Cho Tool Inputs Trong Claude API
- Hướng dẫn tích hợp Claude trên Amazon Bedrock (legacy)