Repository Public
1---2title: Text editor tool3url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool4description: Give Claude the Anthropic-defined text editor tool to view, create, and edit files, and handle its view, str_replace, create, and insert commands.5---67<Note>8 To learn how zero data retention (ZDR) applies to this feature, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).9</Note>1011Claude 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.1213For model support, see the [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference).1415## When to use the text editor tool1617Some examples of when to use the text editor tool are:1819* **Code debugging:** Have Claude identify and fix bugs in your code, from syntax errors to logic issues.20* **Code refactoring:** Let Claude improve your code structure, readability, and performance through targeted edits.21* **Documentation generation:** Ask Claude to add docstrings, comments, or README files to your code base.22* **Test creation:** Have Claude create unit tests for your code based on its analysis of the implementation.2324## Use the text editor tool2526Provide the text editor tool (named `str_replace_based_edit_tool`) to Claude using the Messages API.2728You can optionally specify a `max_characters` parameter to control truncation when viewing large files.2930<Note>31 `max_characters` is only compatible with `text_editor_20250728` and later versions of the text editor tool.32</Note>3334<CodeGroup>35 ```bash cURL36 curl https://api.anthropic.com/v1/messages \37 -H "content-type: application/json" \38 -H "x-api-key: $ANTHROPIC_API_KEY" \39 -H "anthropic-version: 2023-06-01" \40 -d '{41 "model": "claude-opus-5",42 "max_tokens": 1024,43 "tools": [44 {45 "type": "text_editor_20250728",46 "name": "str_replace_based_edit_tool",47 "max_characters": 1000048 }49 ],50 "messages": [51 {52 "role": "user",53 "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"54 }55 ]56 }'57 ```5859 ```bash CLI60 ant messages create \61 --model claude-opus-5 \62 --max-tokens 1024 \63 --tool '{type: text_editor_20250728, name: str_replace_based_edit_tool, max_characters: 10000}' \64 --message '{role: user, content: There is a syntax error in my primes.py file. Can you help me fix it?}'65 ```6667 ```python Python68 client = anthropic.Anthropic()6970 response = client.messages.create(71 model="claude-opus-5",72 max_tokens=1024,73 tools=[74 {75 "type": "text_editor_20250728",76 "name": "str_replace_based_edit_tool",77 "max_characters": 10000,78 }79 ],80 messages=[81 {82 "role": "user",83 "content": "There's a syntax error in my primes.py file. Can you help me fix it?",84 }85 ],86 )8788 print(response)89 ```9091 ```typescript TypeScript92 const anthropic = new Anthropic();9394 const response = await anthropic.messages.create({95 model: "claude-opus-5",96 max_tokens: 1024,97 tools: [98 {99 type: "text_editor_20250728",100 name: "str_replace_based_edit_tool",101 max_characters: 10000102 }103 ],104 messages: [105 {106 role: "user",107 content: "There's a syntax error in my primes.py file. Can you help me fix it?"108 }109 ]110 });111112 console.log(response);113 ```114115 ```csharp C#116 var client = new AnthropicClient();117118 var response = await client.Messages.Create(119 new()120 {121 Model = Model.ClaudeOpus5,122 MaxTokens = 1024,123 Tools = [new ToolTextEditor20250728 { MaxCharacters = 10000 }],124 Messages =125 [126 new()127 {128 Role = Role.User,129 Content = "There's a syntax error in my primes.py file. Can you help me fix it?",130 },131 ],132 }133 );134135 Console.WriteLine(response);136 ```137138 ```go Go139 client := anthropic.NewClient()140141 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{142 Model: anthropic.ModelClaudeOpus5,143 MaxTokens: 1024,144 Tools: []anthropic.ToolUnionParam{145 {OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{146 MaxCharacters: anthropic.Int(10000),147 }},148 },149 Messages: []anthropic.MessageParam{150 anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),151 },152 })153 if err != nil {154 log.Fatal(err)155 }156 fmt.Println(response)157 ```158159 ```java Java160 import com.anthropic.models.messages.ToolTextEditor20250728;161 // ...162 void main() {163 AnthropicClient client = AnthropicOkHttpClient.fromEnv();164165 ToolTextEditor20250728 editorTool =166 ToolTextEditor20250728.builder()167 .maxCharacters(10000L)168 .build();169170 MessageCreateParams params = MessageCreateParams.builder()171 .model(Model.CLAUDE_OPUS_5)172 .maxTokens(1024)173 .addTool(editorTool)174 .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")175 .build();176177 Message message = client.messages().create(params);178 IO.println(message);179 }180 ```181182 ```php PHP183 $client = new Client();184185 $response = $client->messages->create(186 model: 'claude-opus-5',187 maxTokens: 1024,188 tools: [ToolTextEditor20250728::with(maxCharacters: 10000)],189 messages: [190 [191 'role' => 'user',192 'content' => "There's a syntax error in my primes.py file. Can you help me fix it?",193 ],194 ],195 );196197 echo $response;198 ```199200 ```ruby Ruby201 client = Anthropic::Client.new202203 response = client.messages.create(204 model: "claude-opus-5",205 max_tokens: 1024,206 tools: [207 {208 type: "text_editor_20250728",209 name: "str_replace_based_edit_tool",210 max_characters: 10000211 }212 ],213 messages: [214 {215 role: "user",216 content: "There's a syntax error in my primes.py file. Can you help me fix it?"217 }218 ]219 )220221 puts response222 ```223</CodeGroup>224225Use the text editor tool in the following way:226227<Steps>228 <Step title="Provide Claude with the text editor tool and a user prompt">229 * Include the text editor tool in your API request230 * Provide a user prompt that may require examining or modifying files, such as "Can you fix the syntax error in my code?"231 </Step>232233 <Step title="Claude uses the tool to examine files or directories">234 * Claude assesses what it needs to look at and uses the `view` command to examine file contents or list directory contents235 * The API response will contain a `tool_use` content block with the `view` command236 </Step>237238 <Step title="Execute the view command and return results">239 * Extract the file or directory path from Claude's tool use request240 * Read the file's contents or list the directory contents241 * If a `max_characters` parameter was specified in the tool configuration, truncate the file contents to that length242 * Return the results to Claude by continuing the conversation with a new `user` message containing a `tool_result` content block243 </Step>244245 <Step title="Claude uses the tool to modify files">246 * After examining the file or directory, Claude may use a command such as `str_replace` to make changes or `insert` to add text at a specific line number.247 * If Claude uses the `str_replace` command, Claude constructs a properly formatted tool use request with the old text and new text to replace it with248 </Step>249250 <Step title="Execute the edit and return results">251 * Extract the file path, old text, and new text from Claude's tool use request252 * Perform the text replacement in the file253 * Return the results to Claude254 </Step>255256 <Step title="Claude provides its analysis and explanation">257 * After examining and possibly editing the files, Claude provides a complete explanation of what it found and what changes it made258 </Step>259</Steps>260261### Text editor tool commands262263The text editor tool supports several commands for viewing and modifying files:264265#### view266267The `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.268269Parameters:270271* `command`: Must be "view"272* `path`: The path to the file or directory to view273* `view_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.274275<Accordion title="Example view commands">276 Example for viewing a file:277278 ```json279 {280 "type": "tool_use",281 "id": "toolu_01A09q90qw90lq917835lq9",282 "name": "str_replace_based_edit_tool",283 "input": {284 "command": "view",285 "path": "primes.py"286 }287 }288 ```289290 Example for viewing a directory:291292 ```json293 {294 "type": "tool_use",295 "id": "toolu_02B19r91rw91mr917835mr9",296 "name": "str_replace_based_edit_tool",297 "input": {298 "command": "view",299 "path": "src/"300 }301 }302 ```303</Accordion>304305#### str\_replace306307The `str_replace` command allows Claude to replace a specific string in a file with a new string. This is used for making precise edits.308309Parameters:310311* `command`: Must be "str\_replace"312* `path`: The path to the file to modify313* `old_str`: The text to replace (must match exactly, including whitespace and indentation)314* `new_str`: The new text to insert in place of the old text315316<Accordion title="Example str_replace command">317 ```json318 {319 "type": "tool_use",320 "id": "toolu_01A09q90qw90lq917835lq9",321 "name": "str_replace_based_edit_tool",322 "input": {323 "command": "str_replace",324 "path": "primes.py",325 "old_str": "for num in range(2, limit + 1)",326 "new_str": "for num in range(2, limit + 1):"327 }328 }329 ```330</Accordion>331332#### create333334The `create` command allows Claude to create a new file with specified content.335336Parameters:337338* `command`: Must be "create"339* `path`: The path where the new file should be created340* `file_text`: The content to write to the new file341342<Accordion title="Example create command">343 ```json344 {345 "type": "tool_use",346 "id": "toolu_01A09q90qw90lq917835lq9",347 "name": "str_replace_based_edit_tool",348 "input": {349 "command": "create",350 "path": "test_primes.py",351 "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()"352 }353 }354 ```355</Accordion>356357#### insert358359The `insert` command allows Claude to insert text at a specific location in a file.360361Parameters:362363* `command`: Must be "insert"364* `path`: The path to the file to modify365* `insert_line`: The line number after which to insert the text (0 for beginning of file)366* `insert_text`: The text to insert367368<Accordion title="Example insert command">369 ```json370 {371 "type": "tool_use",372 "id": "toolu_01A09q90qw90lq917835lq9",373 "name": "str_replace_based_edit_tool",374 "input": {375 "command": "insert",376 "path": "primes.py",377 "insert_line": 0,378 "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"379 }380 }381 ```382</Accordion>383384### Example: Fixing a syntax error with the text editor tool385386This example demonstrates how Claude uses the text editor tool to fix a syntax error in a Python file.387388First, your application provides Claude with the text editor tool and a prompt to fix a syntax error:389390<CodeGroup>391 ```bash cURL392 curl https://api.anthropic.com/v1/messages \393 -H "content-type: application/json" \394 -H "x-api-key: $ANTHROPIC_API_KEY" \395 -H "anthropic-version: 2023-06-01" \396 -d '{397 "model": "claude-opus-5",398 "max_tokens": 1024,399 "tools": [400 {401 "type": "text_editor_20250728",402 "name": "str_replace_based_edit_tool"403 }404 ],405 "messages": [406 {407 "role": "user",408 "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"409 }410 ]411 }'412 ```413414 ```bash CLI415 ant messages create \416 --model claude-opus-5 \417 --max-tokens 1024 \418 --tool '{type: text_editor_20250728, name: str_replace_based_edit_tool}' \419 --message '{role: user, content: There is a syntax error in my primes.py file. Can you help me fix it?}'420 ```421422 ```python Python423 client = anthropic.Anthropic()424425 response = client.messages.create(426 model="claude-opus-5",427 max_tokens=1024,428 tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],429 messages=[430 {431 "role": "user",432 "content": "There's a syntax error in my primes.py file. Can you help me fix it?",433 }434 ],435 )436437 print(response)438 ```439440 ```typescript TypeScript441 const anthropic = new Anthropic();442443 const response = await anthropic.messages.create({444 model: "claude-opus-5",445 max_tokens: 1024,446 tools: [447 {448 type: "text_editor_20250728",449 name: "str_replace_based_edit_tool"450 }451 ],452 messages: [453 {454 role: "user",455 content: "There's a syntax error in my primes.py file. Can you help me fix it?"456 }457 ]458 });459460 console.log(response);461 ```462463 ```csharp C#464 var client = new AnthropicClient();465466 var response = await client.Messages.Create(467 new()468 {469 Model = Model.ClaudeOpus5,470 MaxTokens = 1024,471 Tools = [new ToolTextEditor20250728()],472 Messages =473 [474 new()475 {476 Role = Role.User,477 Content = "There's a syntax error in my primes.py file. Can you help me fix it?",478 },479 ],480 }481 );482483 Console.WriteLine(response);484 ```485486 ```go Go487 client := anthropic.NewClient()488489 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{490 Model: anthropic.ModelClaudeOpus5,491 MaxTokens: 1024,492 Tools: []anthropic.ToolUnionParam{493 {OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},494 },495 Messages: []anthropic.MessageParam{496 anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),497 },498 })499 if err != nil {500 log.Fatal(err)501 }502 fmt.Println(response)503 ```504505 ```java Java506 import com.anthropic.models.messages.ToolTextEditor20250728;507 // ...508 void main() {509 AnthropicClient client = AnthropicOkHttpClient.fromEnv();510511 ToolTextEditor20250728 editorTool =512 ToolTextEditor20250728.builder().build();513514 MessageCreateParams params = MessageCreateParams.builder()515 .model(Model.CLAUDE_OPUS_5)516 .maxTokens(1024)517 .addTool(editorTool)518 .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")519 .build();520521 Message message = client.messages().create(params);522 IO.println(message);523 }524 ```525526 ```php PHP527 $client = new Client();528529 $response = $client->messages->create(530 model: 'claude-opus-5',531 maxTokens: 1024,532 tools: [new ToolTextEditor20250728()],533 messages: [534 [535 'role' => 'user',536 'content' => "There's a syntax error in my primes.py file. Can you help me fix it?",537 ],538 ],539 );540541 echo $response;542 ```543544 ```ruby Ruby545 client = Anthropic::Client.new546547 response = client.messages.create(548 model: "claude-opus-5",549 max_tokens: 1024,550 tools: [{type: "text_editor_20250728", name: "str_replace_based_edit_tool"}],551 messages: [552 {553 role: "user",554 content: "There's a syntax error in my primes.py file. Can you help me fix it?"555 }556 ]557 )558559 puts response560 ```561</CodeGroup>562563Claude uses the text editor tool first to view the file:564565```json Output566{567 "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",568 "model": "claude-opus-5",569 "stop_reason": "tool_use",570 "role": "assistant",571 "content": [572 {573 "type": "text",574 "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."575 },576 {577 "type": "tool_use",578 "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",579 "name": "str_replace_based_edit_tool",580 "input": {581 "command": "view",582 "path": "primes.py"583 }584 }585 ]586}587```588589Your application should then read the file and return its contents to Claude:590591<CodeGroup>592 ```bash cURL593 curl https://api.anthropic.com/v1/messages \594 -H "content-type: application/json" \595 -H "x-api-key: $ANTHROPIC_API_KEY" \596 -H "anthropic-version: 2023-06-01" \597 -d '{598 "model": "claude-opus-5",599 "max_tokens": 1024,600 "tools": [601 {602 "type": "text_editor_20250728",603 "name": "str_replace_based_edit_tool"604 }605 ],606 "messages": [607 {608 "role": "user",609 "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"610 },611 {612 "role": "assistant",613 "content": [614 {615 "type": "text",616 "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."617 },618 {619 "type": "tool_use",620 "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",621 "name": "str_replace_based_edit_tool",622 "input": {623 "command": "view",624 "path": "primes.py"625 }626 }627 ]628 },629 {630 "role": "user",631 "content": [632 {633 "type": "tool_result",634 "tool_use_id": "toolu_01AbCdEfGhIjKlMnOpQrStU",635 "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()"636 }637 ]638 }639 ]640 }'641 ```642643 ```bash CLI644 ant messages create <<'YAML'645 model: claude-opus-5646 max_tokens: 1024647 tools:648 - type: text_editor_20250728649 name: str_replace_based_edit_tool650 messages:651 - role: user652 content: There's a syntax error in my primes.py file. Can you help me fix it?653 - role: assistant654 content:655 - type: text656 text: >-657 I'll help you fix the syntax error in your primes.py file. First,658 let me take a look at the file to identify the issue.659 - type: tool_use660 id: toolu_01AbCdEfGhIjKlMnOpQrStU661 name: str_replace_based_edit_tool662 input:663 command: view664 path: primes.py665 - role: user666 content:667 - type: tool_result668 tool_use_id: toolu_01AbCdEfGhIjKlMnOpQrStU669 content: |-670 1: def is_prime(n):671 2: """Check if a number is prime."""672 3: if n <= 1:673 4: return False674 5: if n <= 3:675 6: return True676 7: if n % 2 == 0 or n % 3 == 0:677 8: return False678 9: i = 5679 10: while i * i <= n:680 11: if n % i == 0 or n % (i + 2) == 0:681 12: return False682 13: i += 6683 14: return True684 15:685 16: def get_primes(limit):686 17: """Generate a list of prime numbers up to the given limit."""687 18: primes = []688 19: for num in range(2, limit + 1)689 20: if is_prime(num):690 21: primes.append(num)691 22: return primes692 23:693 24: def main():694 25: """Main function to demonstrate prime number generation."""695 26: limit = 100696 27: prime_list = get_primes(limit)697 28: print(f"Prime numbers up to {limit}:")698 29: print(prime_list)699 30: print(f"Found {len(prime_list)} prime numbers.")700 31:701 32: if __name__ == "__main__":702 33: main()703 YAML704 ```705706 ```python Python707 response = client.messages.create(708 model="claude-opus-5",709 max_tokens=1024,710 tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],711 messages=[712 {713 "role": "user",714 "content": "There's a syntax error in my primes.py file. Can you help me fix it?",715 },716 {717 "role": "assistant",718 "content": [719 {720 "type": "text",721 "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.",722 },723 {724 "type": "tool_use",725 "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",726 "name": "str_replace_based_edit_tool",727 "input": {"command": "view", "path": "primes.py"},728 },729 ],730 },731 {732 "role": "user",733 "content": [734 {735 "type": "tool_result",736 "tool_use_id": "toolu_01AbCdEfGhIjKlMnOpQrStU",737 "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()',738 }739 ],740 },741 ],742 )743744 print(response)745 ```746747 ```typescript TypeScript748 const anthropic = new Anthropic();749750 const response = await anthropic.messages.create({751 model: "claude-opus-5",752 max_tokens: 1024,753 tools: [754 {755 type: "text_editor_20250728",756 name: "str_replace_based_edit_tool"757 }758 ],759 messages: [760 {761 role: "user",762 content: "There's a syntax error in my primes.py file. Can you help me fix it?"763 },764 {765 role: "assistant",766 content: [767 {768 type: "text",769 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."770 },771 {772 type: "tool_use",773 id: "toolu_01AbCdEfGhIjKlMnOpQrStU",774 name: "str_replace_based_edit_tool",775 input: {776 command: "view",777 path: "primes.py"778 }779 }780 ]781 },782 {783 role: "user",784 content: [785 {786 type: "tool_result",787 tool_use_id: "toolu_01AbCdEfGhIjKlMnOpQrStU",788 content:789 '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()'790 }791 ]792 }793 ]794 });795796 console.log(response);797 ```798799 ```csharp C#800 var client = new AnthropicClient();801802 var response = await client.Messages.Create(803 new()804 {805 Model = Model.ClaudeOpus5,806 MaxTokens = 1024,807 Tools = [new ToolTextEditor20250728()],808 Messages =809 [810 new()811 {812 Role = Role.User,813 Content = "There's a syntax error in my primes.py file. Can you help me fix it?",814 },815 new()816 {817 Role = Role.Assistant,818 Content = new MessageParamContent(new List<ContentBlockParam>819 {820 new ContentBlockParam(new TextBlockParam()821 {822 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.",823 }),824 new ContentBlockParam(new ToolUseBlockParam()825 {826 ID = "toolu_01AbCdEfGhIjKlMnOpQrStU",827 Name = "str_replace_based_edit_tool",828 Input = new Dictionary<string, JsonElement>829 {830 ["command"] = JsonSerializer.SerializeToElement("view"),831 ["path"] = JsonSerializer.SerializeToElement("primes.py"),832 },833 }),834 }),835 },836 new()837 {838 Role = Role.User,839 Content = new MessageParamContent(new List<ContentBlockParam>840 {841 new ContentBlockParam(new ToolResultBlockParam()842 {843 ToolUseID = "toolu_01AbCdEfGhIjKlMnOpQrStU",844 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()",845 }),846 }),847 },848 ],849 }850 );851852 Console.WriteLine(response);853 ```854855 ```go Go856 client := anthropic.NewClient()857858 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{859 Model: anthropic.ModelClaudeOpus5,860 MaxTokens: 1024,861 Tools: []anthropic.ToolUnionParam{862 {OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},863 },864 Messages: []anthropic.MessageParam{865 anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),866 anthropic.NewAssistantMessage(867 anthropic.NewTextBlock("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."),868 anthropic.NewToolUseBlock(869 "toolu_01AbCdEfGhIjKlMnOpQrStU",870 map[string]any{"command": "view", "path": "primes.py"},871 "str_replace_based_edit_tool",872 ),873 ),874 anthropic.NewUserMessage(875 anthropic.NewToolResultBlock(876 "toolu_01AbCdEfGhIjKlMnOpQrStU",877 "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()",878 false,879 ),880 ),881 },882 })883 if err != nil {884 log.Fatal(err)885 }886 fmt.Println(response)887 ```888889 ```java Java890 AnthropicClient client = AnthropicOkHttpClient.fromEnv();891892 MessageCreateParams params = MessageCreateParams.builder()893 .model(Model.CLAUDE_OPUS_5)894 .maxTokens(1024)895 .addTool(ToolTextEditor20250728.builder().build())896 .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")897 .addAssistantMessageOfBlockParams(898 List.of(899 ContentBlockParam.ofText(900 TextBlockParam.builder()901 .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.")902 .build()903 ),904 ContentBlockParam.ofToolUse(905 ToolUseBlockParam.builder()906 .id("toolu_01AbCdEfGhIjKlMnOpQrStU")907 .name("str_replace_based_edit_tool")908 .input(909 ToolUseBlockParam.Input.builder()910 .putAdditionalProperty("command", JsonValue.from("view"))911 .putAdditionalProperty("path", JsonValue.from("primes.py"))912 .build()913 )914 .build()915 )916 )917 )918 .addUserMessageOfBlockParams(919 List.of(920 ContentBlockParam.ofToolResult(921 ToolResultBlockParam.builder()922 .toolUseId("toolu_01AbCdEfGhIjKlMnOpQrStU")923 .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()")924 .build()925 )926 )927 )928 .build();929930 Message message = client.messages().create(params);931 System.out.println(message);932 ```933934 ```php PHP935 $client = new Client();936937 $response = $client->messages->create(938 model: 'claude-opus-5',939 maxTokens: 1024,940 tools: [new ToolTextEditor20250728()],941 messages: [942 [943 'role' => 'user',944 'content' => "There's a syntax error in my primes.py file. Can you help me fix it?",945 ],946 [947 'role' => 'assistant',948 'content' => [949 [950 'type' => 'text',951 '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.",952 ],953 [954 'type' => 'tool_use',955 'id' => 'toolu_01AbCdEfGhIjKlMnOpQrStU',956 'name' => 'str_replace_based_edit_tool',957 'input' => ['command' => 'view', 'path' => 'primes.py'],958 ],959 ],960 ],961 [962 'role' => 'user',963 'content' => [964 [965 'type' => 'tool_result',966 'tool_use_id' => 'toolu_01AbCdEfGhIjKlMnOpQrStU',967 '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()",968 ],969 ],970 ],971 ],972 );973974 echo $response;975 ```976977 ```ruby Ruby978 client = Anthropic::Client.new979980 response = client.messages.create(981 model: "claude-opus-5",982 max_tokens: 1024,983 tools: [{type: "text_editor_20250728", name: "str_replace_based_edit_tool"}],984 messages: [985 {986 role: "user",987 content: "There's a syntax error in my primes.py file. Can you help me fix it?"988 },989 {990 role: "assistant",991 content: [992 {993 type: "text",994 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."995 },996 {997 type: "tool_use",998 id: "toolu_01AbCdEfGhIjKlMnOpQrStU",999 name: "str_replace_based_edit_tool",1000 input: {command: "view", path: "primes.py"}1001 }1002 ]1003 },1004 {1005 role: "user",1006 content: [1007 {1008 type: "tool_result",1009 tool_use_id: "toolu_01AbCdEfGhIjKlMnOpQrStU",1010 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()"1011 }1012 ]1013 }1014 ]1015 )10161017 puts response1018 ```1019</CodeGroup>10201021<Tip>1022 **Line numbers**10231024 In the preceding example, the `view` tool result includes file contents with line numbers prepended to each line (for example, "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.1025</Tip>10261027Claude identifies the syntax error and uses the `str_replace` command to fix it:10281029```json Output1030{1031 "id": "msg_01VwXyZAbCdEfGhIjKlMnO",1032 "model": "claude-opus-5",1033 "stop_reason": "tool_use",1034 "role": "assistant",1035 "content": [1036 {1037 "type": "text",1038 "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."1039 },1040 {1041 "type": "tool_use",1042 "id": "toolu_01PqRsTuVwXyZAbCdEfGh",1043 "name": "str_replace_based_edit_tool",1044 "input": {1045 "command": "str_replace",1046 "path": "primes.py",1047 "old_str": " for num in range(2, limit + 1)",1048 "new_str": " for num in range(2, limit + 1):"1049 }1050 }1051 ]1052}1053```10541055Your application should then make the edit and return the result:10561057<CodeGroup>1058 ```bash cURL1059 curl https://api.anthropic.com/v1/messages \1060 -H "content-type: application/json" \1061 -H "x-api-key: $ANTHROPIC_API_KEY" \1062 -H "anthropic-version: 2023-06-01" \1063 -d '{1064 "model": "claude-opus-5",1065 "max_tokens": 1024,1066 "tools": [1067 {1068 "type": "text_editor_20250728",1069 "name": "str_replace_based_edit_tool"1070 }1071 ],1072 "messages": [1073 {1074 "role": "assistant",1075 "content": [1076 {1077 "type": "text",1078 "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."1079 },1080 {1081 "type": "tool_use",1082 "id": "toolu_01PqRsTuVwXyZAbCdEfGh",1083 "name": "str_replace_based_edit_tool",1084 "input": {1085 "command": "str_replace",1086 "path": "primes.py",1087 "old_str": " for num in range(2, limit + 1)",1088 "new_str": " for num in range(2, limit + 1):"1089 }1090 }1091 ]1092 },1093 {1094 "role": "user",1095 "content": [1096 {1097 "type": "tool_result",1098 "tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",1099 "content": "Successfully replaced text at exactly one location."1100 }1101 ]1102 }1103 ]1104 }'1105 ```11061107 ```bash CLI1108 ant messages create <<'YAML'1109 model: claude-opus-51110 max_tokens: 10241111 tools:1112 - type: text_editor_202507281113 name: str_replace_based_edit_tool1114 messages:1115 # Previous messages...1116 - role: assistant1117 content:1118 - type: text1119 text: >-1120 I found the syntax error in your primes.py file. In the `get_primes`1121 function, there is a missing colon (:) at the end of the for loop1122 line. Let me fix that for you.1123 - type: tool_use1124 id: toolu_01PqRsTuVwXyZAbCdEfGh1125 name: str_replace_based_edit_tool1126 input:1127 command: str_replace1128 path: primes.py1129 old_str: " for num in range(2, limit + 1)"1130 new_str: " for num in range(2, limit + 1):"1131 - role: user1132 content:1133 - type: tool_result1134 tool_use_id: toolu_01PqRsTuVwXyZAbCdEfGh1135 content: Successfully replaced text at exactly one location.1136 YAML1137 ```11381139 ```python Python1140 response = client.messages.create(1141 model="claude-opus-5",1142 max_tokens=1024,1143 tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],1144 messages=[1145 # Previous messages...1146 {1147 "role": "assistant",1148 "content": [1149 {1150 "type": "text",1151 "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.",1152 },1153 {1154 "type": "tool_use",1155 "id": "toolu_01PqRsTuVwXyZAbCdEfGh",1156 "name": "str_replace_based_edit_tool",1157 "input": {1158 "command": "str_replace",1159 "path": "primes.py",1160 "old_str": " for num in range(2, limit + 1)",1161 "new_str": " for num in range(2, limit + 1):",1162 },1163 },1164 ],1165 },1166 {1167 "role": "user",1168 "content": [1169 {1170 "type": "tool_result",1171 "tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",1172 "content": "Successfully replaced text at exactly one location.",1173 }1174 ],1175 },1176 ],1177 )11781179 print(response)1180 ```11811182 ```typescript TypeScript1183 const response = await client.messages.create({1184 model: "claude-opus-5",1185 max_tokens: 1024,1186 tools: [1187 {1188 type: "text_editor_20250728",1189 name: "str_replace_based_edit_tool"1190 }1191 ],1192 messages: [1193 // Previous messages...1194 {1195 role: "assistant",1196 content: [1197 {1198 type: "text",1199 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."1200 },1201 {1202 type: "tool_use",1203 id: "toolu_01PqRsTuVwXyZAbCdEfGh",1204 name: "str_replace_based_edit_tool",1205 input: {1206 command: "str_replace",1207 path: "primes.py",1208 old_str: " for num in range(2, limit + 1)",1209 new_str: " for num in range(2, limit + 1):"1210 }1211 }1212 ]1213 },1214 {1215 role: "user",1216 content: [1217 {1218 type: "tool_result",1219 tool_use_id: "toolu_01PqRsTuVwXyZAbCdEfGh",1220 content: "Successfully replaced text at exactly one location."1221 }1222 ]1223 }1224 ]1225 });12261227 console.log(response);1228 ```12291230 ```csharp C#1231 var client = new AnthropicClient();12321233 var response = await client.Messages.Create(1234 new()1235 {1236 Model = Model.ClaudeOpus5,1237 MaxTokens = 1024,1238 Tools = [new ToolTextEditor20250728()],1239 Messages =1240 [1241 // Previous messages...1242 new()1243 {1244 Role = Role.Assistant,1245 Content = new MessageParamContent(new List<ContentBlockParam>1246 {1247 new ContentBlockParam(new TextBlockParam()1248 {1249 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.",1250 }),1251 new ContentBlockParam(new ToolUseBlockParam()1252 {1253 ID = "toolu_01PqRsTuVwXyZAbCdEfGh",1254 Name = "str_replace_based_edit_tool",1255 Input = new Dictionary<string, JsonElement>1256 {1257 ["command"] = JsonSerializer.SerializeToElement("str_replace"),1258 ["path"] = JsonSerializer.SerializeToElement("primes.py"),1259 ["old_str"] = JsonSerializer.SerializeToElement(" for num in range(2, limit + 1)"),1260 ["new_str"] = JsonSerializer.SerializeToElement(" for num in range(2, limit + 1):"),1261 },1262 }),1263 }),1264 },1265 new()1266 {1267 Role = Role.User,1268 Content = new MessageParamContent(new List<ContentBlockParam>1269 {1270 new ContentBlockParam(new ToolResultBlockParam()1271 {1272 ToolUseID = "toolu_01PqRsTuVwXyZAbCdEfGh",1273 Content = "Successfully replaced text at exactly one location.",1274 }),1275 }),1276 },1277 ],1278 }1279 );12801281 Console.WriteLine(response);1282 ```12831284 ```go Go1285 client := anthropic.NewClient()12861287 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1288 Model: anthropic.ModelClaudeOpus5,1289 MaxTokens: 1024,1290 Tools: []anthropic.ToolUnionParam{1291 {OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},1292 },1293 Messages: []anthropic.MessageParam{1294 // Previous messages...1295 anthropic.NewAssistantMessage(1296 anthropic.NewTextBlock("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."),1297 anthropic.NewToolUseBlock(1298 "toolu_01PqRsTuVwXyZAbCdEfGh",1299 map[string]any{1300 "command": "str_replace",1301 "path": "primes.py",1302 "old_str": " for num in range(2, limit + 1)",1303 "new_str": " for num in range(2, limit + 1):",1304 },1305 "str_replace_based_edit_tool",1306 ),1307 ),1308 anthropic.NewUserMessage(1309 anthropic.NewToolResultBlock(1310 "toolu_01PqRsTuVwXyZAbCdEfGh",1311 "Successfully replaced text at exactly one location.",1312 false,1313 ),1314 ),1315 },1316 })1317 if err != nil {1318 log.Fatal(err)1319 }1320 fmt.Println(response)1321 ```13221323 ```java Java1324 AnthropicClient client = AnthropicOkHttpClient.fromEnv();13251326 MessageCreateParams params = MessageCreateParams.builder()1327 .model(Model.CLAUDE_OPUS_5)1328 .maxTokens(1024)1329 .addTool(ToolTextEditor20250728.builder().build())1330 // Previous messages would go here1331 .addAssistantMessageOfBlockParams(1332 List.of(1333 ContentBlockParam.ofText(1334 TextBlockParam.builder()1335 .text(1336 "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."1337 )1338 .build()1339 ),1340 ContentBlockParam.ofToolUse(1341 ToolUseBlockParam.builder()1342 .id("toolu_01PqRsTuVwXyZAbCdEfGh")1343 .name("str_replace_based_edit_tool")1344 .input(1345 ToolUseBlockParam.Input.builder()1346 .putAdditionalProperty("command", JsonValue.from("str_replace"))1347 .putAdditionalProperty("path", JsonValue.from("primes.py"))1348 .putAdditionalProperty(1349 "old_str",1350 JsonValue.from(" for num in range(2, limit + 1)")1351 )1352 .putAdditionalProperty(1353 "new_str",1354 JsonValue.from(" for num in range(2, limit + 1):")1355 )1356 .build()1357 )1358 .build()1359 )1360 )1361 )1362 .addUserMessageOfBlockParams(1363 List.of(1364 ContentBlockParam.ofToolResult(1365 ToolResultBlockParam.builder()1366 .toolUseId("toolu_01PqRsTuVwXyZAbCdEfGh")1367 .content("Successfully replaced text at exactly one location.")1368 .build()1369 )1370 )1371 )1372 .build();13731374 Message message = client.messages().create(params);1375 System.out.println(message);1376 ```13771378 ```php PHP1379 $client = new Client();13801381 $response = $client->messages->create(1382 model: 'claude-opus-5',1383 maxTokens: 1024,1384 tools: [new ToolTextEditor20250728()],1385 messages: [1386 // Previous messages...1387 [1388 'role' => 'assistant',1389 'content' => [1390 [1391 'type' => 'text',1392 '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.',1393 ],1394 [1395 'type' => 'tool_use',1396 'id' => 'toolu_01PqRsTuVwXyZAbCdEfGh',1397 'name' => 'str_replace_based_edit_tool',1398 'input' => [1399 'command' => 'str_replace',1400 'path' => 'primes.py',1401 'old_str' => ' for num in range(2, limit + 1)',1402 'new_str' => ' for num in range(2, limit + 1):',1403 ],1404 ],1405 ],1406 ],1407 [1408 'role' => 'user',1409 'content' => [1410 [1411 'type' => 'tool_result',1412 'tool_use_id' => 'toolu_01PqRsTuVwXyZAbCdEfGh',1413 'content' => 'Successfully replaced text at exactly one location.',1414 ],1415 ],1416 ],1417 ],1418 );14191420 echo $response;1421 ```14221423 ```ruby Ruby1424 client = Anthropic::Client.new14251426 response = client.messages.create(1427 model: "claude-opus-5",1428 max_tokens: 1024,1429 tools: [{type: "text_editor_20250728", name: "str_replace_based_edit_tool"}],1430 messages: [1431 # Previous messages...1432 {1433 role: "assistant",1434 content: [1435 {1436 type: "text",1437 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."1438 },1439 {1440 type: "tool_use",1441 id: "toolu_01PqRsTuVwXyZAbCdEfGh",1442 name: "str_replace_based_edit_tool",1443 input: {1444 command: "str_replace",1445 path: "primes.py",1446 old_str: " for num in range(2, limit + 1)",1447 new_str: " for num in range(2, limit + 1):"1448 }1449 }1450 ]1451 },1452 {1453 role: "user",1454 content: [1455 {1456 type: "tool_result",1457 tool_use_id: "toolu_01PqRsTuVwXyZAbCdEfGh",1458 content: "Successfully replaced text at exactly one location."1459 }1460 ]1461 }1462 ]1463 )14641465 puts response1466 ```1467</CodeGroup>14681469Finally, Claude provides a complete explanation of the fix:14701471````json Output1472{1473 "id": "msg_01IjKlMnOpQrStUvWxYzAb",1474 "model": "claude-opus-5",1475 "stop_reason": "end_turn",1476 "role": "assistant",1477 "content": [1478 {1479 "type": "text",1480 "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."1481 }1482 ]1483}1484````14851486## Implement the text editor tool14871488The 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.14891490The tool type is `type: "text_editor_20250728"` for Claude 4 and later models.14911492<Steps>1493 <Step title="Initialize your editor implementation">1494 Create helper functions to handle file operations like reading, writing, and modifying files. Consider implementing backup functionality to recover from mistakes.1495 </Step>14961497 <Step title="Handle editor tool calls">1498 Create a function that processes tool calls from Claude based on the command type:14991500 <CodeGroup exclude="shell">1501 ```python Python1502 def handle_editor_tool(tool_call):1503 input_params = tool_call.input1504 command = input_params.get("command", "")1505 file_path = input_params.get("path", "")15061507 match command:1508 case "view":1509 # Read and return file contents1510 pass1511 case "str_replace":1512 # Replace text in file1513 pass1514 case "create":1515 # Create new file1516 pass1517 case "insert":1518 # Insert text at location1519 pass1520 ```15211522 ```typescript TypeScript1523 function handleEditorTool(toolCall: { input: { command?: string; path?: string } }): void {1524 const inputParams = toolCall.input;1525 const command = inputParams.command ?? "";1526 const filePath = inputParams.path ?? "";15271528 switch (command) {1529 case "view":1530 // Read and return file contents1531 break;1532 case "str_replace":1533 // Replace text in file1534 break;1535 case "create":1536 // Create new file1537 break;1538 case "insert":1539 // Insert text at location1540 break;1541 }1542 }1543 ```15441545 ```csharp C#1546 static string HandleEditorTool(IReadOnlyDictionary<string, JsonElement> input)1547 {1548 input.TryGetValue("command", out var commandEl);1549 input.TryGetValue("path", out var pathEl);1550 var command = commandEl.ValueKind == JsonValueKind.String ? commandEl.GetString() : null;1551 var filePath = pathEl.ValueKind == JsonValueKind.String ? pathEl.GetString() : null;15521553 if (command == "view")1554 {1555 // Read and return file contents1556 }1557 else if (command == "str_replace")1558 {1559 // Replace text in file1560 }1561 else if (command == "create")1562 {1563 // Create new file1564 }1565 else if (command == "insert")1566 {1567 // Insert text at location1568 }1569 return "";1570 }1571 ```15721573 ```go Go1574 func handleEditorTool(input map[string]any) string {1575 command, _ := input["command"].(string)1576 filePath, _ := input["path"].(string)1577 // ...15781579 switch command {1580 case "view":1581 // Read and return file contents1582 case "str_replace":1583 // Replace text in file1584 case "create":1585 // Create new file1586 case "insert":1587 // Insert text at location1588 }1589 return ""1590 }1591 ```15921593 ```java Java1594 static void handleEditorTool(Map<String, Object> input) {1595 var command = (String) input.getOrDefault("command", "");1596 var filePath = (String) input.getOrDefault("path", "");15971598 if (command.equals("view")) {1599 // Read and return file contents1600 } else if (command.equals("str_replace")) {1601 // Replace text in file1602 } else if (command.equals("create")) {1603 // Create new file1604 } else if (command.equals("insert")) {1605 // Insert text at location1606 }1607 }1608 ```16091610 ```php PHP1611 function handle_editor_tool(array $input): string1612 {1613 $command = $input['command'] ?? '';1614 $filePath = $input['path'] ?? '';16151616 if ($command === 'view') {1617 // Read and return file contents1618 } elseif ($command === 'str_replace') {1619 // Replace text in file1620 } elseif ($command === 'create') {1621 // Create new file1622 } elseif ($command === 'insert') {1623 // Insert text at location1624 }1625 return '';1626 }1627 ```16281629 ```ruby Ruby1630 def handle_editor_tool(input)1631 command = input[:command] || ""1632 file_path = input[:path] || ""16331634 case command1635 when "view"1636 # Read and return file contents1637 when "str_replace"1638 # Replace text in file1639 when "create"1640 # Create new file1641 when "insert"1642 # Insert text at location1643 end1644 end1645 ```1646 </CodeGroup>1647 </Step>16481649 <Step title="Implement security measures">1650 Add validation and security checks:16511652 * Validate file paths to prevent directory traversal1653 * Create backups before making changes1654 * Handle errors gracefully1655 * Implement permissions checks1656 </Step>16571658 <Step title="Process Claude's responses">1659 Extract and handle tool calls from Claude's responses:16601661 <CodeGroup exclude="shell">1662 ```python Python1663 # Process tool use in Claude's response1664 for content in response.content:1665 if content.type == "tool_use":1666 # Execute the tool based on command1667 result = handle_editor_tool(content)16681669 # Return result to Claude1670 tool_result = {1671 "type": "tool_result",1672 "tool_use_id": content.id,1673 "content": result,1674 }1675 ```16761677 ```typescript TypeScript1678 // Process tool use in Claude's response1679 for (const block of response.content) {1680 if (block.type === "tool_use") {1681 // Execute the tool based on command1682 const result = handleEditorTool(block);16831684 // Return result to Claude1685 const toolResult = {1686 type: "tool_result",1687 tool_use_id: block.id,1688 content: result1689 };1690 }1691 }1692 ```16931694 ```csharp C#1695 // Process tool use in Claude's response1696 foreach (var block in response.Content)1697 {1698 if (block.TryPickToolUse(out var toolUse))1699 {1700 var result = HandleEditorTool(toolUse.Input);1701 var toolResult = new ToolResultBlockParam1702 {1703 ToolUseID = toolUse.ID,1704 Content = result,1705 };1706 }1707 }1708 ```17091710 ```go Go1711 // Process tool use in Claude's response1712 for _, block := range response.Content {1713 if block.Type == "tool_use" {1714 var input map[string]any1715 if err := json.Unmarshal(block.Input, &input); err != nil {1716 log.Fatal(err)1717 }1718 result := handleEditorTool(input)17191720 toolResult := anthropic.NewToolResultBlock(block.ID, result, false)1721 // ...1722 }1723 }1724 ```17251726 ```java Java1727 // Process tool use in Claude's response1728 for (var block : response.content()) {1729 if (block.type().equals("tool_use")) {1730 // Execute the tool based on command1731 var result = handleEditorTool(block);17321733 // Return result to Claude1734 var toolResult = Map.of(1735 "type", "tool_result",1736 "tool_use_id", block.id(),1737 "content", result1738 );1739 }1740 }1741 ```17421743 ```php PHP1744 // Process tool use in Claude's response1745 foreach ($response->content as $block) {1746 if ($block->type === 'tool_use') {1747 // Execute the tool based on command1748 $result = handle_editor_tool($block->input);17491750 // Return result to Claude1751 $toolResult = [1752 'type' => 'tool_result',1753 'tool_use_id' => $block->id,1754 'content' => $result,1755 ];1756 }1757 }1758 ```17591760 ```ruby Ruby1761 # Process tool use in Claude's response1762 tool_results = response.content.filter_map do |block|1763 next unless block.type == :tool_use17641765 {type: "tool_result", tool_use_id: block.id, content: handle_editor_tool(block.input)}1766 end1767 ```1768 </CodeGroup>1769 </Step>1770</Steps>17711772<Warning>1773 When implementing the text editor tool, keep in mind:17741775 1. **Security:** The tool has access to your local filesystem, so implement proper security measures.1776 2. **Backup:** Always create backups before allowing edits to important files.1777 3. **Validation:** Validate all inputs to prevent unintended changes.1778 4. **Unique matching:** Make sure replacements match exactly one location to avoid unintended edits.1779</Warning>17801781### Handle errors17821783When using the text editor tool, various errors may occur. Here is guidance on how to handle them:17841785<AccordionGroup>1786 <Accordion title="File not found">1787 If Claude tries to view or modify a file that doesn't exist, return an appropriate error message in the `tool_result`:17881789 ```json1790 {1791 "role": "user",1792 "content": [1793 {1794 "type": "tool_result",1795 "tool_use_id": "toolu_01A09q90qw90lq917835lq9",1796 "content": "Error: File not found",1797 "is_error": true1798 }1799 ]1800 }1801 ```1802 </Accordion>18031804 <Accordion title="Multiple matches for replacement">1805 If Claude's `str_replace` command matches multiple locations in the file, return an appropriate error message:18061807 ```json1808 {1809 "role": "user",1810 "content": [1811 {1812 "type": "tool_result",1813 "tool_use_id": "toolu_01A09q90qw90lq917835lq9",1814 "content": "Error: Found 3 matches for replacement text. Please provide more context to make a unique match.",1815 "is_error": true1816 }1817 ]1818 }1819 ```1820 </Accordion>18211822 <Accordion title="No matches for replacement">1823 If Claude's `str_replace` command doesn't match any text in the file, return an appropriate error message:18241825 ```json1826 {1827 "role": "user",1828 "content": [1829 {1830 "type": "tool_result",1831 "tool_use_id": "toolu_01A09q90qw90lq917835lq9",1832 "content": "Error: No match found for replacement. Please check your text and try again.",1833 "is_error": true1834 }1835 ]1836 }1837 ```1838 </Accordion>18391840 <Accordion title="Permission errors">1841 If there are permission issues with creating, reading, or modifying files, return an appropriate error message:18421843 ```json1844 {1845 "role": "user",1846 "content": [1847 {1848 "type": "tool_result",1849 "tool_use_id": "toolu_01A09q90qw90lq917835lq9",1850 "content": "Error: Permission denied. Cannot write to file.",1851 "is_error": true1852 }1853 ]1854 }1855 ```1856 </Accordion>1857</AccordionGroup>18581859### Follow implementation best practices18601861<AccordionGroup>1862 <Accordion title="Provide clear context">1863 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.18641865 **Less helpful prompt:** "Can you fix my code?"18661867 **Better prompt:** "There's a syntax error in my primes.py file that prevents it from running. Can you fix it?"1868 </Accordion>18691870 <Accordion title="Be explicit about file paths">1871 Specify file paths clearly when needed, especially if you're working with multiple files or files in different directories.18721873 **Less helpful prompt:** "Review my helper file"18741875 **Better prompt:** "Can you check my utils/helpers.py file for any performance issues?"1876 </Accordion>18771878 <Accordion title="Create backups before editing">1879 Implement a backup system in your application that creates copies of files before allowing Claude to edit them, especially for important or production code.18801881 <CodeGroup exclude="shell">1882 ```python Python1883 def backup_file(file_path):1884 """Create a backup of a file before editing."""1885 backup_path = f"{file_path}.backup"1886 if os.path.exists(file_path):1887 with open(file_path, "r") as src, open(backup_path, "w") as dst:1888 dst.write(src.read())1889 ```18901891 ```typescript TypeScript1892 async function backupFile(filePath: string): Promise<void> {1893 const backupPath = `${filePath}.backup`;1894 try {1895 await access(filePath);1896 await copyFile(filePath, backupPath);1897 } catch {1898 // File does not exist; nothing to back up1899 }1900 }1901 ```19021903 ```csharp C#1904 static void BackupFile(string filePath)1905 {1906 var backupPath = $"{filePath}.backup";1907 if (File.Exists(filePath))1908 {1909 File.Copy(filePath, backupPath, overwrite: true);1910 }1911 }1912 ```19131914 ```go Go1915 func backupFile(filePath string) error {1916 backupPath := filePath + ".backup"1917 data, err := os.ReadFile(filePath)1918 if err != nil {1919 if os.IsNotExist(err) {1920 return nil1921 }1922 return err1923 }1924 return os.WriteFile(backupPath, data, 0o644)1925 }1926 ```19271928 ```java Java1929 static void backupFile(String filePath) throws IOException {1930 Path source = Path.of(filePath);1931 Path backupPath = Path.of(filePath + ".backup");1932 if (Files.exists(source)) {1933 Files.copy(source, backupPath, StandardCopyOption.REPLACE_EXISTING);1934 }1935 }1936 ```19371938 ```php PHP1939 function backup_file(string $filePath): void1940 {1941 $backupPath = $filePath . '.backup';1942 if (file_exists($filePath)) {1943 copy($filePath, $backupPath);1944 }1945 }1946 ```19471948 ```ruby Ruby1949 def backup_file(file_path)1950 backup_path = "#{file_path}.backup"1951 FileUtils.cp(file_path, backup_path) if File.exist?(file_path)1952 end1953 ```1954 </CodeGroup>1955 </Accordion>19561957 <Accordion title="Handle unique text replacement carefully">1958 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.19591960 <CodeGroup exclude="shell">1961 ```python Python1962 def safe_replace(file_path, old_text, new_text):1963 """Replace text only if there's exactly one match."""1964 with open(file_path, "r") as f:1965 content = f.read()19661967 count = content.count(old_text)1968 if count == 0:1969 return "Error: No match found"1970 elif count > 1:1971 return f"Error: Found {count} matches"1972 else:1973 new_content = content.replace(old_text, new_text)1974 with open(file_path, "w") as f:1975 f.write(new_content)1976 return "Successfully replaced text"1977 ```19781979 ```typescript TypeScript1980 async function safeReplace(1981 filePath: string,1982 oldText: string,1983 newText: string1984 ): Promise<string> {1985 const content = await readFile(filePath, "utf8");19861987 const count = content.split(oldText).length - 1;1988 if (count === 0) {1989 return "Error: No match found";1990 } else if (count > 1) {1991 return `Error: Found ${count} matches`;1992 } else {1993 const newContent = content.replace(oldText, newText);1994 await writeFile(filePath, newContent, "utf8");1995 return "Successfully replaced text";1996 }1997 }1998 ```19992000 ```csharp C#2001 static string SafeReplace(string filePath, string oldText, string newText)2002 {2003 var content = File.ReadAllText(filePath);20042005 var count = content.Split(oldText).Length - 1;2006 if (count == 0)2007 {2008 return "Error: No match found";2009 }2010 else if (count > 1)2011 {2012 return $"Error: Found {count} matches";2013 }2014 else2015 {2016 var newContent = content.Replace(oldText, newText);2017 File.WriteAllText(filePath, newContent);2018 return "Successfully replaced text";2019 }2020 }2021 ```20222023 ```go Go2024 func safeReplace(filePath, oldText, newText string) string {2025 data, err := os.ReadFile(filePath)2026 if err != nil {2027 return fmt.Sprintf("Error: %v", err)2028 }2029 content := string(data)20302031 count := strings.Count(content, oldText)2032 if count == 0 {2033 return "Error: No match found"2034 } else if count > 1 {2035 return fmt.Sprintf("Error: Found %d matches", count)2036 }20372038 newContent := strings.Replace(content, oldText, newText, 1)2039 if err := os.WriteFile(filePath, []byte(newContent), 0o644); err != nil {2040 return fmt.Sprintf("Error: %v", err)2041 }2042 return "Successfully replaced text"2043 }2044 ```20452046 ```java Java2047 static String safeReplace(String filePath, String oldText, String newText) throws IOException {2048 String content = Files.readString(Path.of(filePath));20492050 int count = content.split(Pattern.quote(oldText), -1).length - 1;2051 if (count == 0) {2052 return "Error: No match found";2053 } else if (count > 1) {2054 return "Error: Found " + count + " matches";2055 } else {2056 String newContent = content.replace(oldText, newText);2057 Files.writeString(Path.of(filePath), newContent);2058 return "Successfully replaced text";2059 }2060 }2061 ```20622063 ```php PHP2064 function safe_replace(string $filePath, string $oldText, string $newText): string2065 {2066 $content = file_get_contents($filePath);20672068 $count = substr_count($content, $oldText);2069 if ($count === 0) {2070 return 'Error: No match found';2071 } elseif ($count > 1) {2072 return "Error: Found {$count} matches";2073 } else {2074 $newContent = str_replace($oldText, $newText, $content);2075 file_put_contents($filePath, $newContent);2076 return 'Successfully replaced text';2077 }2078 }2079 ```20802081 ```ruby Ruby2082 def safe_replace(file_path, old_text, new_text)2083 content = File.read(file_path)20842085 count = content.scan(old_text).length2086 if count == 02087 "Error: No match found"2088 elsif count > 12089 "Error: Found #{count} matches"2090 else2091 new_content = content.sub(old_text) { new_text }2092 File.write(file_path, new_content)2093 "Successfully replaced text"2094 end2095 end2096 ```2097 </CodeGroup>2098 </Accordion>20992100 <Accordion title="Verify changes">2101 After Claude makes changes to a file, verify the changes by running tests or checking that the code still works as expected.21022103 <CodeGroup exclude="shell">2104 ```python Python2105 def verify_changes(file_path):2106 """Run tests or checks after making changes."""2107 try:2108 # For Python files, check for syntax errors2109 if file_path.endswith(".py"):2110 import ast21112112 with open(file_path, "r") as f:2113 ast.parse(f.read())2114 return "Syntax check passed"2115 except Exception as e:2116 return f"Verification failed: {str(e)}"2117 ```21182119 ```typescript TypeScript2120 function verifyChanges(filePath: string): string {2121 try {2122 // For Python files, check for syntax errors2123 if (filePath.endsWith(".py")) {2124 execFileSync("python3", ["-m", "py_compile", filePath]);2125 return "Syntax check passed";2126 }2127 return "No checks defined for this file type";2128 } catch (err) {2129 return `Verification failed: ${err}`;2130 }2131 }2132 ```21332134 ```csharp C#2135 static string VerifyChanges(string filePath)2136 {2137 try2138 {2139 // For Python files, check for syntax errors2140 if (filePath.EndsWith(".py"))2141 {2142 var psi = new ProcessStartInfo("python3")2143 {2144 RedirectStandardError = true,2145 };2146 psi.ArgumentList.Add("-m");2147 psi.ArgumentList.Add("py_compile");2148 psi.ArgumentList.Add(filePath);2149 using var proc = Process.Start(psi)!;2150 proc.WaitForExit();2151 if (proc.ExitCode != 0)2152 {2153 return $"Verification failed: {proc.StandardError.ReadToEnd()}";2154 }2155 return "Syntax check passed";2156 }2157 return "No checks defined for this file type";2158 }2159 catch (Exception e)2160 {2161 return $"Verification failed: {e.Message}";2162 }2163 }2164 ```21652166 ```go Go2167 func verifyChanges(filePath string) string {2168 // For Python files, check for syntax errors2169 if strings.HasSuffix(filePath, ".py") {2170 cmd := exec.Command("python3", "-m", "py_compile", filePath)2171 if out, err := cmd.CombinedOutput(); err != nil {2172 return fmt.Sprintf("Verification failed: %v: %s", err, out)2173 }2174 return "Syntax check passed"2175 }2176 return "No checks defined for this file type"2177 }2178 ```21792180 ```java Java2181 static String verifyChanges(String filePath) {2182 try {2183 // For Python files, check for syntax errors2184 if (filePath.endsWith(".py")) {2185 Process proc = new ProcessBuilder("python3", "-m", "py_compile", filePath)2186 .redirectErrorStream(true)2187 .start();2188 if (proc.waitFor() != 0) {2189 return "Verification failed: " + new String(proc.getInputStream().readAllBytes());2190 }2191 return "Syntax check passed";2192 }2193 return "No checks defined for this file type";2194 } catch (IOException | InterruptedException e) {2195 return "Verification failed: " + e.getMessage();2196 }2197 }2198 ```21992200 ```php PHP2201 function verify_changes(string $filePath): string2202 {2203 // For Python files, check for syntax errors2204 if (str_ends_with($filePath, '.py')) {2205 exec('python3 -m py_compile ' . escapeshellarg($filePath) . ' 2>&1', $output, $exitCode);2206 if ($exitCode !== 0) {2207 return 'Verification failed: ' . implode("\n", $output);2208 }2209 return 'Syntax check passed';2210 }2211 return 'No checks defined for this file type';2212 }2213 ```22142215 ```ruby Ruby2216 def verify_changes(file_path)2217 # For Python files, check for syntax errors2218 if file_path.end_with?(".py")2219 if system("python3", "-m", "py_compile", file_path)2220 "Syntax check passed"2221 else2222 "Verification failed: syntax error in #{file_path}"2223 end2224 else2225 "No checks defined for this file type"2226 end2227 end2228 ```2229 </CodeGroup>2230 </Accordion>2231</AccordionGroup>22322233***22342235## Pricing and token usage22362237The 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.22382239In addition to the base tokens, the following additional input tokens are needed for the text editor tool:22402241| Tool | Additional input tokens |2242| ----------------------------------- | ----------------------- |2243| `text_editor_20250429` (Claude 4.x) | 700 tokens |22442245For more detailed information about tool pricing, see [Tool use pricing](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview#pricing).22462247## Integrate the text editor tool with other tools22482249You can use the text editor tool alongside other Claude tools. When combining tools, ensure you:22502251* Match the tool version with the model you're using2252* Account for the additional token usage for all tools included in your request22532254## Change log22552256| Date | Version | Changes |2257| ---------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |2258| 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`. |2259| 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. |2260| 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. |2261| October 22, 2024 | `text_editor_20241022` | Initial release of the text editor tool with Claude Sonnet 3.5 (retired; see [Model deprecations](https://platform.claude.com/docs/en/about-claude/model-deprecations)). Provides capabilities for viewing, creating, and editing files through the `view`, `create`, `str_replace`, `insert`, and `undo_edit` commands. |22622263## Next steps22642265Here are some ideas for how to use the text editor tool in more convenient and powerful ways:22662267* **Integrate with your development workflow**: Build the text editor tool into your development tools or IDE2268* **Create a code review system**: Have Claude review your code and make improvements2269* **Build a debugging assistant**: Create a system where Claude can help you diagnose and fix issues in your code2270* **Implement file format conversion**: Let Claude help you convert files from one format to another2271* **Automate documentation**: Set up workflows for Claude to automatically document your code22722273The text editor tool enables Claude to work directly with your code base, supporting workflows from debugging to automated documentation.22742275<CardGroup cols={3}>2276 <Card title="Tool use overview" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">2277 Learn how to implement tool workflows for use with Claude.2278 </Card>22792280 <Card title="Bash tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool">2281 Execute shell commands with Claude.2282 </Card>2283</CardGroup>2284