---
title: Texteditor-Tool
url: https://platform.claude.com/docs/de/agents-and-tools/tool-use/text-editor-tool
description: Stelle Claude das von Anthropic definierte Text-Editor-Tool zur Verfügung, um Dateien anzuzeigen, zu erstellen und zu bearbeiten, und verarbeite die Befehle view, str_replace, create und insert.
featureMetadata:
  status: stable
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). Clientseitiges Tool, das in deiner Umgebung ausgeführt wird.
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Amazon Bedrock: stable
    Amazon Bedrock (bedrock-runtime): stable
    Claude Platform on AWS: stable
    Claude Models on Google Cloud (Anthropic managed): stable
    Claude Models on Google Cloud (Google managed): stable
    Microsoft Foundry: stable
---

Claude kann ein Text-Editor-Tool mit Anthropic-Schema verwenden, um Textdateien anzuzeigen und zu ändern, und dir so helfen, deinen Code oder andere Textdokumente zu debuggen, zu korrigieren und zu verbessern. Dadurch kann Claude direkt mit deinen Dateien interagieren und praktische Unterstützung bieten, anstatt nur Änderungen vorzuschlagen.

Informationen zur Modellunterstützung findest du in der [Tool-Referenz](https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-reference).

## Wann du das Text-Editor-Tool verwenden solltest

Einige Beispiele dafür, wann du das Text-Editor-Tool verwenden kannst:

* **Code-Debugging:** Lass Claude Fehler in deinem Code identifizieren und beheben, von Syntaxfehlern bis hin zu Logikproblemen.
* **Code-Refactoring:** Lass Claude die Struktur, Lesbarkeit und Performance deines Codes durch gezielte Bearbeitungen verbessern.
* **Dokumentationserstellung:** Bitte Claude, Docstrings, Kommentare oder README-Dateien zu deiner Codebasis hinzuzufügen.
* **Testerstellung:** Lass Claude auf Grundlage seiner Analyse der Implementierung Unit-Tests für deinen Code erstellen.

## Das Text-Editor-Tool verwenden

Stelle Claude das Text-Editor-Tool (mit dem Namen `str_replace_based_edit_tool`) über die Messages API zur Verfügung.

Optional kannst du einen `max_characters`-Parameter angeben, um die Kürzung beim Anzeigen großer Dateien zu steuern.

<Note>
  `max_characters` ist nur mit `text_editor_20250728` und späteren Versionen des Text-Editor-Tools kompatibel.
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "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?"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --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?}'
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      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)
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic();

  const response = await anthropic.messages.create({
    model: "claude-opus-5-5",
    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);
  ```

  ```csharp C#
  var client = new AnthropicClient();

  var response = await client.Messages.Create(
      new()
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Tools = [new ToolTextEditor20250728 { MaxCharacters = 10000 }],
          Messages =
          [
              new UserMessageParam
              {
                  Content = "There's a syntax error in my primes.py file. Can you help me fix it?",
              },
          ],
      }
  );

  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{
  			MaxCharacters: anthropic.Int(10000),
  		}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  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_5_5)
          .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);
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 1024,
      tools: [ToolTextEditor20250728::with(maxCharacters: 10000)],
      messages: [
          [
              'role' => 'user',
              'content' => "There's a syntax error in my primes.py file. Can you help me fix it?",
          ],
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    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?"
      }
    ]
  )

  puts response
  ```
</CodeGroup>

Verwende das Text-Editor-Tool folgendermaßen:

<Steps>
  <Step title="Stelle Claude das Text-Editor-Tool und einen Benutzer-Prompt bereit">
    * Füge das Text-Editor-Tool in deine API-Anfrage ein.
    * Gib einen Benutzer-Prompt an, der das Untersuchen oder Ändern von Dateien erfordern könnte, zum Beispiel „Kannst du den Syntaxfehler in meinem Code beheben?“
  </Step>

  <Step title="Claude verwendet das Tool, um Dateien oder Verzeichnisse zu untersuchen">
    * Claude bewertet, was es sich ansehen muss, und verwendet den Befehl `view`, um Dateiinhalte zu untersuchen oder Verzeichnisinhalte aufzulisten.
    * Die API-Antwort enthält einen `tool_use`-Content-Block mit dem Befehl `view`.
  </Step>

  <Step title="Führe den view-Befehl aus und gib die Ergebnisse zurück">
    * Extrahiere den Datei- oder Verzeichnispfad aus Claudes Tool-Nutzungs-Anfrage.
    * Lies den Inhalt der Datei oder liste den Inhalt des Verzeichnisses auf.
    * Wenn du in der Tool-Konfiguration einen `max_characters`-Parameter angegeben hast, kürze den Dateiinhalt auf diese Länge.
    * Gib die Ergebnisse an Claude zurück, indem du die Konversation mit einer neuen `user`-Nachricht fortsetzt, die einen `tool_result`-Content-Block enthält.
  </Step>

  <Step title="Claude verwendet das Tool, um Dateien zu ändern">
    * Nach dem Untersuchen der Datei oder des Verzeichnisses verwendet Claude möglicherweise einen Befehl wie `str_replace`, um Änderungen vorzunehmen, oder `insert`, um Text an einer bestimmten Zeilennummer hinzuzufügen.
    * Wenn Claude den Befehl `str_replace` verwendet, erstellt Claude eine korrekt formatierte Tool-Nutzungs-Anfrage mit dem alten Text und dem neuen Text, durch den er ersetzt werden soll.
  </Step>

  <Step title="Führe die Bearbeitung durch und gib die Ergebnisse zurück">
    * Extrahiere den Dateipfad, den alten Text und den neuen Text aus Claudes Tool-Nutzungs-Anfrage.
    * Führe die Textersetzung in der Datei durch.
    * Gib die Ergebnisse an Claude zurück.
  </Step>

  <Step title="Claude liefert seine Analyse und Erklärung">
    * Nach dem Untersuchen und möglicherweise Bearbeiten der Dateien liefert Claude eine vollständige Erklärung dessen, was es gefunden und welche Änderungen es vorgenommen hat.
  </Step>
</Steps>

### Befehle des Text-Editor-Tools

Das Text-Editor-Tool unterstützt mehrere Befehle zum Anzeigen und Ändern von Dateien:

#### view

Mit dem Befehl `view` kann Claude den Inhalt einer Datei untersuchen oder den Inhalt eines Verzeichnisses auflisten. Er kann die gesamte Datei oder einen bestimmten Zeilenbereich lesen.

Parameter:

* `command`: Muss `view` sein
* `path`: Der Pfad zur anzuzeigenden Datei oder zum anzuzeigenden Verzeichnis
* `view_range` (optional): Ein Array aus zwei Ganzzahlen, die die Start- und Endzeilennummer angeben, die angezeigt werden sollen. Zeilennummern beginnen bei 1, und -1 als Endzeile bedeutet, bis zum Ende der Datei zu lesen. Dieser Parameter gilt nur beim Anzeigen von Dateien, nicht von Verzeichnissen.

<Accordion title="Beispiele für view-Befehle">
  Beispiel für das Anzeigen einer Datei:

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

  Beispiel für das Anzeigen eines Verzeichnisses:

  ```json
  {
    "type": "tool_use",
    "id": "toolu_02B19r91rw91mr917835mr9",
    "name": "str_replace_based_edit_tool",
    "input": {
      "command": "view",
      "path": "src/"
    }
  }
  ```
</Accordion>

#### str\_replace

Mit dem Befehl `str_replace` kann Claude eine bestimmte Zeichenkette in einer Datei durch eine neue Zeichenkette ersetzen. Dies wird für präzise Bearbeitungen verwendet.

Parameter:

* `command`: Muss `str_replace` sein
* `path`: Der Pfad zur zu ändernden Datei
* `old_str`: Der zu ersetzende Text (muss exakt übereinstimmen, einschließlich Leerzeichen und Einrückung)
* `new_str`: Der neue Text, der anstelle des alten Textes eingefügt werden soll

<Accordion title="Beispiel für einen str_replace-Befehl">
  ```json
  {
    "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):"
    }
  }
  ```
</Accordion>

#### create

Mit dem Befehl `create` kann Claude eine neue Datei mit angegebenem Inhalt erstellen.

Parameter:

* `command`: Muss `create` sein
* `path`: Der Pfad, unter dem die neue Datei erstellt werden soll
* `file_text`: Der Inhalt, der in die neue Datei geschrieben werden soll

<Accordion title="Beispiel für einen create-Befehl">
  ```json
  {
    "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()"
    }
  }
  ```
</Accordion>

#### insert

Mit dem Befehl `insert` kann Claude Text an einer bestimmten Stelle in einer Datei einfügen.

Parameter:

* `command`: Muss `insert` sein
* `path`: Der Pfad zur zu ändernden Datei
* `insert_line`: Die Zeilennummer, nach der der Text eingefügt werden soll (0 für den Anfang der Datei)
* `insert_text`: Der einzufügende Text

<Accordion title="Beispiel für einen insert-Befehl">
  ```json
  {
    "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"
    }
  }
  ```
</Accordion>

### Beispiel: Einen Syntaxfehler mit dem Text-Editor-Tool beheben

Dieses Beispiel zeigt, wie Claude das Text-Editor-Tool verwendet, um einen Syntaxfehler in einer Python-Datei zu beheben.

Zuerst stellt deine Anwendung Claude das Text-Editor-Tool und einen Prompt zum Beheben eines Syntaxfehlers bereit:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "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?"
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --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?}'
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      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)
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic();

  const response = await anthropic.messages.create({
    model: "claude-opus-5-5",
    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);
  ```

  ```csharp C#
  var client = new AnthropicClient();

  var response = await client.Messages.Create(
      new()
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Tools = [new ToolTextEditor20250728()],
          Messages =
          [
              new UserMessageParam
              {
                  Content = "There's a syntax error in my primes.py file. Can you help me fix it?",
              },
          ],
      }
  );

  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  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_5_5)
          .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);
  }
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 1024,
      tools: [new ToolTextEditor20250728()],
      messages: [
          [
              'role' => 'user',
              'content' => "There's a syntax error in my primes.py file. Can you help me fix it?",
          ],
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    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?"
      }
    ]
  )

  puts response
  ```
</CodeGroup>

Claude verwendet das Text-Editor-Tool zunächst, um die Datei anzuzeigen:

```json Output
{
  "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
  "model": "claude-opus-5-5",
  "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"
      }
    }
  ]
}
```

Deine Anwendung sollte dann die Datei lesen und ihren Inhalt an Claude zurückgeben:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "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()"
            }
          ]
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  tools:
    - type: text_editor_20250728
      name: str_replace_based_edit_tool
  messages:
    - role: user
      content: There's a syntax error in my primes.py file. Can you help me fix it?
    - role: assistant
      content:
        - type: text
          text: >-
            I'll help you fix the syntax error in your primes.py file. First,
            let me take a look at the file to identify the issue.
        - type: tool_use
          id: toolu_01AbCdEfGhIjKlMnOpQrStU
          name: str_replace_based_edit_tool
          input:
            command: view
            path: primes.py
    - role: user
      content:
        - type: tool_result
          tool_use_id: toolu_01AbCdEfGhIjKlMnOpQrStU
          content: |-
            1: def is_prime(n):
            2:     """Check if a number is prime."""
            3:     if n <= 1:
            4:         return False
            5:     if n <= 3:
            6:         return True
            7:     if n % 2 == 0 or n % 3 == 0:
            8:         return False
            9:     i = 5
            10:     while i * i <= n:
            11:         if n % i == 0 or n % (i + 2) == 0:
            12:             return False
            13:         i += 6
            14:     return True
            15:
            16: def get_primes(limit):
            17:     """Generate a list of prime numbers up to the given limit."""
            18:     primes = []
            19:     for num in range(2, limit + 1)
            20:         if is_prime(num):
            21:             primes.append(num)
            22:     return primes
            23:
            24: def main():
            25:     """Main function to demonstrate prime number generation."""
            26:     limit = 100
            27:     prime_list = get_primes(limit)
            28:     print(f"Prime numbers up to {limit}:")
            29:     print(prime_list)
            30:     print(f"Found {len(prime_list)} prime numbers.")
            31:
            32: if __name__ == "__main__":
            33:     main()
  YAML
  ```

  ```python Python
  response = client.messages.create(
      model="claude-opus-5-5",
      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)
  ```

  ```typescript TypeScript
  const anthropic = new Anthropic();

  const response = await anthropic.messages.create({
    model: "claude-opus-5-5",
    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);
  ```

  ```csharp C#
  var client = new AnthropicClient();

  var response = await client.Messages.Create(
      new()
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Tools = [new ToolTextEditor20250728()],
          Messages =
          [
              new UserMessageParam
              {
                  Content = "There's a syntax error in my primes.py file. Can you help me fix it?",
              },
              new AssistantMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new TextBlockParam()
                      {
                          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.",
                      }),
                      new ContentBlockParam(new ToolUseBlockParam()
                      {
                          ID = "toolu_01AbCdEfGhIjKlMnOpQrStU",
                          Name = "str_replace_based_edit_tool",
                          Input = new Dictionary<string, JsonElement>
                          {
                              ["command"] = JsonSerializer.SerializeToElement("view"),
                              ["path"] = JsonSerializer.SerializeToElement("primes.py"),
                          },
                      }),
                  },
              },
              new UserMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new ToolResultBlockParam()
                      {
                          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()",
                      }),
                  },
              },
          ],
      }
  );

  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),
  		anthropic.NewAssistantMessage(
  			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."),
  			anthropic.NewToolUseBlock(
  				"toolu_01AbCdEfGhIjKlMnOpQrStU",
  				map[string]any{"command": "view", "path": "primes.py"},
  				"str_replace_based_edit_tool",
  			),
  		),
  		anthropic.NewUserMessage(
  			anthropic.NewToolResultBlock(
  				"toolu_01AbCdEfGhIjKlMnOpQrStU",
  				"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()",
  				false,
  			),
  		),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(1024)
      .addTool(ToolTextEditor20250728.builder().build())
      .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")
      .addAssistantMessageOfContentBlockParams(
          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()
              )
          )
      )
      .addUserMessageOfContentBlockParams(
          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);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 1024,
      tools: [new ToolTextEditor20250728()],
      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()",
                  ],
              ],
          ],
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    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()"
          }
        ]
      }
    ]
  )

  puts response
  ```
</CodeGroup>

<Tip>
  **Zeilennummern**

  Im vorherigen Beispiel enthält das Ergebnis des `view`-Tools Dateiinhalte, denen jeweils Zeilennummern vorangestellt sind (zum Beispiel „1: def is\_prime(n):“). Zeilennummern sind nicht erforderlich, aber sie sind unerlässlich, um den Parameter `view_range` erfolgreich zum Untersuchen bestimmter Abschnitte von Dateien und den Parameter `insert_line` zum Hinzufügen von Inhalten an präzisen Stellen zu verwenden.
</Tip>

Claude identifiziert den Syntaxfehler und verwendet den Befehl `str_replace`, um ihn zu beheben:

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

Deine Anwendung sollte dann die Bearbeitung durchführen und das Ergebnis zurückgeben:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "tools": [
        {
          "type": "text_editor_20250728",
          "name": "str_replace_based_edit_tool"
        }
      ],
      "messages": [
        {
          "role": "assistant",
          "content": [
            {
              "type": "text",
              "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."
            },
            {
              "type": "tool_use",
              "id": "toolu_01PqRsTuVwXyZAbCdEfGh",
              "name": "str_replace_based_edit_tool",
              "input": {
                "command": "str_replace",
                "path": "primes.py",
                "old_str": "    for num in range(2, limit + 1)",
                "new_str": "    for num in range(2, limit + 1):"
              }
            }
          ]
        },
        {
          "role": "user",
          "content": [
            {
              "type": "tool_result",
              "tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",
              "content": "Successfully replaced text at exactly one location."
            }
          ]
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  tools:
    - type: text_editor_20250728
      name: str_replace_based_edit_tool
  messages:
    # Vorherige Nachrichten...
    - role: assistant
      content:
        - type: text
          text: >-
            I found the syntax error in your primes.py file. In the `get_primes`
            function, there is a missing colon (:) at the end of the for loop
            line. Let me fix that for you.
        - type: tool_use
          id: toolu_01PqRsTuVwXyZAbCdEfGh
          name: str_replace_based_edit_tool
          input:
            command: str_replace
            path: primes.py
            old_str: "    for num in range(2, limit + 1)"
            new_str: "    for num in range(2, limit + 1):"
    - role: user
      content:
        - type: tool_result
          tool_use_id: toolu_01PqRsTuVwXyZAbCdEfGh
          content: Successfully replaced text at exactly one location.
  YAML
  ```

  ```python Python
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
      messages=[
          # Vorherige Nachrichten...
          {
              "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)
  ```

  ```typescript TypeScript
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [
      {
        type: "text_editor_20250728",
        name: "str_replace_based_edit_tool"
      }
    ],
    messages: [
      // Vorherige Nachrichten...
      {
        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);
  ```

  ```csharp C#
  var client = new AnthropicClient();

  var response = await client.Messages.Create(
      new()
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Tools = [new ToolTextEditor20250728()],
          Messages =
          [
              // Vorherige Nachrichten...
              new AssistantMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new TextBlockParam()
                      {
                          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.",
                      }),
                      new ContentBlockParam(new ToolUseBlockParam()
                      {
                          ID = "toolu_01PqRsTuVwXyZAbCdEfGh",
                          Name = "str_replace_based_edit_tool",
                          Input = new Dictionary<string, JsonElement>
                          {
                              ["command"] = JsonSerializer.SerializeToElement("str_replace"),
                              ["path"] = JsonSerializer.SerializeToElement("primes.py"),
                              ["old_str"] = JsonSerializer.SerializeToElement("    for num in range(2, limit + 1)"),
                              ["new_str"] = JsonSerializer.SerializeToElement("    for num in range(2, limit + 1):"),
                          },
                      }),
                  },
              },
              new UserMessageParam
              {
                  Content = new List<ContentBlockParam>
                  {
                      new ContentBlockParam(new ToolResultBlockParam()
                      {
                          ToolUseID = "toolu_01PqRsTuVwXyZAbCdEfGh",
                          Content = "Successfully replaced text at exactly one location.",
                      }),
                  },
              },
          ],
      }
  );

  Console.WriteLine(response);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
  	},
  	Messages: []anthropic.MessageParam{
  		// Vorherige Nachrichten...
  		anthropic.NewAssistantMessage(
  			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."),
  			anthropic.NewToolUseBlock(
  				"toolu_01PqRsTuVwXyZAbCdEfGh",
  				map[string]any{
  					"command": "str_replace",
  					"path":    "primes.py",
  					"old_str": "    for num in range(2, limit + 1)",
  					"new_str": "    for num in range(2, limit + 1):",
  				},
  				"str_replace_based_edit_tool",
  			),
  		),
  		anthropic.NewUserMessage(
  			anthropic.NewToolResultBlock(
  				"toolu_01PqRsTuVwXyZAbCdEfGh",
  				"Successfully replaced text at exactly one location.",
  				false,
  			),
  		),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(1024)
      .addTool(ToolTextEditor20250728.builder().build())
      // Hier würden die vorherigen Nachrichten stehen
      .addAssistantMessageOfContentBlockParams(
          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()
              )
          )
      )
      .addUserMessageOfContentBlockParams(
          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);
  ```

  ```php PHP
  $client = new Client();

  $response = $client->messages->create(
      model: Model::CLAUDE_OPUS_5_5,
      maxTokens: 1024,
      tools: [new ToolTextEditor20250728()],
      messages: [
          // Vorherige Nachrichten...
          [
              '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.',
                  ],
              ],
          ],
      ],
  );

  echo $response;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 1024,
    tools: [{type: "text_editor_20250728", name: "str_replace_based_edit_tool"}],
    messages: [
      # Vorherige Nachrichten...
      {
        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."
          }
        ]
      }
    ]
  )

  puts response
  ```
</CodeGroup>

Abschließend liefert Claude eine vollständige Erklärung der Korrektur:

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

## Das Text-Editor-Tool implementieren

Das Text-Editor-Tool ist als schemaloses Tool implementiert. Wenn du dieses Tool verwendest, musst du kein Eingabeschema wie bei anderen Tools angeben; das Schema ist in Claudes Modell integriert und kann nicht geändert werden.

Der Tool-Typ ist `type: "text_editor_20250728"` für Claude 4 und spätere Modelle.

<Steps>
  <Step title="Initialisiere deine Editor-Implementierung">
    Erstelle Hilfsfunktionen für Dateioperationen wie das Lesen, Schreiben und Ändern von Dateien. Erwäge, eine Backup-Funktionalität zu implementieren, um Fehler rückgängig machen zu können.
  </Step>

  <Step title="Verarbeite Editor-Tool-Aufrufe">
    Erstelle eine Funktion, die Tool-Aufrufe von Claude basierend auf dem Befehlstyp verarbeitet:

    <CodeGroup exclude="shell">
      ```python Python
      def handle_editor_tool(tool_call):
          input_params = tool_call.input
          command = input_params.get("command", "")
          file_path = input_params.get("path", "")

          match command:
              case "view":
                  # Dateiinhalt lesen und zurückgeben
                  pass
              case "str_replace":
                  # Text in Datei ersetzen
                  pass
              case "create":
                  # Neue Datei erstellen
                  pass
              case "insert":
                  # Text an Position einfügen
                  pass
      ```

      ```typescript TypeScript
      function handleEditorTool(toolCall: { input: { command?: string; path?: string } }): void {
        const inputParams = toolCall.input;
        const command = inputParams.command ?? "";
        const filePath = inputParams.path ?? "";

        switch (command) {
          case "view":
            // Dateiinhalt lesen und zurückgeben
            break;
          case "str_replace":
            // Text in Datei ersetzen
            break;
          case "create":
            // Neue Datei erstellen
            break;
          case "insert":
            // Text an Position einfügen
            break;
        }
      }
      ```

      ```csharp C#
      static string HandleEditorTool(IReadOnlyDictionary<string, JsonElement> input)
      {
          input.TryGetValue("command", out var commandEl);
          input.TryGetValue("path", out var pathEl);
          var command = commandEl.ValueKind == JsonValueKind.String ? commandEl.GetString() : null;
          var filePath = pathEl.ValueKind == JsonValueKind.String ? pathEl.GetString() : null;

          if (command == "view")
          {
              // Dateiinhalt lesen und zurückgeben
          }
          else if (command == "str_replace")
          {
              // Text in Datei ersetzen
          }
          else if (command == "create")
          {
              // Neue Datei erstellen
          }
          else if (command == "insert")
          {
              // Text an Position einfügen
          }
          return "";
      }
      ```

      ```go Go
      func handleEditorTool(input map[string]any) string {
      	command, _ := input["command"].(string)
      	filePath, _ := input["path"].(string)
      	// ...

      	switch command {
      	case "view":
      		// Dateiinhalt lesen und zurückgeben
      	case "str_replace":
      		// Text in Datei ersetzen
      	case "create":
      		// Neue Datei erstellen
      	case "insert":
      		// Text an Position einfügen
      	}
      	return ""
      }
      ```

      ```java Java
      static void handleEditorTool(Map<String, Object> input) {
          var command = (String) input.getOrDefault("command", "");
          var filePath = (String) input.getOrDefault("path", "");

          if (command.equals("view")) {
              // Dateiinhalt lesen und zurückgeben
          } else if (command.equals("str_replace")) {
              // Text in Datei ersetzen
          } else if (command.equals("create")) {
              // Neue Datei erstellen
          } else if (command.equals("insert")) {
              // Text an Position einfügen
          }
      }
      ```

      ```php PHP
      function handle_editor_tool(array $input): string
      {
          $command = $input['command'] ?? '';
          $filePath = $input['path'] ?? '';

          if ($command === 'view') {
              // Dateiinhalt lesen und zurückgeben
          } elseif ($command === 'str_replace') {
              // Text in Datei ersetzen
          } elseif ($command === 'create') {
              // Neue Datei erstellen
          } elseif ($command === 'insert') {
              // Text an Position einfügen
          }
          return '';
      }
      ```

      ```ruby Ruby
      def handle_editor_tool(input)
        command = input[:command] || ""
        file_path = input[:path] || ""

        case command
        when "view"
          # Dateiinhalt lesen und zurückgeben
        when "str_replace"
          # Text in Datei ersetzen
        when "create"
          # Neue Datei erstellen
        when "insert"
          # Text an Position einfügen
        end
      end
      ```
    </CodeGroup>
  </Step>

  <Step title="Implementiere Sicherheitsmaßnahmen">
    Füge Validierungen und Sicherheitsprüfungen hinzu:

    * Validiere Dateipfade, um Directory Traversal zu verhindern
    * Erstelle Backups, bevor Änderungen vorgenommen werden
    * Behandle Fehler ordnungsgemäß
    * Implementiere Berechtigungsprüfungen
  </Step>

  <Step title="Verarbeite Claudes Antworten">
    Extrahiere und verarbeite Tool-Aufrufe aus Claudes Antworten:

    <CodeGroup exclude="shell">
      ```python Python
      # Verarbeite die Tool-Nutzung in Claudes Antwort
      for content in response.content:
          if content.type == "tool_use":
              # Führe das Tool basierend auf dem Befehl aus
              result = handle_editor_tool(content)

              # Gib das Ergebnis an Claude zurück
              tool_result = {
                  "type": "tool_result",
                  "tool_use_id": content.id,
                  "content": result,
              }
      ```

      ```typescript TypeScript
      // Verarbeite die Tool-Nutzung in Claudes Antwort
      for (const block of response.content) {
        if (block.type === "tool_use") {
          // Führe das Tool anhand des Befehls aus
          const result = handleEditorTool(block);

          // Gib das Ergebnis an Claude zurück
          const toolResult = {
            type: "tool_result",
            tool_use_id: block.id,
            content: result
          };
        }
      }
      ```

      ```csharp C#
      // Verarbeite die Tool-Nutzung in Claudes Antwort
      foreach (var block in response.Content)
      {
          if (block.TryPickToolUse(out var toolUse))
          {
              var result = HandleEditorTool(toolUse.Input);
              var toolResult = new ToolResultBlockParam
              {
                  ToolUseID = toolUse.ID,
                  Content = result,
              };
          }
      }
      ```

      ```go Go
      // Verarbeite die Tool-Nutzung in Claudes Antwort
      for _, block := range response.Content {
      	if block.Type == "tool_use" {
      		var input map[string]any
      		if err := json.Unmarshal(block.Input, &input); err != nil {
      			log.Fatal(err)
      		}
      		result := handleEditorTool(input)

      		toolResult := anthropic.NewToolResultBlock(block.ID, result, false)
      		// ...
      	}
      }
      ```

      ```java Java
      // Verarbeite die Tool-Nutzung in Claudes Antwort
      for (var block : response.content()) {
          if (block.type().equals("tool_use")) {
              // Führe das Tool basierend auf dem Befehl aus
              var result = handleEditorTool(block);

              // Gib das Ergebnis an Claude zurück
              var toolResult = Map.of(
                  "type", "tool_result",
                  "tool_use_id", block.id(),
                  "content", result
              );
          }
      }
      ```

      ```php PHP
      // Verarbeite die Tool-Nutzung in Claudes Antwort
      foreach ($response->content as $block) {
          if ($block->type === 'tool_use') {
              // Führe das Tool abhängig vom Befehl aus
              $result = handle_editor_tool($block->input);

              // Gib das Ergebnis an Claude zurück
              $toolResult = [
                  'type' => 'tool_result',
                  'tool_use_id' => $block->id,
                  'content' => $result,
              ];
          }
      }
      ```

      ```ruby Ruby
      # Verarbeite die Tool-Nutzung in Claudes Antwort
      tool_results = response.content.filter_map do |block|
        next unless block.type == :tool_use

        {type: "tool_result", tool_use_id: block.id, content: handle_editor_tool(block.input)}
      end
      ```
    </CodeGroup>
  </Step>
</Steps>

<Warning>
  Beachte bei der Implementierung des Text-Editor-Tools Folgendes:

  1. **Sicherheit:** Das Tool hat Zugriff auf dein lokales Dateisystem, implementiere also angemessene Sicherheitsmaßnahmen.
  2. **Backup:** Erstelle immer Backups, bevor du Bearbeitungen an wichtigen Dateien zulässt.
  3. **Validierung:** Validiere alle Eingaben, um unbeabsichtigte Änderungen zu verhindern.
  4. **Eindeutige Übereinstimmung:** Stelle sicher, dass Ersetzungen genau mit einer Stelle übereinstimmen, um unbeabsichtigte Bearbeitungen zu vermeiden.
</Warning>

### Fehler behandeln

Bei der Verwendung des Text-Editor-Tools können verschiedene Fehler auftreten. Hier findest du Hinweise, wie du damit umgehst:

<AccordionGroup>
  <Accordion title="Datei nicht gefunden">
    Wenn Claude versucht, eine Datei anzuzeigen oder zu ändern, die nicht existiert, gib eine entsprechende Fehlermeldung im `tool_result` zurück:

    ```json
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
          "content": "Error: File not found",
          "is_error": true
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="Mehrere Übereinstimmungen für die Ersetzung">
    Wenn Claudes `str_replace`-Befehl mit mehreren Stellen in der Datei übereinstimmt, gib eine entsprechende Fehlermeldung zurück:

    ```json
    {
      "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
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="Keine Übereinstimmungen für die Ersetzung">
    Wenn Claudes `str_replace`-Befehl mit keinem Text in der Datei übereinstimmt, gib eine entsprechende Fehlermeldung zurück:

    ```json
    {
      "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
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="Berechtigungsfehler">
    Wenn es Berechtigungsprobleme beim Erstellen, Lesen oder Ändern von Dateien gibt, gib eine entsprechende Fehlermeldung zurück:

    ```json
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
          "content": "Error: Permission denied. Cannot write to file.",
          "is_error": true
        }
      ]
    }
    ```
  </Accordion>
</AccordionGroup>

### Best Practices für die Implementierung befolgen

<AccordionGroup>
  <Accordion title="Klaren Kontext bereitstellen">
    Wenn du Claude bittest, Code zu korrigieren oder zu ändern, gib genau an, welche Dateien untersucht oder welche Probleme behoben werden sollen. Klarer Kontext hilft Claude, die richtigen Dateien zu identifizieren und angemessene Änderungen vorzunehmen.

    **Weniger hilfreicher Prompt:** „Kannst du meinen Code korrigieren?“

    **Besserer Prompt:** „In meiner Datei primes.py gibt es einen Syntaxfehler, der verhindert, dass sie ausgeführt wird. Kannst du ihn beheben?“
  </Accordion>

  <Accordion title="Dateipfade explizit angeben">
    Gib Dateipfade bei Bedarf klar an, insbesondere wenn du mit mehreren Dateien oder Dateien in verschiedenen Verzeichnissen arbeitest.

    **Weniger hilfreicher Prompt:** „Überprüfe meine Hilfsdatei“

    **Besserer Prompt:** „Kannst du meine Datei utils/helpers.py auf Performance-Probleme überprüfen?“
  </Accordion>

  <Accordion title="Backups vor dem Bearbeiten erstellen">
    Implementiere in deiner Anwendung ein Backup-System, das Kopien von Dateien erstellt, bevor Claude sie bearbeiten darf, insbesondere bei wichtigem Code oder Produktionscode.

    <CodeGroup exclude="shell">
      ```python Python
      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())
      ```

      ```typescript TypeScript
      async function backupFile(filePath: string): Promise<void> {
        const backupPath = `${filePath}.backup`;
        try {
          await access(filePath);
          await copyFile(filePath, backupPath);
        } catch {
          // Datei existiert nicht; nichts zu sichern
        }
      }
      ```

      ```csharp C#
      static void BackupFile(string filePath)
      {
          var backupPath = $"{filePath}.backup";
          if (File.Exists(filePath))
          {
              File.Copy(filePath, backupPath, overwrite: true);
          }
      }
      ```

      ```go Go
      func backupFile(filePath string) error {
      	backupPath := filePath + ".backup"
      	data, err := os.ReadFile(filePath)
      	if err != nil {
      		if os.IsNotExist(err) {
      			return nil
      		}
      		return err
      	}
      	return os.WriteFile(backupPath, data, 0o644)
      }
      ```

      ```java Java
      static void backupFile(String filePath) throws IOException {
          Path source = Path.of(filePath);
          Path backupPath = Path.of(filePath + ".backup");
          if (Files.exists(source)) {
              Files.copy(source, backupPath, StandardCopyOption.REPLACE_EXISTING);
          }
      }
      ```

      ```php PHP
      function backup_file(string $filePath): void
      {
          $backupPath = $filePath . '.backup';
          if (file_exists($filePath)) {
              copy($filePath, $backupPath);
          }
      }
      ```

      ```ruby Ruby
      def backup_file(file_path)
        backup_path = "#{file_path}.backup"
        FileUtils.cp(file_path, backup_path) if File.exist?(file_path)
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Eindeutige Textersetzung sorgfältig behandeln">
    Der Befehl `str_replace` erfordert eine exakte Übereinstimmung für den zu ersetzenden Text. Deine Anwendung sollte sicherstellen, dass es genau eine Übereinstimmung für den alten Text gibt, oder entsprechende Fehlermeldungen ausgeben.

    <CodeGroup exclude="shell">
      ```python Python
      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"
      ```

      ```typescript TypeScript
      async function safeReplace(
        filePath: string,
        oldText: string,
        newText: string
      ): Promise<string> {
        const content = await readFile(filePath, "utf8");

        const count = content.split(oldText).length - 1;
        if (count === 0) {
          return "Error: No match found";
        } else if (count > 1) {
          return `Error: Found ${count} matches`;
        } else {
          const newContent = content.replace(oldText, newText);
          await writeFile(filePath, newContent, "utf8");
          return "Successfully replaced text";
        }
      }
      ```

      ```csharp C#
      static string SafeReplace(string filePath, string oldText, string newText)
      {
          var content = File.ReadAllText(filePath);

          var count = content.Split(oldText).Length - 1;
          if (count == 0)
          {
              return "Error: No match found";
          }
          else if (count > 1)
          {
              return $"Error: Found {count} matches";
          }
          else
          {
              var newContent = content.Replace(oldText, newText);
              File.WriteAllText(filePath, newContent);
              return "Successfully replaced text";
          }
      }
      ```

      ```go Go
      func safeReplace(filePath, oldText, newText string) string {
      	data, err := os.ReadFile(filePath)
      	if err != nil {
      		return fmt.Sprintf("Error: %v", err)
      	}
      	content := string(data)

      	count := strings.Count(content, oldText)
      	if count == 0 {
      		return "Error: No match found"
      	} else if count > 1 {
      		return fmt.Sprintf("Error: Found %d matches", count)
      	}

      	newContent := strings.Replace(content, oldText, newText, 1)
      	if err := os.WriteFile(filePath, []byte(newContent), 0o644); err != nil {
      		return fmt.Sprintf("Error: %v", err)
      	}
      	return "Successfully replaced text"
      }
      ```

      ```java Java
      static String safeReplace(String filePath, String oldText, String newText) throws IOException {
          String content = Files.readString(Path.of(filePath));

          int count = content.split(Pattern.quote(oldText), -1).length - 1;
          if (count == 0) {
              return "Error: No match found";
          } else if (count > 1) {
              return "Error: Found " + count + " matches";
          } else {
              String newContent = content.replace(oldText, newText);
              Files.writeString(Path.of(filePath), newContent);
              return "Successfully replaced text";
          }
      }
      ```

      ```php PHP
      function safe_replace(string $filePath, string $oldText, string $newText): string
      {
          $content = file_get_contents($filePath);

          $count = substr_count($content, $oldText);
          if ($count === 0) {
              return 'Error: No match found';
          } elseif ($count > 1) {
              return "Error: Found {$count} matches";
          } else {
              $newContent = str_replace($oldText, $newText, $content);
              file_put_contents($filePath, $newContent);
              return 'Successfully replaced text';
          }
      }
      ```

      ```ruby Ruby
      def safe_replace(file_path, old_text, new_text)
        content = File.read(file_path)

        count = content.scan(old_text).length
        if count == 0
          "Error: No match found"
        elsif count > 1
          "Error: Found #{count} matches"
        else
          new_content = content.sub(old_text) { new_text }
          File.write(file_path, new_content)
          "Successfully replaced text"
        end
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Änderungen überprüfen">
    Nachdem Claude Änderungen an einer Datei vorgenommen hat, überprüfe die Änderungen, indem du Tests ausführst oder kontrollierst, ob der Code weiterhin wie erwartet funktioniert.

    <CodeGroup exclude="shell">
      ```python Python
      def verify_changes(file_path):
          """Run tests or checks after making changes."""
          try:
              # Prüfe Python-Dateien auf Syntaxfehler
              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)}"
      ```

      ```typescript TypeScript
      function verifyChanges(filePath: string): string {
        try {
          // Bei Python-Dateien auf Syntaxfehler prüfen
          if (filePath.endsWith(".py")) {
            execFileSync("python3", ["-m", "py_compile", filePath]);
            return "Syntax check passed";
          }
          return "No checks defined for this file type";
        } catch (err) {
          return `Verification failed: ${err}`;
        }
      }
      ```

      ```csharp C#
      static string VerifyChanges(string filePath)
      {
          try
          {
              // Prüfe Python-Dateien auf Syntaxfehler
              if (filePath.EndsWith(".py"))
              {
                  var psi = new ProcessStartInfo("python3")
                  {
                      RedirectStandardError = true,
                  };
                  psi.ArgumentList.Add("-m");
                  psi.ArgumentList.Add("py_compile");
                  psi.ArgumentList.Add(filePath);
                  using var proc = Process.Start(psi)!;
                  proc.WaitForExit();
                  if (proc.ExitCode != 0)
                  {
                      return $"Verification failed: {proc.StandardError.ReadToEnd()}";
                  }
                  return "Syntax check passed";
              }
              return "No checks defined for this file type";
          }
          catch (Exception e)
          {
              return $"Verification failed: {e.Message}";
          }
      }
      ```

      ```go Go
      func verifyChanges(filePath string) string {
      	// Prüfe bei Python-Dateien auf Syntaxfehler
      	if strings.HasSuffix(filePath, ".py") {
      		cmd := exec.Command("python3", "-m", "py_compile", filePath)
      		if out, err := cmd.CombinedOutput(); err != nil {
      			return fmt.Sprintf("Verification failed: %v: %s", err, out)
      		}
      		return "Syntax check passed"
      	}
      	return "No checks defined for this file type"
      }
      ```

      ```java Java
      static String verifyChanges(String filePath) {
          try {
              // Prüfe Python-Dateien auf Syntaxfehler
              if (filePath.endsWith(".py")) {
                  Process proc = new ProcessBuilder("python3", "-m", "py_compile", filePath)
                      .redirectErrorStream(true)
                      .start();
                  if (proc.waitFor() != 0) {
                      return "Verification failed: " + new String(proc.getInputStream().readAllBytes());
                  }
                  return "Syntax check passed";
              }
              return "No checks defined for this file type";
          } catch (IOException | InterruptedException e) {
              return "Verification failed: " + e.getMessage();
          }
      }
      ```

      ```php PHP
      function verify_changes(string $filePath): string
      {
          // Prüfe bei Python-Dateien auf Syntaxfehler
          if (str_ends_with($filePath, '.py')) {
              exec('python3 -m py_compile ' . escapeshellarg($filePath) . ' 2>&1', $output, $exitCode);
              if ($exitCode !== 0) {
                  return 'Verification failed: ' . implode("\n", $output);
              }
              return 'Syntax check passed';
          }
          return 'No checks defined for this file type';
      }
      ```

      ```ruby Ruby
      def verify_changes(file_path)
        # Prüfe Python-Dateien auf Syntaxfehler
        if file_path.end_with?(".py")
          if system("python3", "-m", "py_compile", file_path)
            "Syntax check passed"
          else
            "Verification failed: syntax error in #{file_path}"
          end
        else
          "No checks defined for this file type"
        end
      end
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

***

## Preise und Token-Nutzung

Das Text-Editor-Tool verwendet dieselbe Preisstruktur wie andere Tools, die mit Claude verwendet werden. Es folgt der standardmäßigen Preisgestaltung für Eingabe- und Ausgabe-Token, basierend auf dem Claude-Modell, das du verwendest.

Zusätzlich zu den Basis-Token werden für das Text-Editor-Tool die folgenden zusätzlichen Input-Token benötigt:

| Tool                                                                               | Zusätzliche Input-Token |
| ---------------------------------------------------------------------------------- | ----------------------- |
| `text_editor_20250728` (Claude 4.7 und neuere Modelle sowie Claude Mythos Preview) | 974 Token               |
| `text_editor_20250728` (Claude 4.6 und ältere Modelle)                             | 745 Token               |

Ausführlichere Informationen zu Tool-Preisen findest du unter [Preise für die Tool-Nutzung](https://platform.claude.com/docs/de/agents-and-tools/tool-use/overview#pricing).

## Das Text-Editor-Tool mit anderen Tools integrieren

Du kannst das Text-Editor-Tool zusammen mit anderen Claude-Tools verwenden. Achte beim Kombinieren von Tools darauf:

* Die Tool-Version an das verwendete Modell anzupassen
* Die zusätzliche Token-Nutzung für alle in deiner Anfrage enthaltenen Tools zu berücksichtigen

## Änderungsprotokoll

| Datum            | Version                | Änderungen                                                                                                                                                                                                                                                                                                                           |
| ---------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 28. Juli 2025    | `text_editor_20250728` | Veröffentlichung eines aktualisierten Text-Editor-Tools, das einige Probleme behebt und einen optionalen `max_characters`-Parameter hinzufügt. Ansonsten ist es identisch mit `text_editor_20250429`.                                                                                                                                |
| 29. April 2025   | `text_editor_20250429` | Veröffentlichung des Text-Editor-Tools für Claude 4. Diese Version entfernt den Befehl `undo_edit`, behält aber alle anderen Fähigkeiten bei. Der Tool-Name wurde aktualisiert, um seine auf `str_replace` basierende Architektur widerzuspiegeln.                                                                                   |
| 13. März 2025    | `text_editor_20250124` | Einführung einer eigenständigen Dokumentation für das Text-Editor-Tool. Diese Version ist für Claude Sonnet 3.7 optimiert, hat aber identische Fähigkeiten wie die vorherige Version.                                                                                                                                                |
| 22. Oktober 2024 | `text_editor_20241022` | Erstveröffentlichung des Text-Editor-Tools mit Claude Sonnet 3.5 (eingestellt; siehe [Modell-Abkündigungen](https://platform.claude.com/docs/de/about-claude/model-deprecations)). Bietet Fähigkeiten zum Anzeigen, Erstellen und Bearbeiten von Dateien über die Befehle `view`, `create`, `str_replace`, `insert` und `undo_edit`. |

## Nächste Schritte

Hier sind einige Ideen, wie du das Text-Editor-Tool noch bequemer und leistungsfähiger nutzen kannst:

* **Integration in deinen Entwicklungs-Workflow:** Baue das Text-Editor-Tool in deine Entwicklungstools oder deine IDE ein.
* **Ein Code-Review-System erstellen:** Lass Claude deinen Code überprüfen und Verbesserungen vornehmen.
* **Einen Debugging-Assistenten bauen:** Erstelle ein System, in dem Claude dir helfen kann, Probleme in deinem Code zu diagnostizieren und zu beheben.
* **Dateiformatkonvertierung implementieren:** Lass dir von Claude helfen, Dateien von einem Format in ein anderes zu konvertieren.
* **Dokumentation automatisieren:** Richte Workflows ein, mit denen Claude deinen Code automatisch dokumentiert.

Das Text-Editor-Tool ermöglicht es Claude, direkt mit deiner Codebasis zu arbeiten, und unterstützt Workflows vom Debugging bis zur automatisierten Dokumentation.

<CardGroup cols={3}>
  <Card title="Überblick über die Tool-Nutzung" icon="wrench" href="https://platform.claude.com/docs/de/agents-and-tools/tool-use/overview">
    Erfahre, wie du Tool-Workflows zur Verwendung mit Claude implementierst.
  </Card>

  <Card title="Bash-Tool" icon="terminal" href="https://platform.claude.com/docs/de/agents-and-tools/tool-use/bash-tool">
    Führe Shell-Befehle mit Claude aus.
  </Card>
</CardGroup>

## Verfügbarkeit

Texteditor-Tool ist auf allen Modellen verfügbar und für Zero Data Retention und HIPAA-Bereitschaft berechtigt.

### API-Unterstützung

#### [Messages API](https://platform.claude.com/docs/de/build-with-claude/working-with-messages)

* Verfügbarkeit: Verfügbar

| Status    | Cloud-Plattformen              |
| --------- | ------------------------------ |
| Verfügbar | Alle unterstützten Plattformen |

### Datenverarbeitung

[Übersicht über die Datenverarbeitung](https://platform.claude.com/docs/de/manage-claude/api-and-data-retention#feature-eligibility)

| Element | Zero Data Retention                                                                                                                                                 | HIPAA      |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| Status  | Berechtigt (ausgenommen: [Abgedeckte Modelle](https://platform.claude.com/docs/de/manage-claude/api-and-data-retention#model-specific-data-retention-requirements)) | Berechtigt |
| Details | Clientseitiges Tool, das in deiner Umgebung ausgeführt wird.                                                                                                        | —          |

Zutreffende Endpunkte:

* `/v1/messages` mit Tool `text_editor`
