---
title: Outil d'édition de texte
url: https://platform.claude.com/docs/fr/agents-and-tools/tool-use/text-editor-tool
description: Donnez à Claude l'outil d'éditeur de texte défini par Anthropic pour afficher, créer et modifier des fichiers, et gérez ses commandes view, str_replace, create et 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). Outil côté client exécuté dans votre environnement.
  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
    Claude Platform on AWS: stable
    Amazon Bedrock: stable
    Amazon Bedrock (InvokeModel): stable
    Claude Models on Google Cloud (Google managed): stable
    Microsoft Foundry: stable
---

Claude peut utiliser un outil d’éditeur de texte au schéma défini par Anthropic pour afficher et modifier des fichiers texte, vous aidant ainsi à déboguer, corriger et améliorer votre code ou d’autres documents texte. Cela permet à Claude d’interagir directement avec vos fichiers, en fournissant une assistance concrète plutôt que de simplement suggérer des modifications.

Pour la prise en charge des modèles, consultez la [référence des outils](https://platform.claude.com/docs/fr/agents-and-tools/tool-use/tool-reference).

## Quand utiliser l’outil d’éditeur de texte

Voici quelques exemples de situations où utiliser l’outil d’éditeur de texte :

* **Débogage de code :** Demandez à Claude d’identifier et de corriger les bugs dans votre code, des erreurs de syntaxe aux problèmes de logique.
* **Refactorisation de code :** Laissez Claude améliorer la structure, la lisibilité et les performances de votre code grâce à des modifications ciblées.
* **Génération de documentation :** Demandez à Claude d’ajouter des docstrings, des commentaires ou des fichiers README à votre base de code.
* **Création de tests :** Demandez à Claude de créer des tests unitaires pour votre code en fonction de son analyse de l’implémentation.

## Utiliser l’outil d’éditeur de texte

Fournissez l’outil d’éditeur de texte (nommé `str_replace_based_edit_tool`) à Claude en utilisant l’API Messages.

Vous pouvez éventuellement spécifier un paramètre `max_characters` pour contrôler la troncature lors de l’affichage de fichiers volumineux.

<Note>
  `max_characters` n’est compatible qu’avec `text_editor_20250728` et les versions ultérieures de l’outil d’éditeur de texte.
</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>

Utilisez l’outil d’éditeur de texte de la manière suivante :

<Steps>
  <Step title="Fournir à Claude l’outil d’éditeur de texte et un prompt utilisateur">
    * Incluez l’outil d’éditeur de texte dans votre requête API.
    * Fournissez un prompt utilisateur qui pourrait nécessiter l’examen ou la modification de fichiers, par exemple « Pouvez-vous corriger l’erreur de syntaxe dans mon code ? ».
  </Step>

  <Step title="Claude utilise l’outil pour examiner des fichiers ou des répertoires">
    * Claude évalue ce qu’il doit consulter et utilise la commande `view` pour examiner le contenu des fichiers ou lister le contenu des répertoires.
    * La réponse de l’API contient un bloc de contenu `tool_use` avec la commande `view`.
  </Step>

  <Step title="Exécuter la commande view et renvoyer les résultats">
    * Extrayez le chemin du fichier ou du répertoire de la requête d’utilisation d’outils de Claude.
    * Lisez le contenu du fichier ou listez le contenu du répertoire.
    * Si vous avez spécifié un paramètre `max_characters` dans la configuration de l’outil, tronquez le contenu du fichier à cette longueur.
    * Renvoyez les résultats à Claude en poursuivant la conversation avec un nouveau message `user` contenant un bloc de contenu `tool_result`.
  </Step>

  <Step title="Claude utilise l’outil pour modifier des fichiers">
    * Après avoir examiné le fichier ou le répertoire, Claude peut utiliser une commande telle que `str_replace` pour effectuer des modifications ou `insert` pour ajouter du texte à un numéro de ligne spécifique.
    * Si Claude utilise la commande `str_replace`, Claude construit une requête d’utilisation d’outils correctement formatée avec l’ancien texte et le nouveau texte qui doit le remplacer.
  </Step>

  <Step title="Effectuer la modification et renvoyer les résultats">
    * Extrayez le chemin du fichier, l’ancien texte et le nouveau texte de la requête d’utilisation d’outils de Claude.
    * Effectuez le remplacement du texte dans le fichier.
    * Renvoyez les résultats à Claude.
  </Step>

  <Step title="Claude fournit son analyse et son explication">
    * Après avoir examiné et éventuellement modifié les fichiers, Claude fournit une explication complète de ce qu’il a trouvé et des modifications qu’il a apportées.
  </Step>
</Steps>

### Commandes de l’outil d’éditeur de texte

L’outil d’éditeur de texte prend en charge plusieurs commandes pour afficher et modifier des fichiers :

#### view

La commande `view` permet à Claude d’examiner le contenu d’un fichier ou de lister le contenu d’un répertoire. Elle peut lire le fichier entier ou une plage de lignes spécifique.

Paramètres :

* `command` : Doit être `view`
* `path` : Le chemin du fichier ou du répertoire à afficher
* `view_range` (facultatif) : Un tableau de deux entiers spécifiant les numéros de ligne de début et de fin à afficher. Les numéros de ligne commencent à 1, et -1 pour la ligne de fin signifie lire jusqu’à la fin du fichier. Ce paramètre s’applique uniquement lors de l’affichage de fichiers, pas de répertoires.

<Accordion title="Exemples de commandes view">
  Exemple d’affichage d’un fichier :

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

  Exemple d’affichage d’un répertoire :

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

#### str\_replace

La commande `str_replace` permet à Claude de remplacer une chaîne spécifique dans un fichier par une nouvelle chaîne. Elle est utilisée pour effectuer des modifications précises.

Paramètres :

* `command` : Doit être `str_replace`
* `path` : Le chemin du fichier à modifier
* `old_str` : Le texte à remplacer (doit correspondre exactement, y compris les espaces et l’indentation)
* `new_str` : Le nouveau texte à insérer à la place de l’ancien texte

<Accordion title="Exemple de commande str_replace">
  ```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

La commande `create` permet à Claude de créer un nouveau fichier avec un contenu spécifié.

Paramètres :

* `command` : Doit être `create`
* `path` : Le chemin où le nouveau fichier doit être créé
* `file_text` : Le contenu à écrire dans le nouveau fichier

<Accordion title="Exemple de commande create">
  ```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

La commande `insert` permet à Claude d’insérer du texte à un emplacement spécifique dans un fichier.

Paramètres :

* `command` : Doit être `insert`
* `path` : Le chemin du fichier à modifier
* `insert_line` : Le numéro de ligne après lequel insérer le texte (0 pour le début du fichier)
* `insert_text` : Le texte à insérer

<Accordion title="Exemple de commande insert">
  ```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>

### Exemple : Corriger une erreur de syntaxe avec l’outil d’éditeur de texte

Cet exemple montre comment Claude utilise l’outil d’éditeur de texte pour corriger une erreur de syntaxe dans un fichier Python.

Tout d’abord, votre application fournit à Claude l’outil d’éditeur de texte et un prompt pour corriger une erreur de syntaxe :

<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 utilise d’abord l’outil d’éditeur de texte pour afficher le fichier :

```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"
      }
    }
  ]
}
```

Votre application doit ensuite lire le fichier et renvoyer son contenu à Claude :

<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>
  **Numéros de ligne**

  Dans l’exemple précédent, le résultat de l’outil `view` inclut le contenu du fichier avec des numéros de ligne ajoutés au début de chaque ligne (par exemple, « 1: def is\_prime(n): »). Les numéros de ligne ne sont pas obligatoires, mais ils sont essentiels pour utiliser avec succès le paramètre `view_range` afin d’examiner des sections spécifiques de fichiers et le paramètre `insert_line` afin d’ajouter du contenu à des emplacements précis.
</Tip>

Claude identifie l’erreur de syntaxe et utilise la commande `str_replace` pour la corriger :

```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):"
      }
    }
  ]
}
```

Votre application doit ensuite effectuer la modification et renvoyer le résultat :

<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:
    # Messages précédents...
    - 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=[
          # Messages précédents...
          {
              "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: [
      // Messages précédents...
      {
        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 =
          [
              // Messages précédents...
              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{
  		// Messages précédents...
  		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())
      // Les messages précédents iraient ici
      .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: [
          // Messages précédents...
          [
              '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: [
      # Messages précédents...
      {
        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>

Enfin, Claude fournit une explication complète de la correction :

````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."
    }
  ]
}
````

## Implémenter l’outil d’éditeur de texte

L’outil d’éditeur de texte est implémenté comme un outil sans schéma. Lorsque vous utilisez cet outil, vous n’avez pas besoin de fournir un schéma d’entrée comme avec les autres outils ; le schéma est intégré au modèle de Claude et ne peut pas être modifié.

Le type d’outil est `type: "text_editor_20250728"` pour Claude 4 et les modèles ultérieurs.

<Steps>
  <Step title="Initialiser votre implémentation de l’éditeur">
    Créez des fonctions utilitaires pour gérer les opérations sur les fichiers telles que la lecture, l’écriture et la modification de fichiers. Envisagez d’implémenter une fonctionnalité de sauvegarde pour récupérer en cas d’erreur.
  </Step>

  <Step title="Gérer les appels à l’outil d’éditeur">
    Créez une fonction qui traite les appels d’outils de Claude en fonction du type de commande :

    <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":
                  # Lire et renvoyer le contenu du fichier
                  pass
              case "str_replace":
                  # Remplacer du texte dans le fichier
                  pass
              case "create":
                  # Créer un nouveau fichier
                  pass
              case "insert":
                  # Insérer du texte à l'emplacement indiqué
                  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":
            // Lire et renvoyer le contenu du fichier
            break;
          case "str_replace":
            // Remplacer du texte dans le fichier
            break;
          case "create":
            // Créer un nouveau fichier
            break;
          case "insert":
            // Insérer du texte à l'emplacement indiqué
            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")
          {
              // Lire et renvoyer le contenu du fichier.
          }
          else if (command == "str_replace")
          {
              // Remplacer du texte dans le fichier.
          }
          else if (command == "create")
          {
              // Créer un nouveau fichier.
          }
          else if (command == "insert")
          {
              // Insérer du texte à l'emplacement indiqué.
          }
          return "";
      }
      ```

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

      	switch command {
      	case "view":
      		// Lire et renvoyer le contenu du fichier
      	case "str_replace":
      		// Remplacer du texte dans le fichier
      	case "create":
      		// Créer un nouveau fichier
      	case "insert":
      		// Insérer du texte à l'emplacement indiqué
      	}
      	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")) {
              // Lire et renvoyer le contenu du fichier
          } else if (command.equals("str_replace")) {
              // Remplacer du texte dans le fichier
          } else if (command.equals("create")) {
              // Créer un nouveau fichier
          } else if (command.equals("insert")) {
              // Insérer du texte à l'emplacement indiqué
          }
      }
      ```

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

          if ($command === 'view') {
              // Lire et renvoyer le contenu du fichier
          } elseif ($command === 'str_replace') {
              // Remplacer du texte dans le fichier
          } elseif ($command === 'create') {
              // Créer un nouveau fichier
          } elseif ($command === 'insert') {
              // Insérer du texte à l'emplacement indiqué
          }
          return '';
      }
      ```

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

        case command
        when "view"
          # Lire et renvoyer le contenu du fichier
        when "str_replace"
          # Remplacer du texte dans le fichier
        when "create"
          # Créer un nouveau fichier
        when "insert"
          # Insérer du texte à l'emplacement indiqué
        end
      end
      ```
    </CodeGroup>
  </Step>

  <Step title="Implémenter des mesures de sécurité">
    Ajoutez des validations et des contrôles de sécurité :

    * Validez les chemins de fichiers pour empêcher la traversée de répertoires
    * Créez des sauvegardes avant d’effectuer des modifications
    * Gérez les erreurs de manière appropriée
    * Implémentez des vérifications des autorisations
  </Step>

  <Step title="Traiter les réponses de Claude">
    Extrayez et gérez les appels d’outils à partir des réponses de Claude :

    <CodeGroup exclude="shell">
      ```python Python
      # Traiter l'utilisation d'outils dans la réponse de Claude
      for content in response.content:
          if content.type == "tool_use":
              # Exécuter l'outil en fonction de la commande
              result = handle_editor_tool(content)

              # Renvoyer le résultat à Claude
              tool_result = {
                  "type": "tool_result",
                  "tool_use_id": content.id,
                  "content": result,
              }
      ```

      ```typescript TypeScript
      // Traiter l'utilisation d'outils dans la réponse de Claude
      for (const block of response.content) {
        if (block.type === "tool_use") {
          // Exécuter l'outil selon la commande
          const result = handleEditorTool(block);

          // Renvoyer le résultat à Claude
          const toolResult = {
            type: "tool_result",
            tool_use_id: block.id,
            content: result
          };
        }
      }
      ```

      ```csharp C#
      // Traiter l'utilisation d'outils dans la réponse de Claude.
      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
      // Traiter l'utilisation d'outils dans la réponse de Claude.
      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
      // Traiter l'utilisation d'outils dans la réponse de Claude
      for (var block : response.content()) {
          if (block.type().equals("tool_use")) {
              // Exécuter l'outil en fonction de la commande
              var result = handleEditorTool(block);

              // Renvoyer le résultat à Claude
              var toolResult = Map.of(
                  "type", "tool_result",
                  "tool_use_id", block.id(),
                  "content", result
              );
          }
      }
      ```

      ```php PHP
      // Traiter l'utilisation d'outils dans la réponse de Claude
      foreach ($response->content as $block) {
          if ($block->type === 'tool_use') {
              // Exécuter l'outil selon la commande
              $result = handle_editor_tool($block->input);

              // Renvoyer le résultat à Claude
              $toolResult = [
                  'type' => 'tool_result',
                  'tool_use_id' => $block->id,
                  'content' => $result,
              ];
          }
      }
      ```

      ```ruby Ruby
      # Traiter l'utilisation d'outils dans la réponse de Claude
      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>
  Lors de l’implémentation de l’outil d’éditeur de texte, gardez à l’esprit les points suivants :

  1. **Sécurité :** L’outil a accès à votre système de fichiers local, implémentez donc des mesures de sécurité appropriées.
  2. **Sauvegarde :** Créez toujours des sauvegardes avant d’autoriser des modifications sur des fichiers importants.
  3. **Validation :** Validez toutes les entrées pour éviter les modifications involontaires.
  4. **Correspondance unique :** Assurez-vous que les remplacements correspondent à exactement un emplacement pour éviter les modifications involontaires.
</Warning>

### Gérer les erreurs

Lors de l’utilisation de l’outil d’éditeur de texte, diverses erreurs peuvent survenir. Voici des conseils pour les gérer :

<AccordionGroup>
  <Accordion title="Fichier introuvable">
    Si Claude tente d’afficher ou de modifier un fichier qui n’existe pas, renvoyez un message d’erreur approprié dans le `tool_result` :

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

  <Accordion title="Correspondances multiples pour le remplacement">
    Si la commande `str_replace` de Claude correspond à plusieurs emplacements dans le fichier, renvoyez un message d’erreur approprié :

    ```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="Aucune correspondance pour le remplacement">
    Si la commande `str_replace` de Claude ne correspond à aucun texte dans le fichier, renvoyez un message d’erreur approprié :

    ```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="Erreurs d’autorisation">
    En cas de problèmes d’autorisation lors de la création, de la lecture ou de la modification de fichiers, renvoyez un message d’erreur approprié :

    ```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>

### Suivre les bonnes pratiques d’implémentation

<AccordionGroup>
  <Accordion title="Fournir un contexte clair">
    Lorsque vous demandez à Claude de corriger ou de modifier du code, soyez précis quant aux fichiers à examiner ou aux problèmes à résoudre. Un contexte clair aide Claude à identifier les bons fichiers et à effectuer les modifications appropriées.

    **Prompt moins utile :** « Pouvez-vous corriger mon code ? »

    **Meilleur prompt :** « Il y a une erreur de syntaxe dans mon fichier primes.py qui l’empêche de s’exécuter. Pouvez-vous la corriger ? »
  </Accordion>

  <Accordion title="Être explicite sur les chemins de fichiers">
    Spécifiez clairement les chemins de fichiers lorsque nécessaire, surtout si vous travaillez avec plusieurs fichiers ou des fichiers situés dans différents répertoires.

    **Prompt moins utile :** « Examinez mon fichier d’utilitaires »

    **Meilleur prompt :** « Pouvez-vous vérifier mon fichier utils/helpers.py pour détecter d’éventuels problèmes de performance ? »
  </Accordion>

  <Accordion title="Créer des sauvegardes avant la modification">
    Implémentez un système de sauvegarde dans votre application qui crée des copies des fichiers avant d’autoriser Claude à les modifier, en particulier pour le code important ou de production.

    <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 {
          // Le fichier n'existe pas ; rien à sauvegarder.
        }
      }
      ```

      ```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="Gérer avec soin le remplacement de texte unique">
    La commande `str_replace` nécessite une correspondance exacte pour le texte à remplacer. Votre application doit s’assurer qu’il existe exactement une correspondance pour l’ancien texte ou fournir des messages d’erreur appropriés.

    <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="Vérifier les modifications">
    Après que Claude a modifié un fichier, vérifiez les modifications en exécutant des tests ou en vous assurant que le code fonctionne toujours comme prévu.

    <CodeGroup exclude="shell">
      ```python Python
      def verify_changes(file_path):
          """Run tests or checks after making changes."""
          try:
              # Pour les fichiers Python, vérifier les erreurs de syntaxe.
              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 {
          // Pour les fichiers Python, vérifier les erreurs de syntaxe.
          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
          {
              // Pour les fichiers Python, vérifier les erreurs de syntaxe.
              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 {
      	// Pour les fichiers Python, vérifier les erreurs de syntaxe.
      	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 {
              // Pour les fichiers Python, vérifier les erreurs de syntaxe.
              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
      {
          // Pour les fichiers Python, vérifier les erreurs de syntaxe.
          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)
        # Pour les fichiers Python, vérifier les erreurs de syntaxe.
        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>

***

## Tarification et utilisation des tokens

L’outil d’édition de texte utilise la même structure tarifaire que les autres outils utilisés avec Claude. Il suit la tarification standard des tokens d’entrée et de sortie en fonction du modèle Claude que vous utilisez.

En plus des tokens de base, les tokens d’entrée supplémentaires suivants sont nécessaires pour l’outil d’édition de texte :

| Outil                                                                                     | Tokens d’entrée supplémentaires |
| ----------------------------------------------------------------------------------------- | ------------------------------- |
| `text_editor_20250728` (modèles Claude 4.7 et ultérieurs ainsi que Claude Mythos Preview) | 974 tokens                      |
| `text_editor_20250728` (modèles Claude 4.6 et antérieurs)                                 | 745 tokens                      |

Pour des informations plus détaillées sur la tarification des outils, consultez [Tarification de l’utilisation d’outils](https://platform.claude.com/docs/fr/agents-and-tools/tool-use/overview#pricing).

## Intégrer l’outil d’éditeur de texte avec d’autres outils

Vous pouvez utiliser l’outil d’éditeur de texte conjointement avec d’autres outils de Claude. Lorsque vous combinez des outils, assurez-vous de :

* Faire correspondre la version de l’outil avec le modèle que vous utilisez
* Tenir compte de l’utilisation supplémentaire de tokens pour tous les outils inclus dans votre requête

## Journal des modifications

| Date            | Version                | Modifications                                                                                                                                                                                                                                                                                                                                         |
| --------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 28 juillet 2025 | `text_editor_20250728` | Publication d’un outil d’éditeur de texte mis à jour qui corrige certains problèmes et ajoute un paramètre facultatif `max_characters`. Il est par ailleurs identique à `text_editor_20250429`.                                                                                                                                                       |
| 29 avril 2025   | `text_editor_20250429` | Publication de l’outil d’éditeur de texte pour Claude 4. Cette version supprime la commande `undo_edit` mais conserve toutes les autres fonctionnalités. Le nom de l’outil a été mis à jour pour refléter son architecture basée sur `str_replace`.                                                                                                   |
| 13 mars 2025    | `text_editor_20250124` | Introduction d’une documentation autonome pour l’outil d’éditeur de texte. Cette version est optimisée pour Claude Sonnet 3.7 mais possède des fonctionnalités identiques à la version précédente.                                                                                                                                                    |
| 22 octobre 2024 | `text_editor_20241022` | Publication initiale de l’outil d’éditeur de texte avec Claude Sonnet 3.5 (retiré ; consultez [Dépréciations de modèles](https://platform.claude.com/docs/fr/about-claude/model-deprecations)). Fournit des fonctionnalités pour afficher, créer et modifier des fichiers via les commandes `view`, `create`, `str_replace`, `insert` et `undo_edit`. |

## Prochaines étapes

Voici quelques idées pour utiliser l’outil d’éditeur de texte de manière plus pratique et plus puissante :

* **Intégrer à votre flux de travail de développement :** Intégrez l’outil d’éditeur de texte à vos outils de développement ou à votre IDE.
* **Créer un système de revue de code :** Demandez à Claude de relire votre code et d’y apporter des améliorations.
* **Construire un assistant de débogage :** Créez un système dans lequel Claude peut vous aider à diagnostiquer et corriger les problèmes de votre code.
* **Implémenter la conversion de formats de fichiers :** Laissez Claude vous aider à convertir des fichiers d’un format à un autre.
* **Automatiser la documentation :** Mettez en place des flux de travail permettant à Claude de documenter automatiquement votre code.

L’outil d’éditeur de texte permet à Claude de travailler directement avec votre base de code, prenant en charge des flux de travail allant du débogage à la documentation automatisée.

<CardGroup cols={3}>
  <Card title="Présentation de l’utilisation d’outils" icon="wrench" href="https://platform.claude.com/docs/fr/agents-and-tools/tool-use/overview">
    Découvrez comment implémenter des flux de travail d’outils à utiliser avec Claude.
  </Card>

  <Card title="Outil Bash" icon="terminal" href="https://platform.claude.com/docs/fr/agents-and-tools/tool-use/bash-tool">
    Exécutez des commandes shell avec Claude.
  </Card>
</CardGroup>

## Disponibilité

Outil d’édition de texte est disponible sur tous les modèles et éligible aux dispositifs suivants : zéro conservation des données et préparation HIPAA.

### Prise en charge de l’API

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

* Disponibilité : Disponible

| Statut     | Plateformes cloud                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Disponible | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/fr/build-with-claude/claude-platform-on-aws), [Amazon Bedrock](https://platform.claude.com/docs/fr/build-with-claude/claude-in-amazon-bedrock), [Amazon Bedrock (InvokeModel)](https://platform.claude.com/docs/fr/build-with-claude/claude-on-amazon-bedrock-legacy), [Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/fr/build-with-claude/claude-models-on-google-cloud/google-managed), [Microsoft Foundry](https://platform.claude.com/docs/fr/build-with-claude/claude-in-microsoft-foundry) |

### Traitement des données

[Présentation du traitement des données](https://platform.claude.com/docs/fr/manage-claude/api-and-data-retention#feature-eligibility)

| Élément | Zéro conservation des données                                                                                                                             | HIPAA    |
| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| Statut  | Éligible (exclut [Modèles couverts](https://platform.claude.com/docs/fr/manage-claude/api-and-data-retention#model-specific-data-retention-requirements)) | Éligible |
| Détails | Outil côté client exécuté dans votre environnement.                                                                                                       | —        |

Points de terminaison concernés :

* `/v1/messages` avec l’outil `text_editor`
