---
title: Motivi di arresto e fallback
url: https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons
description: Scopri cosa significa ciascun valore di stop_reason e come gestire il troncamento, l'uso degli strumenti, i turni in pausa e i rifiuti nella tua applicazione.
---

Ogni risposta della Messages API include un campo [`stop_reason`](https://platform.claude.com/docs/it/api/messages/create#message.stop_reason) che ti indica perché Claude ha smesso di generare. Controlla questo campo per decidere se usare la risposta così com’è, continuare la conversazione, riprovare o ripiegare su un altro modello.

Per lo schema completo della risposta, consulta il [riferimento della Messages API](https://platform.claude.com/docs/it/api/messages/create).

## Riferimento rapido

| Valore                                                                                                                                       | Quando si verifica                                                     | Cosa fare                                                                                                                                                                  |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`end_turn`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#end-turn)                                           | Claude ha completato la sua risposta in modo naturale.                 | Usa la risposta.                                                                                                                                                           |
| [`max_tokens`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#max-tokens)                                       | La risposta ha raggiunto il tuo limite `max_tokens`.                   | Aumenta `max_tokens` oppure [continua la risposta](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#ensuring-complete-responses).               |
| [`stop_sequence`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#stop-sequence)                                 | Claude ha emesso una delle tue `stop_sequences`.                       | Leggi `stop_sequence` per vedere quale si è attivata.                                                                                                                      |
| [`tool_use`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#tool-use)                                           | Claude sta chiamando uno strumento.                                    | Esegui lo strumento e restituisci il risultato. Una chiamata a uno strumento server a cui manca ancora il blocco di risultato viene completata in una risposta successiva. |
| [`pause_turn`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#pause-turn)                                       | Un ciclo di strumenti server ha raggiunto il suo limite di iterazioni. | Rimanda indietro il contenuto dell’assistente per continuare.                                                                                                              |
| [`refusal`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#refusal)                                             | Claude ha rifiutato di rispondere.                                     | Leggi `stop_details` e [riprova su un modello di fallback](https://platform.claude.com/docs/it/build-with-claude/refusals-and-fallback).                                   |
| [`model_context_window_exceeded`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#model-context-window-exceeded) | La risposta ha riempito la finestra di contesto del modello.           | Tratta la risposta come troncata.                                                                                                                                          |

## Il campo stop\_reason

Il campo `stop_reason` fa parte di ogni risposta riuscita della Messages API. A differenza degli errori, che indicano fallimenti nell’elaborazione della tua richiesta, `stop_reason` ti indica perché Claude ha completato la generazione della sua risposta.

```json Example response
{
  "id": "msg_01234",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Here's the answer to your question..."
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "stop_details": null,
  "usage": {
    "input_tokens": 100,
    "output_tokens": 50
  }
}
```

## Valori del motivo di arresto

### end\_turn

Il motivo di arresto più comune. Indica che Claude ha completato la sua risposta in modo naturale.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello!"}]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello!"}'
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello!"}],
  )
  if response.stop_reason == "end_turn":
      # Elabora la risposta completa
      for block in response.content:
          if block.type == "text":
              print(block.text)
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello!" }]
  });

  if (response.stop_reason === "end_turn") {
    // Elabora la risposta completa
    const textBlock = response.content.find((block) => block.type === "text");
    console.log(textBlock?.text);
  }
  ```

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

  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new UserMessageParam { Content = "Hello!" }]
  });

  if (response.StopReason == "end_turn")
  {
      // Elabora la risposta completa
      foreach (var block in response.Content)
      {
          if (block.TryPickText(out var textBlock))
          {
              Console.WriteLine(textBlock.Text);
          }
      }
  }
  ```

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello!")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  if response.StopReason == "end_turn" {
  	// Elabora la risposta completa
  	for _, block := range response.Content {
  		if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  			fmt.Println(textBlock.Text)
  		}
  	}
  }
  ```

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

  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addUserMessage("Hello!")
          .build()
  );

  if (response.stopReason().map(StopReason.END_TURN::equals).orElse(false)) {
      // Elabora la risposta completa
      response.content().stream()
          .flatMap(block -> block.text().stream())
          .forEach(textBlock -> IO.println(textBlock.text()));
  }
  ```

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

  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello!']],
      model: 'claude-opus-5-5',
  );

  if ($response->stopReason === 'end_turn') {
      // Elabora la risposta completa
      foreach ($response->content as $block) {
          if ($block->type === 'text') {
              echo $block->text, PHP_EOL;
          }
      }
  }
  ```

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

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello!" }]
  )

  if response.stop_reason == :end_turn
    # Elabora la risposta completa
    response.content.each do |block|
      puts block.text if block.type == :text
    end
  end
  ```
</CodeGroup>

<Accordion title="Risposte vuote con end_turn">
  A volte Claude restituisce una risposta vuota (esattamente 2–3 token senza contenuto) con `stop_reason: "end_turn"`. Questo si verifica tipicamente quando Claude determina che il turno dell’assistente è completo, in particolare dopo i risultati degli strumenti.

  **Cause comuni:**

  * Aggiungere blocchi di testo immediatamente dopo i risultati degli strumenti (la cronologia mostra quindi testo dell’utente dopo ogni risultato di strumento, quindi Claude termina il suo turno per seguire quello schema)
  * Rimandare indietro la risposta completata di Claude senza aggiungere nulla (Claude ha già stabilito di aver finito, quindi rimarrà tale)

  **Come prevenire le risposte vuote:**

  <CodeGroup exclude="shell">
    ```python Python
    # ERRATO: aggiunta di testo subito dopo tool_result
    messages = [
        {"role": "user", "content": "Calculate the sum of 1234 and 5678"},
        {
            "role": "assistant",
            "content": [
                {
                    "type": "tool_use",
                    "id": "toolu_123",
                    "name": "calculator",
                    "input": {"operation": "add", "a": 1234, "b": 5678},
                }
            ],
        },
        {
            "role": "user",
            "content": [
                {"type": "tool_result", "tool_use_id": "toolu_123", "content": "6912"},
                {
                    "type": "text",
                    "text": "Here's the result",  # Don't add text after tool_result
                },
            ],
        },
    ]

    # CORRETTO: invia i risultati degli strumenti direttamente senza testo aggiuntivo
    messages = [
        {"role": "user", "content": "Calculate the sum of 1234 and 5678"},
        {
            "role": "assistant",
            "content": [
                {
                    "type": "tool_use",
                    "id": "toolu_123",
                    "name": "calculator",
                    "input": {"operation": "add", "a": 1234, "b": 5678},
                }
            ],
        },
        {
            "role": "user",
            "content": [
                {"type": "tool_result", "tool_use_id": "toolu_123", "content": "6912"}
            ],
        },  # Only the tool_result, no additional text
    ]
    ```

    ```typescript TypeScript
    // ERRATO: aggiungere testo subito dopo tool_result
    let messages: Anthropic.MessageParam[] = [
      { role: "user", content: "Calculate the sum of 1234 and 5678" },
      {
        role: "assistant",
        content: [
          {
            type: "tool_use",
            id: "toolu_123",
            name: "calculator",
            input: { operation: "add", a: 1234, b: 5678 }
          }
        ]
      },
      {
        role: "user",
        content: [
          { type: "tool_result", tool_use_id: "toolu_123", content: "6912" },
          { type: "text", text: "Here's the result" } // Don't add text after tool_result
        ]
      }
    ];

    // CORRETTO: invia i risultati degli strumenti direttamente senza testo aggiuntivo
    messages = [
      { role: "user", content: "Calculate the sum of 1234 and 5678" },
      {
        role: "assistant",
        content: [
          {
            type: "tool_use",
            id: "toolu_123",
            name: "calculator",
            input: { operation: "add", a: 1234, b: 5678 }
          }
        ]
      },
      {
        role: "user",
        // Solo il tool_result, nessun testo aggiuntivo
        content: [{ type: "tool_result", tool_use_id: "toolu_123", content: "6912" }]
      }
    ];
    ```

    ```csharp C#
    using System.Text.Json;
    using Anthropic.Models.Messages;

    var input = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(
        """{"operation":"add","a":1234,"b":5678}"""
    )!;

    // ERRATO: aggiungere testo subito dopo tool_result
    List<MessageParam> messages =
    [
        new UserMessageParam { Content = "Calculate the sum of 1234 and 5678" },
        new AssistantMessageParam
        {
            Content = new List<ContentBlockParam>
            {
                new ToolUseBlockParam { ID = "toolu_123", Name = "calculator", Input = input }
            }
        },
        new UserMessageParam
        {
            Content = new List<ContentBlockParam>
            {
                new ToolResultBlockParam { ToolUseID = "toolu_123", Content = "6912" },
                new TextBlockParam { Text = "Here's the result" } // Don't add text after tool_result
            }
        }
    ];

    // CORRETTO: invia i risultati degli strumenti direttamente senza testo aggiuntivo
    messages =
    [
        new UserMessageParam { Content = "Calculate the sum of 1234 and 5678" },
        new AssistantMessageParam
        {
            Content = new List<ContentBlockParam>
            {
                new ToolUseBlockParam { ID = "toolu_123", Name = "calculator", Input = input }
            }
        },
        new UserMessageParam
        {
            // Solo il tool_result, nessun testo aggiuntivo
            Content = new List<ContentBlockParam>
            {
                new ToolResultBlockParam { ToolUseID = "toolu_123", Content = "6912" }
            }
        }
    ];
    ```

    ```go Go
    input := map[string]any{"operation": "add", "a": 1234, "b": 5678}

    // ERRATO: aggiungere testo subito dopo tool_result
    messages := []anthropic.MessageParam{
    	anthropic.NewUserMessage(anthropic.NewTextBlock("Calculate the sum of 1234 and 5678")),
    	anthropic.NewAssistantMessage(
    		anthropic.NewToolUseBlock("toolu_123", input, "calculator"),
    	),
    	anthropic.NewUserMessage(
    		anthropic.NewToolResultBlock("toolu_123", "6912", false),
    		anthropic.NewTextBlock("Here's the result"), // Don't add text after tool_result
    	),
    }

    // CORRETTO: invia i risultati degli strumenti direttamente senza testo aggiuntivo
    messages = []anthropic.MessageParam{
    	anthropic.NewUserMessage(anthropic.NewTextBlock("Calculate the sum of 1234 and 5678")),
    	anthropic.NewAssistantMessage(
    		anthropic.NewToolUseBlock("toolu_123", input, "calculator"),
    	),
    	// Solo il tool_result, nessun testo aggiuntivo
    	anthropic.NewUserMessage(
    		anthropic.NewToolResultBlock("toolu_123", "6912", false),
    	),
    }
    ```

    ```java Java
    ToolUseBlockParam toolUse = ToolUseBlockParam.builder()
        .id("toolu_123")
        .name("calculator")
        .input(ToolUseBlockParam.Input.builder()
            .putAdditionalProperty("operation", JsonValue.from("add"))
            .putAdditionalProperty("a", JsonValue.from(1234))
            .putAdditionalProperty("b", JsonValue.from(5678))
            .build())
        .build();

    // ERRATO: aggiungere testo subito dopo tool_result
    List<MessageParam> messages = List.of(
        MessageParam.ofUser("Calculate the sum of 1234 and 5678"),
        MessageParam.ofAssistantOfContentBlockParams(List.of(ContentBlockParam.ofToolUse(toolUse))),
        MessageParam.ofUserOfContentBlockParams(List.of(
            ContentBlockParam.ofToolResult(
                ToolResultBlockParam.builder()
                    .toolUseId("toolu_123")
                    .content("6912")
                    .build()),
            // Non aggiungere testo dopo tool_result
            ContentBlockParam.ofText(TextBlockParam.builder()
                .text("Here's the result")
                .build())
        ))
    );

    // CORRETTO: invia i risultati degli strumenti direttamente senza testo aggiuntivo
    messages = List.of(
        MessageParam.ofUser("Calculate the sum of 1234 and 5678"),
        MessageParam.ofAssistantOfContentBlockParams(List.of(ContentBlockParam.ofToolUse(toolUse))),
        // Solo il tool_result, nessun testo aggiuntivo
        MessageParam.ofUserOfContentBlockParams(List.of(
            ContentBlockParam.ofToolResult(
                ToolResultBlockParam.builder()
                    .toolUseId("toolu_123")
                    .content("6912")
                    .build())
        ))
    );
    ```

    ```php PHP
    // ERRATO: aggiunta di testo subito dopo tool_result
    $messages = [
        ['role' => 'user', 'content' => 'Calculate the sum of 1234 and 5678'],
        [
            'role' => 'assistant',
            'content' => [
                [
                    'type' => 'tool_use',
                    'id' => 'toolu_123',
                    'name' => 'calculator',
                    'input' => ['operation' => 'add', 'a' => 1234, 'b' => 5678],
                ],
            ],
        ],
        [
            'role' => 'user',
            'content' => [
                ['type' => 'tool_result', 'tool_use_id' => 'toolu_123', 'content' => '6912'],
                // Non aggiungere testo dopo tool_result
                ['type' => 'text', 'text' => "Here's the result"],
            ],
        ],
    ];

    // CORRETTO: invia i risultati degli strumenti direttamente senza testo aggiuntivo
    $messages = [
        ['role' => 'user', 'content' => 'Calculate the sum of 1234 and 5678'],
        [
            'role' => 'assistant',
            'content' => [
                [
                    'type' => 'tool_use',
                    'id' => 'toolu_123',
                    'name' => 'calculator',
                    'input' => ['operation' => 'add', 'a' => 1234, 'b' => 5678],
                ],
            ],
        ],
        [
            'role' => 'user',
            // Solo il tool_result, nessun testo aggiuntivo
            'content' => [
                ['type' => 'tool_result', 'tool_use_id' => 'toolu_123', 'content' => '6912'],
            ],
        ],
    ];
    ```

    ```ruby Ruby
    # ERRATO: aggiunta di testo subito dopo tool_result
    messages = [
      { role: "user", content: "Calculate the sum of 1234 and 5678" },
      {
        role: "assistant",
        content: [
          {
            type: "tool_use",
            id: "toolu_123",
            name: "calculator",
            input: { operation: "add", a: 1234, b: 5678 }
          }
        ]
      },
      {
        role: "user",
        content: [
          { type: "tool_result", tool_use_id: "toolu_123", content: "6912" },
          # Non aggiungere testo dopo tool_result
          { type: "text", text: "Here's the result" }
        ]
      }
    ]

    # CORRETTO: invia i risultati degli strumenti direttamente senza testo aggiuntivo
    messages = [
      { role: "user", content: "Calculate the sum of 1234 and 5678" },
      {
        role: "assistant",
        content: [
          {
            type: "tool_use",
            id: "toolu_123",
            name: "calculator",
            input: { operation: "add", a: 1234, b: 5678 }
          }
        ]
      },
      {
        role: "user",
        # Solo il tool_result, nessun testo aggiuntivo
        content: [
          { type: "tool_result", tool_use_id: "toolu_123", content: "6912" }
        ]
      }
    ]
    ```
  </CodeGroup>

  Se ottieni ancora risposte vuote dopo aver corretto la struttura dei messaggi, aggiungi un prompt di continuazione in un nuovo messaggio utente invece di riprovare con la risposta vuota:

  <CodeGroup exclude="shell">
    ```python Python
    def handle_empty_response(client, messages):
        response = client.messages.create(
            model="claude-opus-5-5", max_tokens=1024, messages=messages
        )

        # Verifica se la risposta è vuota
        if response.stop_reason == "end_turn" and not response.content:
            # ERRATO: non limitarti a riprovare con la risposta vuota
            # Non funzionerà perché Claude ha già deciso di aver finito

            # CORRETTO: aggiungi un prompt di continuazione in un NUOVO messaggio utente
            messages.append({"role": "user", "content": "Please continue"})

            response = client.messages.create(
                model="claude-opus-5-5", max_tokens=1024, messages=messages
            )

        return response
    ```

    ```typescript TypeScript
    async function handleEmptyResponse(
      client: Anthropic,
      messages: Anthropic.MessageParam[]
    ): Promise<Anthropic.Message> {
      let response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages
      });

      // Verifica se la risposta è vuota
      if (response.stop_reason === "end_turn" && response.content.length === 0) {
        // ERRATO: non limitarti a riprovare con la risposta vuota
        // Non funzionerà perché Claude ha già deciso di aver finito

        // CORRETTO: aggiungi un prompt di continuazione in un NUOVO messaggio utente
        messages.push({ role: "user", content: "Please continue" });

        response = await client.messages.create({
          model: "claude-opus-5-5",
          max_tokens: 1024,
          messages
        });
      }

      return response;
    }
    ```

    ```csharp C#
    static async Task<Message> HandleEmptyResponse(AnthropicClient client, List<MessageParam> messages)
    {
        var response = await client.Messages.Create(new MessageCreateParams
        {
            Model = Model.ClaudeOpus5_5,
            MaxTokens = 1024,
            Messages = messages
        });

        // Verifica se la risposta è vuota
        if (response.StopReason == "end_turn" && response.Content.Count == 0)
        {
            // CORRETTO: aggiungi un prompt di continuazione in un NUOVO messaggio utente
            messages.Add(new UserMessageParam { Content = "Please continue" });

            response = await client.Messages.Create(new MessageCreateParams
            {
                Model = Model.ClaudeOpus5_5,
                MaxTokens = 1024,
                Messages = messages
            });
        }

        return response;
    }
    ```

    ```go Go
    func handleEmptyResponse(client anthropic.Client, messages []anthropic.MessageParam) (*anthropic.Message, error) {
    	response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    		Model:     anthropic.ModelClaudeOpus5_5,
    		MaxTokens: 1024,
    		Messages:  messages,
    	})
    	if err != nil {
    		return nil, err
    	}

    	// Verifica se la risposta è vuota
    	if response.StopReason == "end_turn" && len(response.Content) == 0 {
    		// CORRETTO: aggiungi un prompt di continuazione in un NUOVO messaggio utente
    		messages = append(messages, anthropic.NewUserMessage(anthropic.NewTextBlock("Please continue")))

    		response, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    			Model:     anthropic.ModelClaudeOpus5_5,
    			MaxTokens: 1024,
    			Messages:  messages,
    		})
    		if err != nil {
    			return nil, err
    		}
    	}

    	return response, nil
    }
    ```

    ```java Java
    static Message handleEmptyResponse(AnthropicClient client, List<MessageParam> messages) {
        Message response = client.messages().create(
            MessageCreateParams.builder()
                .model(Model.CLAUDE_OPUS_5_5)
                .maxTokens(1024L)
                .messages(messages)
                .build()
        );

        // Verifica se la risposta è vuota
        boolean isEndTurn = response.stopReason().map(StopReason.END_TURN::equals).orElse(false);
        if (isEndTurn && response.content().isEmpty()) {
            // CORRETTO: aggiungi un prompt di continuazione in un NUOVO messaggio utente
            List<MessageParam> extended = new ArrayList<>(messages);
            extended.add(MessageParam.ofUser("Please continue"));

            response = client.messages().create(
                MessageCreateParams.builder()
                    .model(Model.CLAUDE_OPUS_5_5)
                    .maxTokens(1024L)
                    .messages(extended)
                    .build()
            );
        }

        return response;
    }
    ```

    ```php PHP
    function handle_empty_response(Client $client, array $messages)
    {
        $response = $client->messages->create(
            maxTokens: 1024,
            messages: $messages,
            model: 'claude-opus-5-5',
        );

        // Verifica se la risposta è vuota
        if ($response->stopReason === 'end_turn' && count($response->content) === 0) {
            // CORRETTO: aggiungi un prompt di continuazione in un NUOVO messaggio utente
            $messages[] = ['role' => 'user', 'content' => 'Please continue'];

            $response = $client->messages->create(
                maxTokens: 1024,
                messages: $messages,
                model: 'claude-opus-5-5',
            );
        }

        return $response;
    }
    ```

    ```ruby Ruby
    def handle_empty_response(client, messages)
      response = client.messages.create(
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages: messages
      )

      # Verifica se la risposta è vuota
      if response.stop_reason == :end_turn && response.content.empty?
        # CORRETTO: aggiungi un prompt di continuazione in un NUOVO messaggio utente
        messages << { role: "user", content: "Please continue" }

        response = client.messages.create(
          model: "claude-opus-5-5",
          max_tokens: 1024,
          messages: messages
        )
      end

      response
    end
    ```
  </CodeGroup>

  **Best practice:**

  1. **Non aggiungere mai blocchi di testo immediatamente dopo i risultati degli strumenti:** Questo stabilisce uno schema di input dell’utente dopo ogni uso di uno strumento, e Claude segue quello schema terminando il suo turno.
  2. **Non riprovare le risposte vuote senza modifiche:** Rimandare indietro la risposta vuota non aiuterà.
  3. **Usa i prompt di continuazione come ultima risorsa:** Solo se queste correzioni non risolvono il problema.
</Accordion>

### max\_tokens

Claude si è fermato perché ha raggiunto il limite [`max_tokens`](https://platform.claude.com/docs/it/api/messages/create#create.max_tokens) specificato nella tua richiesta.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 10,
      "messages": [{"role": "user", "content": "Explain quantum physics"}]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 10 \
    --message '{role: user, content: "Explain quantum physics"}'
  ```

  ```python Python
  client = anthropic.Anthropic()
  # Richiesta con token limitati
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=10,
      messages=[{"role": "user", "content": "Explain quantum physics"}],
  )

  if response.stop_reason == "max_tokens":
      # La risposta è stata troncata
      print("Response was cut off at token limit")
      # Valuta di effettuare un'altra richiesta per continuare
  ```

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

  // Richiesta con token limitati
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 10,
    messages: [{ role: "user", content: "Explain quantum physics" }]
  });

  if (response.stop_reason === "max_tokens") {
    // La risposta è stata troncata
    console.log("Response was cut off at token limit");
    // Valuta di effettuare un'altra richiesta per continuare
  }
  ```

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

  // Richiesta con token limitati
  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 10,
      Messages = [new UserMessageParam { Content = "Explain quantum physics" }]
  });

  if (response.StopReason == "max_tokens")
  {
      // La risposta è stata troncata
      Console.WriteLine("Response was cut off at token limit");
      // Valuta di effettuare un'altra richiesta per continuare
  }
  ```

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

  // Richiesta con token limitati
  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 10,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Explain quantum physics")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  if response.StopReason == "max_tokens" {
  	// La risposta è stata troncata
  	fmt.Println("Response was cut off at token limit")
  	// Valuta di effettuare un'altra richiesta per continuare
  }
  ```

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

  // Richiesta con token limitati
  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(10L)
          .addUserMessage("Explain quantum physics")
          .build()
  );

  if (response.stopReason().map(StopReason.MAX_TOKENS::equals).orElse(false)) {
      // La risposta è stata troncata
      IO.println("Response was cut off at token limit");
      // Valuta di effettuare un'altra richiesta per continuare
  }
  ```

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

  // Richiesta con token limitati
  $response = $client->messages->create(
      maxTokens: 10,
      messages: [['role' => 'user', 'content' => 'Explain quantum physics']],
      model: Model::CLAUDE_OPUS_5_5,
  );

  if ($response->stopReason === 'max_tokens') {
      // La risposta è stata troncata
      echo 'Response was cut off at token limit', PHP_EOL;
      // Valuta di effettuare un'altra richiesta per continuare
  }
  ```

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

  # Richiesta con token limitati
  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 10,
    messages: [{ role: "user", content: "Explain quantum physics" }]
  )

  if response.stop_reason == :max_tokens
    # La risposta è stata troncata
    puts "Response was cut off at token limit"
    # Valuta di effettuare un'altra richiesta per continuare
  end
  ```
</CodeGroup>

<Accordion title="Blocchi di uso degli strumenti incompleti">
  Se la risposta di Claude viene interrotta perché ha raggiunto il limite `max_tokens`, e la risposta troncata contiene un blocco di uso degli strumenti incompleto, dovrai riprovare la richiesta con un valore `max_tokens` più alto per ottenere l’uso degli strumenti completo.

  <CodeGroup exclude="shell:cURL, shell:CLI">
    <CodeGroupItem language="cURL">
      Questo flusso di lavoro richiede più logica di un singolo comando shell. Usa l’[Anthropic SDK](https://platform.claude.com/docs/it/cli-sdks-libraries/overview) per eseguirlo.
    </CodeGroupItem>

    <CodeGroupItem language="CLI">
      Questo flusso di lavoro richiede più logica di un singolo comando shell. Usa l’[Anthropic SDK](https://platform.claude.com/docs/it/cli-sdks-libraries/overview) per eseguirlo.
    </CodeGroupItem>

    ```python Python
    # Verifica se la risposta è stata troncata durante l'uso degli strumenti
    if response.stop_reason == "max_tokens":
        # Verifica se l'ultimo blocco di contenuto è un tool_use incompleto
        last_block = response.content[-1]
        if last_block.type == "tool_use":
            # Invia la richiesta con un valore di max_tokens più alto
            response = client.messages.create(
                model="claude-opus-5-5",
                max_tokens=4096,  # Increased limit
                messages=messages,
                tools=tools,
            )
    ```

    ```typescript TypeScript
    // Verifica se la risposta è stata troncata durante l'uso degli strumenti
    if (response.stop_reason === "max_tokens") {
      // Verifica se l'ultimo blocco di contenuto è un tool_use incompleto
      const lastBlock = response.content[response.content.length - 1];
      if (lastBlock.type === "tool_use") {
        // Invia la richiesta con un valore di max_tokens più alto
        response = await client.messages.create({
          model: "claude-opus-5-5",
          max_tokens: 4096, // Increased limit
          messages: messages,
          tools: tools
        });
      }
    }
    ```

    ```csharp C#
    using System.Linq;
    using Anthropic;
    using Anthropic.Models.Messages;

    AnthropicClient client = new();

    var parameters = new MessageCreateParams
    {
        Model = Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        Messages = messages,
        Tools = tools
    };

    var response = await client.Messages.Create(parameters);

    if (response.StopReason == "max_tokens")
    {
        var lastBlock = response.Content.Last();
        if (lastBlock.TryPickToolUse(out _))
        {
            response = await client.Messages.Create(parameters with { MaxTokens = 4096 });
        }
    }
    ```

    ```go Go
    response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    	Model:     anthropic.ModelClaudeOpus5_5,
    	MaxTokens: 1024,
    	Messages:  messages,
    	Tools:     tools,
    })
    if err != nil {
    	log.Fatal(err)
    }

    if response.StopReason == "max_tokens" {
    	lastBlock := response.Content[len(response.Content)-1]
    	switch lastBlock.AsAny().(type) {
    	case anthropic.ToolUseBlock:
    		response, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    			Model:     anthropic.ModelClaudeOpus5_5,
    			MaxTokens: 4096,
    			Messages:  messages,
    			Tools:     tools,
    		})
    		if err != nil {
    			log.Fatal(err)
    		}
    	}
    }
    ```

    ```java Java
    // Verifica se la risposta è stata troncata durante l'uso degli strumenti
    if (response.stopReason().isPresent() && response.stopReason().get().equals(StopReason.MAX_TOKENS)) {
        ContentBlock lastBlock = response.content().get(response.content().size() - 1);
        if (lastBlock.toolUse().isPresent()) {
            // Invia la richiesta con un valore di max_tokens più alto
            response = client.messages().create(
                MessageCreateParams.builder()
                    .model(Model.CLAUDE_OPUS_5_5)
                    .maxTokens(4096L) // Increased limit
                    .messages(messages)
                    .tools(tools)
                    .build()
            );
        }
    }
    ```

    ```php PHP
    $response = $client->messages->create(
        maxTokens: 1024,
        messages: $messages,
        model: 'claude-opus-5-5',
        tools: $tools,
    );

    if ($response->stopReason === 'max_tokens') {
        $lastBlock = end($response->content);
        if ($lastBlock->type === 'tool_use') {
            $response = $client->messages->create(
                maxTokens: 4096,
                messages: $messages,
                model: 'claude-opus-5-5',
                tools: $tools,
            );
        }
    }
    ```

    ```ruby Ruby
    response = client.messages.create(
      model: Anthropic::Model::CLAUDE_OPUS_5_5,
      max_tokens: 1024,
      messages: messages,
      tools: tools
    )

    if response.stop_reason == :max_tokens
      last_block = response.content.last
      if last_block.type == :tool_use
        response = client.messages.create(
          model: Anthropic::Model::CLAUDE_OPUS_5_5,
          max_tokens: 4096,
          messages: messages,
          tools: tools
        )
      end
    end
    ```
  </CodeGroup>
</Accordion>

### stop\_sequence

Claude ha incontrato una delle tue [sequenze di arresto](https://platform.claude.com/docs/it/api/messages/create#create.stop_sequences) personalizzate.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "stop_sequences": ["END", "STOP"],
      "messages": [{"role": "user", "content": "Generate text until you say END"}]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --stop-sequence END --stop-sequence STOP \
    --message '{role: user, content: "Generate text until you say END"}'
  ```

  ```python Python
  client = anthropic.Anthropic()
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      stop_sequences=["END", "STOP"],
      messages=[{"role": "user", "content": "Generate text until you say END"}],
  )

  if response.stop_reason == "stop_sequence":
      print(f"Stopped at sequence: {response.stop_sequence}")
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    stop_sequences: ["END", "STOP"],
    messages: [{ role: "user", content: "Generate text until you say END" }]
  });

  if (response.stop_reason === "stop_sequence") {
    console.log(`Stopped at sequence: ${response.stop_sequence}`);
  }
  ```

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

  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      StopSequences = ["END", "STOP"],
      Messages = [new UserMessageParam { Content = "Generate text until you say END" }]
  });

  if (response.StopReason == "stop_sequence")
  {
      Console.WriteLine($"Stopped at sequence: {response.StopSequence}");
  }
  ```

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:         anthropic.ModelClaudeOpus5_5,
  	MaxTokens:     1024,
  	StopSequences: []string{"END", "STOP"},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Generate text until you say END")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  if response.StopReason == "stop_sequence" {
  	fmt.Printf("Stopped at sequence: %s\n", response.StopSequence)
  }
  ```

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

  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addStopSequence("END")
          .addStopSequence("STOP")
          .addUserMessage("Generate text until you say END")
          .build()
  );

  if (response.stopReason().map(StopReason.STOP_SEQUENCE::equals).orElse(false)) {
      IO.println("Stopped at sequence: " + response.stopSequence().orElse(""));
  }
  ```

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

  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Generate text until you say END']],
      model: Model::CLAUDE_OPUS_5_5,
      stopSequences: ['END', 'STOP'],
  );

  if ($response->stopReason === 'stop_sequence') {
      echo "Stopped at sequence: {$response->stopSequence}", PHP_EOL;
  }
  ```

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

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 1024,
    stop_sequences: ["END", "STOP"],
    messages: [{ role: "user", content: "Generate text until you say END" }]
  )

  if response.stop_reason == :stop_sequence
    puts "Stopped at sequence: #{response.stop_sequence}"
  end
  ```
</CodeGroup>

### tool\_use

Claude sta chiamando uno strumento che devi eseguire.

<Note>
  Per la maggior parte delle implementazioni di “tool use” (uso degli strumenti), usa il [tool runner](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-runner), che gestisce automaticamente l’esecuzione degli strumenti, la formattazione dei risultati e la gestione della conversazione.
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "tools": [{
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "input_schema": {
          "type": "object",
          "properties": {"location": {"type": "string", "description": "City and state"}},
          "required": ["location"]
        }
      }],
      "messages": [{"role": "user", "content": "What is the weather in San Francisco?"}]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  messages:
    - role: user
      content: What is the weather in San Francisco?
  tools:
    - name: get_weather
      description: Get the current weather in a given location
      input_schema:
        type: object
        properties:
          location: {type: string, description: City and state}
        required: [location]
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()
  weather_tool = {
      "name": "get_weather",
      "description": "Get the current weather in a given location",
      "input_schema": {
          "type": "object",
          "properties": {
              "location": {"type": "string", "description": "City and state"},
          },
          "required": ["location"],
      },
  }


  def execute_tool(name, tool_input):
      """Run a tool and return the result."""
      return f"Weather in {tool_input.get('location', 'unknown')}: 72°F"


  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=[weather_tool],
      messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
  )

  if response.stop_reason == "tool_use":
      # Estrai ed esegui lo strumento
      for block in response.content:
          if block.type == "tool_use":
              result = execute_tool(block.name, block.input)
              # Restituisci il risultato a Claude per la risposta finale
  ```

  ```typescript TypeScript
  const client = new Anthropic();
  const weatherTool: Anthropic.Tool = {
    name: "get_weather",
    description: "Get the current weather in a given location",
    input_schema: {
      type: "object",
      properties: {
        location: { type: "string", description: "City and state" }
      },
      required: ["location"]
    }
  };

  function executeTool(name: string, input: Record<string, string>): string {
    return `Weather in ${input.location ?? "unknown"}: 72°F`;
  }

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [weatherTool],
    messages: [{ role: "user", content: "What is the weather in San Francisco?" }]
  });

  if (response.stop_reason === "tool_use") {
    // Estrai ed esegui lo strumento
    for (const block of response.content) {
      if (block.type === "tool_use") {
        const result = executeTool(block.name, block.input as Record<string, string>);
        // Restituisci il risultato a Claude per la risposta finale
      }
    }
  }
  ```

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

  var weatherTool = new Tool
  {
      Name = "get_weather",
      Description = "Get the current weather in a given location",
      InputSchema = new InputSchema
      {
          Properties = new Dictionary<string, JsonElement>
          {
              ["location"] = JsonSerializer.SerializeToElement(
                  new { type = "string", description = "City and state" }
              ),
          },
          Required = ["location"]
      }
  };

  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = [weatherTool],
      Messages = [new UserMessageParam { Content = "What is the weather in San Francisco?" }]
  });

  if (response.StopReason == "tool_use")
  {
      // Estrai ed esegui lo strumento
      foreach (var block in response.Content)
      {
          if (block.TryPickToolUse(out var toolUse))
          {
              // Esegui toolUse.Name con toolUse.Input e restituisci il risultato a Claude
          }
      }
  }
  ```

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

  weatherTool := anthropic.ToolParam{
  	Name:        "get_weather",
  	Description: anthropic.String("Get the current weather in a given location"),
  	InputSchema: anthropic.ToolInputSchemaParam{
  		Properties: map[string]any{
  			"location": map[string]string{"type": "string", "description": "City and state"},
  		},
  		Required: []string{"location"},
  	},
  }

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools:     []anthropic.ToolUnionParam{{OfTool: &weatherTool}},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What is the weather in San Francisco?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  if response.StopReason == "tool_use" {
  	// Estrai ed esegui lo strumento
  	for _, block := range response.Content {
  		if toolUse, ok := block.AsAny().(anthropic.ToolUseBlock); ok {
  			fmt.Println(toolUse.Name, toolUse.Input)
  			// Restituisci il risultato a Claude per la risposta finale
  		}
  	}
  }
  ```

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

  Tool weatherTool = Tool.builder()
      .name("get_weather")
      .description("Get the current weather in a given location")
      .inputSchema(Tool.InputSchema.builder()
          .properties(JsonValue.from(Map.of(
              "location", Map.of("type", "string", "description", "City and state")
          )))
          .putAdditionalProperty("required", JsonValue.from(List.of("location")))
          .build())
      .build();

  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(weatherTool)
          .addUserMessage("What is the weather in San Francisco?")
          .build()
  );

  if (response.stopReason().map(StopReason.TOOL_USE::equals).orElse(false)) {
      // Estrai ed esegui lo strumento
      for (ContentBlock block : response.content()) {
          block.toolUse().ifPresent(toolUse -> {
              // Esegui toolUse.name() con toolUse.input() e restituisci il risultato a Claude
          });
      }
  }
  ```

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

  $weatherTool = [
      'name' => 'get_weather',
      'description' => 'Get the current weather in a given location',
      'input_schema' => [
          'type' => 'object',
          'properties' => [
              'location' => ['type' => 'string', 'description' => 'City and state'],
          ],
          'required' => ['location'],
      ],
  ];

  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'What is the weather in San Francisco?']],
      model: 'claude-opus-5-5',
      tools: [$weatherTool],
  );

  if ($response->stopReason === 'tool_use') {
      // Estrai ed esegui lo strumento
      foreach ($response->content as $block) {
          if ($block->type === 'tool_use') {
              // Esegui $block->name con $block->input e restituisci il risultato a Claude
          }
      }
  }
  ```

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

  weather_tool = {
    name: "get_weather",
    description: "Get the current weather in a given location",
    input_schema: {
      type: "object",
      properties: {
        location: { type: "string", description: "City and state" }
      },
      required: ["location"]
    }
  }

  response = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [weather_tool],
    messages: [{ role: "user", content: "What is the weather in San Francisco?" }]
  )

  if response.stop_reason == :tool_use
    # Estrai ed esegui lo strumento
    response.content.each do |block|
      next unless block.type == :tool_use
      # Esegui block.name con block.input e restituisci il risultato a Claude
    end
  end
  ```
</CodeGroup>

#### Quando uno strumento server è ancora in attesa

Claude può chiamare uno [strumento server](https://platform.claude.com/docs/it/agents-and-tools/tool-use/server-tools) e uno strumento client (uno strumento eseguito dal tuo codice) nello stesso gruppo di [chiamate parallele agli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/parallel-tool-use). L’API restituisce quindi una risposta `tool_use` senza eseguire lo strumento server, così che tu possa eseguire prima gli strumenti client.

La chiamata in attesa è un blocco `server_tool_use` o `mcp_tool_use` senza blocco di risultato. Nient’altro nella risposta la contrassegna. Dopo l’esecuzione di uno strumento server, il suo blocco di risultato, come `web_search_tool_result`, contiene l’`id` della chiamata nel suo campo `tool_use_id`.

<Note>
  Con la [chiamata programmatica degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/programmatic-tool-calling), la stessa forma di risposta ha un significato diverso. Il blocco client `tool_use` proviene da codice in esecuzione nello strumento `code_execution` anziché direttamente da Claude, e il suo campo `caller` indica il blocco `code_execution` che lo ha chiamato. Quel codice è già stato avviato: è in pausa in attesa dei tuoi blocchi `tool_result`, e inviarli riprende l’esecuzione invece di avviare uno strumento differito. Il blocco di risultato del blocco `code_execution` stesso arriva quando il codice termina, il che può richiedere più di un giro di risultati degli strumenti. Il messaggio utente successivo è lo stesso in entrambi i casi; con la chiamata programmatica degli strumenti, restituisci anche l’`id` dal campo `container` della risposta, come mostrato in quella pagina.
</Note>

Questa risposta mista contiene uno strumento server in attesa e una chiamata a uno strumento client:

```json A mixed tool_use response
{
  "stop_reason": "tool_use",
  "content": [
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01HxbWnMRmbWyMfUtJKC45rA",
      "name": "web_search",
      "input": { "query": "example article" }
    },
    {
      "type": "tool_use",
      "id": "toolu_01PjgRJLbXrXEMZwDNYLnBqk",
      "name": "run_command",
      "input": { "command": "uname -a" }
    }
  ]
}
```

Per continuare da una risposta mista come questa, costruisci una richiesta successiva:

1. Mantieni i messaggi precedenti e aggiungi il `content` della risposta senza modifiche come messaggio `assistant`.
2. Aggiungi un messaggio utente che contenga solo blocchi `tool_result`, uno per ogni blocco client `tool_use`. Una chiamata in attesa non ne riceve nessuno.
3. Invia la richiesta con lo stesso array `tools` di prima, così che lo strumento server in attesa sia ancora definito.

Per i campi di un blocco `tool_result`, vedi [Gestire le chiamate agli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/handle-tool-calls). Il messaggio utente nella richiesta successiva ha questo aspetto:

```json The follow-up user message
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01PjgRJLbXrXEMZwDNYLnBqk",
      "content": "Linux demo-host 6.8.0-52-generic x86_64 GNU/Linux"
    }
  ]
}
```

L’API aggiunge i tuoi risultati al turno non terminato di Claude, esegue lo strumento server in attesa e continua. Per uno strumento server chiamato direttamente da Claude, il `content` della risposta successiva inizia con il blocco di risultato di quello strumento.

Un ciclo che segue i passaggi precedenti per ogni risposta `tool_use` non ha bisogno di rilevare uno strumento server in attesa. Nelle richieste successive, mantieni tre messaggi separati in `messages`, in questo ordine: la prima risposta, il tuo messaggio `tool_result` e la risposta successiva.

Due casi richiedono un campo in più nella richiesta successiva:

* **La risposta include un `container`:** Rinvia il suo ID (vedi la sezione [Riutilizzo del container](https://platform.claude.com/docs/it/agents-and-tools/tool-use/code-execution-tool#container-reuse) dello strumento di esecuzione del codice).
* **Il blocco in attesa è un [blocco `mcp_tool_use`](https://platform.claude.com/docs/it/agents-and-tools/mcp-connector#mcp-tool-use-block):** Invia gli stessi `mcp_servers` di prima.

Ciascuno di questi errori nella richiesta successiva fallisce con un 400 `invalid_request_error`. I messaggi mostrati si riferiscono alla ricerca web. Per altri strumenti server, i nomi al loro interno sono diversi.

| Errore                                                                                               | Il messaggio di errore include                                                 |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `tools` non definisce più lo strumento server in attesa                                              | ``but no `web_search` tool was provided``                                      |
| Testo o altro contenuto segue i blocchi `tool_result`                                                | ``was found without a corresponding `web_search_tool_result` block``           |
| Con la chiamata programmatica degli strumenti, testo o altro contenuto segue i blocchi `tool_result` | `only tool_result blocks are allowed`                                          |
| Testo o altro contenuto precede i blocchi `tool_result`                                              | `` `tool_use` ids were found without `tool_result` blocks immediately after `` |
| Manca un blocco `tool_result`                                                                        | `` `tool_use` ids were found without `tool_result` blocks immediately after `` |

Il contenuto dopo i blocchi `tool_result` fallisce perché termina il turno di Claude mentre lo strumento server è ancora in attesa. Per fornire a Claude ulteriore input, continua finché lo `stop_reason` di una risposta non è né `tool_use` né `pause_turn`. Quindi, invia l’input come nuovo messaggio utente nella stessa lista `messages`.

### pause\_turn

Restituito quando il ciclo di campionamento lato server raggiunge il suo limite di iterazioni durante l’esecuzione di [strumenti server](https://platform.claude.com/docs/it/agents-and-tools/tool-use/server-tools) come la ricerca web. Il limite predefinito è di 10 iterazioni per ogni richiesta.

Quando Claude si ferma per chiamare uno strumento che esegui tu, il motivo di arresto è [`tool_use`](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#tool-use), mai `pause_turn`.

Per consentire a Claude di completare un turno in pausa, costruisci una nuova richiesta:

1. Mantieni i messaggi precedenti e aggiungi il `content` della risposta senza modifiche come messaggio `assistant`, incluso qualsiasi blocco `server_tool_use` che non ha un blocco di risultato.
2. Invia la richiesta con gli stessi `tools` di prima e nessun messaggio utente dopo il messaggio `assistant`.

Se la risposta include un `container`, rinvia anche il suo ID così che il turno mantenga i suoi file. Per i dettagli, vedi la sezione [Riutilizzo del container](https://platform.claude.com/docs/it/agents-and-tools/tool-use/code-execution-tool#container-reuse) dello strumento di esecuzione del codice. Gli esempi seguenti usano la ricerca web e non inviano alcun ID del container:

<CodeGroup>
  ```bash cURL
  # Gli SDK gestiscono direttamente la continuazione. Con cURL, controlla stop_reason
  # nella risposta e ripeti la POST aggiungendo il contenuto dell'assistente.
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "tools": [{"type": "web_search_20250305", "name": "web_search"}],
      "messages": [{"role": "user", "content": "Search for latest AI news"}]
    }'
  ```

  ```bash CLI
  # Controlla stop_reason; se è pause_turn, riesegui con la risposta
  # dell'assistente aggiunta a --message.
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  tools:
    - {type: web_search_20250305, name: web_search}
  messages:
    - {role: user, content: "Search for latest AI news"}
  YAML
  ```

  ```python Python
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      tools=[{"type": "web_search_20250305", "name": "web_search"}],
      messages=[{"role": "user", "content": "Search for latest AI news"}],
  )

  if response.stop_reason == "pause_turn":
      # Continua la conversazione inviando di nuovo la risposta
      messages = [
          {"role": "user", "content": "Search for latest AI news"},
          {"role": "assistant", "content": response.content},
      ]
      continuation = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=4096,
          messages=messages,
          tools=[{"type": "web_search_20250305", "name": "web_search"}],
      )
  ```

  ```typescript TypeScript
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    tools: [{ type: "web_search_20250305", name: "web_search" }],
    messages: [{ role: "user", content: "Search for latest AI news" }]
  });

  if (response.stop_reason === "pause_turn") {
    // Continua la conversazione inviando di nuovo la risposta
    const continuation = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 4096,
      tools: [{ type: "web_search_20250305", name: "web_search" }],
      messages: [
        { role: "user", content: "Search for latest AI news" },
        { role: "assistant", content: response.content }
      ]
    });
  }
  ```

  ```csharp C#
  List<ToolUnion> tools = [new ToolUnion(new WebSearchTool20250305())];
  MessageParam userMessage = new UserMessageParam { Content = "Search for latest AI news" };

  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Tools = tools,
      Messages = [userMessage]
  });

  if (response.StopReason == "pause_turn")
  {
      // Continua la conversazione inviando di nuovo la risposta
      var continuation = await client.Messages.Create(new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 4096,
          Tools = tools,
          Messages =
          [
              userMessage,
              new AssistantMessageParam
              {
                  Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList()
              }
          ]
      });
  }
  ```

  ```go Go
  tools := []anthropic.ToolUnionParam{
  	{OfWebSearchTool20250305: &anthropic.WebSearchTool20250305Param{}},
  }
  userMessage := anthropic.NewUserMessage(anthropic.NewTextBlock("Search for latest AI news"))

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Tools:     tools,
  	Messages:  []anthropic.MessageParam{userMessage},
  })
  if err != nil {
  	log.Fatal(err)
  }

  if response.StopReason == "pause_turn" {
  	// Continua la conversazione inviando di nuovo la risposta
  	var contentParams []anthropic.ContentBlockParamUnion
  	for _, block := range response.Content {
  		contentParams = append(contentParams, block.ToParam())
  	}
  	continuation, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 4096,
  		Tools:     tools,
  		Messages:  []anthropic.MessageParam{userMessage, anthropic.NewAssistantMessage(contentParams...)},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}
  	_ = continuation
  }
  ```

  ```java Java
  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addTool(WebSearchTool20250305.builder().build())
          .addUserMessage("Search for latest AI news")
          .build()
  );

  if (response.stopReason().map(StopReason.PAUSE_TURN::equals).orElse(false)) {
      // Continua la conversazione inviando di nuovo la risposta
      Message continuation = client.messages().create(
          MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(4096L)
              .addTool(WebSearchTool20250305.builder().build())
              .addUserMessage("Search for latest AI news")
              .addMessage(response)
              .build()
      );
  }
  ```

  ```php PHP
  $tools = [['type' => 'web_search_20250305', 'name' => 'web_search']];
  $userMessage = ['role' => 'user', 'content' => 'Search for latest AI news'];

  $response = $client->messages->create(
      maxTokens: 4096,
      messages: [$userMessage],
      model: 'claude-opus-5-5',
      tools: $tools,
  );

  if ($response->stopReason === 'pause_turn') {
      // Continua la conversazione inviando di nuovo la risposta
      $continuation = $client->messages->create(
          maxTokens: 4096,
          messages: [
              $userMessage,
              ['role' => 'assistant', 'content' => $response->content],
          ],
          model: 'claude-opus-5-5',
          tools: $tools,
      );
  }
  ```

  ```ruby Ruby
  tools = [{ type: "web_search_20250305", name: "web_search" }]
  user_message = { role: "user", content: "Search for latest AI news" }

  response = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 4096,
    tools: tools,
    messages: [user_message]
  )

  if response.stop_reason == :pause_turn
    # Continua la conversazione inviando di nuovo la risposta
    continuation = client.messages.create(
      model: "claude-opus-5-5",
      max_tokens: 4096,
      tools: tools,
      messages: [user_message, { role: "assistant", content: response.content }]
    )
  end
  ```
</CodeGroup>

La tua applicazione dovrebbe gestire `pause_turn` in qualsiasi ciclo agente che usa strumenti server. Per un ciclo che gestisce pause ripetute e rinvia l’ID del container, vedi [Implementa la logica di nuovo tentativo per pause\_turn](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#implement-retry-logic-for-pause-turn).

### refusal

Claude ha rifiutato di generare una risposta. I classificatori di sicurezza restituiscono questo motivo di arresto come una normale risposta HTTP 200, non come un errore.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "[Unsafe request]"}]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "[Unsafe request]"}'
  ```

  ```python Python
  client = anthropic.Anthropic()
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "[Unsafe request]"}],
  )

  if response.stop_reason == "refusal":
      # Claude si è rifiutato di rispondere
      print("Claude was unable to process this request")
      # Valuta di riformulare o modificare la richiesta
  ```

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

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "[Unsafe request]" }]
  });

  if (response.stop_reason === "refusal") {
    // Claude ha rifiutato di rispondere
    console.log("Claude was unable to process this request");
    // Valuta di riformulare o modificare la richiesta
  }
  ```

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

  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new UserMessageParam { Content = "[Unsafe request]" }]
  });

  if (response.StopReason == "refusal")
  {
      // Claude ha rifiutato di rispondere
      Console.WriteLine("Claude was unable to process this request");
      // Valuta di riformulare o modificare la richiesta
  }
  ```

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("[Unsafe request]")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  if response.StopReason == "refusal" {
  	// Claude si è rifiutato di rispondere
  	fmt.Println("Claude was unable to process this request")
  	// Valuta di riformulare o modificare la richiesta
  }
  ```

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

  Message response = client.messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addUserMessage("[Unsafe request]")
          .build()
  );

  if (response.stopReason().map(StopReason.REFUSAL::equals).orElse(false)) {
      // Claude ha rifiutato di rispondere
      IO.println("Claude was unable to process this request");
      // Valuta di riformulare o modificare la richiesta
  }
  ```

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

  $response = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => '[Unsafe request]']],
      model: Model::CLAUDE_OPUS_5_5,
  );

  if ($response->stopReason === 'refusal') {
      // Claude ha rifiutato di rispondere
      echo 'Claude was unable to process this request', PHP_EOL;
      // Valuta di riformulare o modificare la richiesta
  }
  ```

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

  response = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 1024,
    messages: [{ role: "user", content: "[Unsafe request]" }]
  )

  if response.stop_reason == :refusal
    # Claude si è rifiutato di rispondere
    puts "Claude was unable to process this request"
    # Valuta di riformulare o modificare la richiesta
  end
  ```
</CodeGroup>

<Tip>
  Se incontri frequentemente motivi di arresto `refusal` durante l’uso di Claude Sonnet 4.5 ([deprecato](https://platform.claude.com/docs/it/about-claude/model-deprecations)) o Claude Opus 4.1 (quest’ultimo [ritirato, tranne su Claude Models on Google Cloud (Google managed) e Amazon Bedrock](https://platform.claude.com/docs/it/about-claude/model-deprecations)), puoi provare ad aggiornare le tue chiamate API per usare Claude Haiku 4.5 (`claude-haiku-4-5-20251001`), che ha restrizioni d’uso diverse. Scopri di più su [come comprendere i filtri di sicurezza dell’API di Sonnet 4.5](https://support.claude.com/en/articles/12449294-understanding-sonnet-4-5-s-api-safety-filters).
</Tip>

In caso di rifiuto, l’oggetto [`stop_details`](https://platform.claude.com/docs/it/api/messages/create#message.stop_details) identifica la categoria di policy che lo ha attivato. Le categorie e la forma completa della risposta di rifiuto sono trattate in [Come appare un rifiuto](https://platform.claude.com/docs/it/build-with-claude/refusals-and-fallback#refusal-response). `stop_details` è `null` per tutti i motivi di arresto diversi da `refusal`.

Di solito puoi ottenere una risposta a una richiesta rifiutata riprovandola su un altro modello Claude. Questo funziona per Claude Fable 5.2, Claude Fable 5.1, Claude Fable 5, Claude Opus 5.5, Claude Opus 5, Claude Sonnet 5.5 e Claude Haiku 5.5. [Rifiuti e fallback](https://platform.claude.com/docs/it/build-with-claude/refusals-and-fallback) mostra come configurare quel nuovo tentativo, lato server o nel tuo client. Claude Haiku 5.5 non ha un fallback lato server, quindi configura il suo nuovo tentativo con il [fallback lato client](https://platform.claude.com/docs/it/build-with-claude/refusals-and-fallback#client-side-fallback). Se costruisci tu stesso il nuovo tentativo a partire da uno qualsiasi di questi modelli tranne Claude Haiku 5.5, [Credito di fallback](https://platform.claude.com/docs/it/build-with-claude/fallback-credit) spiega come evitare di pagare due volte il costo della cache dei prompt.

### model\_context\_window\_exceeded

Claude si è fermato perché ha raggiunto il limite della “context window” (finestra di contesto) del modello. Questo ti consente di richiedere il massimo numero possibile di token senza conoscere la dimensione esatta dell’input.

<Note>
  Questo motivo di arresto è attualmente tipizzato solo nel namespace `beta` (csharp, go: `Beta`; java: `beta()`) dell’SDK, quindi gli esempi seguenti chiamano `client.beta.messages` (csharp, go: `client.Beta.Messages`; java: `client.beta().messages()`; php: `$client->beta->messages`) e usano i tipi con prefisso `Beta`. Su Sonnet 4.5 (deprecato) e modelli più recenti, l’API restituisce questo valore senza un header beta. Per i modelli precedenti, aggiungi l’header beta `model-context-window-exceeded-2025-08-26` per abilitarlo.
</Note>

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 20000,
      "messages": [{"role": "user", "content": "Large input that uses most of context window..."}]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 20000 \
    --message '{role: user, content: "Large input that uses most of context window..."}'
  ```

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

  # Richiesta con il numero massimo di token per ottenere il più possibile
  response = client.beta.messages.create(
      model="claude-opus-5-5",
      max_tokens=20000,  # Python SDK requires streaming for max_tokens above ~21k
      messages=[
          {"role": "user", "content": "Large input that uses most of context window..."}
      ],
  )

  if response.stop_reason == "model_context_window_exceeded":
      # La risposta ha raggiunto il limite della finestra di contesto prima di max_tokens
      print("Response reached model's context window limit")
      # La risposta è comunque valida, ma è stata limitata dalla finestra di contesto
  ```

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

  // Richiesta con il numero massimo di token per ottenere il più possibile
  const response = await client.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 20000,
    messages: [{ role: "user", content: "Large input that uses most of context window..." }]
  });

  if (response.stop_reason === "model_context_window_exceeded") {
    // La risposta ha raggiunto il limite della finestra di contesto prima di max_tokens
    console.log("Response reached model's context window limit");
    // La risposta è comunque valida, ma è stata limitata dalla finestra di contesto
  }
  ```

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

  // Richiesta con il numero massimo di token per ottenere il più possibile
  var response = await client.Beta.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 20000,
      Messages = [new BetaUserMessageParam { Content = "Large input that uses most of context window..." }]
  });

  if (response.StopReason?.Value() == BetaStopReason.ModelContextWindowExceeded)
  {
      // La risposta ha raggiunto il limite della finestra di contesto prima di max_tokens
      Console.WriteLine("Response reached model's context window limit");
      // La risposta è comunque valida, ma è stata limitata dalla finestra di contesto
  }
  ```

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

  // Richiesta con il numero massimo di token per ottenere il più possibile
  response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 20000,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Large input that uses most of context window...")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  if response.StopReason == anthropic.BetaStopReasonModelContextWindowExceeded {
  	// La risposta ha raggiunto il limite della finestra di contesto prima di max_tokens
  	fmt.Println("Response reached model's context window limit")
  	// La risposta è comunque valida ma è stata limitata dalla finestra di contesto
  }
  ```

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

  // Richiesta con il numero massimo di token per ottenere il più possibile
  BetaMessage response = client.beta().messages().create(
      MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(20000L)
          .addUserMessage("Large input that uses most of context window...")
          .build()
  );

  if (response.stopReason().map(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED::equals).orElse(false)) {
      // La risposta ha raggiunto il limite della finestra di contesto prima di max_tokens
      IO.println("Response reached model's context window limit");
      // La risposta è comunque valida, ma è stata limitata dalla finestra di contesto
  }
  ```

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

  // Richiesta con il massimo dei token per ottenere il più possibile
  $response = $client->beta->messages->create(
      maxTokens: 20000,
      messages: [['role' => 'user', 'content' => 'Large input that uses most of context window...']],
      model: 'claude-opus-5-5',
  );

  if ($response->stopReason === 'model_context_window_exceeded') {
      // La risposta ha raggiunto il limite della finestra di contesto prima di max_tokens
      echo 'Response reached model\'s context window limit', PHP_EOL;
      // La risposta è comunque valida, ma è stata limitata dalla finestra di contesto
  }
  ```

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

  # Richiesta con il numero massimo di token per ottenere il più possibile
  response = client.beta.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 20000,
    messages: [{ role: "user", content: "Large input that uses most of context window..." }]
  )

  if response.stop_reason == :model_context_window_exceeded
    # La risposta ha raggiunto il limite della finestra di contesto prima di max_tokens
    puts "Response reached model's context window limit"
    # La risposta è comunque valida, ma è stata limitata dalla finestra di contesto
  end
  ```
</CodeGroup>

## Best practice per la gestione dei motivi di arresto

### Controlla sempre stop\_reason

Prendi l’abitudine di controllare lo `stop_reason` nella tua logica di gestione delle risposte:

<CodeGroup exclude="shell">
  ```python Python
  def handle_response(response):
      match response.stop_reason:
          case "tool_use":
              return handle_tool_use(response)
          case "max_tokens":
              return handle_truncation(response)
          case "model_context_window_exceeded":
              return handle_context_limit(response)
          case "pause_turn":
              return handle_pause(response)
          case "refusal":
              return handle_refusal(response)
          case _:
              # Gestisci end_turn e gli altri casi
              return next(
                  (block.text for block in response.content if block.type == "text"),
                  "",
              )
  ```

  ```typescript TypeScript
  function handleResponse(response: Anthropic.Beta.BetaMessage): string {
    switch (response.stop_reason) {
      case "tool_use":
        return handleToolUse(response);
      case "max_tokens":
        return handleTruncation(response);
      case "model_context_window_exceeded":
        return handleContextLimit(response);
      case "pause_turn":
        return handlePause(response);
      case "refusal":
        return handleRefusal(response);
      default: {
        // Gestisci end_turn e altri casi
        const textBlock = response.content.find((block) => block.type === "text");
        return textBlock?.text ?? "";
      }
    }
  }
  ```

  ```csharp C#
  static string HandleResponse(BetaMessage response)
  {
      return response.StopReason?.Value() switch
      {
          BetaStopReason.ToolUse => HandleToolUse(response),
          BetaStopReason.MaxTokens => HandleTruncation(response),
          BetaStopReason.ModelContextWindowExceeded => HandleContextLimit(response),
          BetaStopReason.PauseTurn => HandlePause(response),
          BetaStopReason.Refusal => HandleRefusal(response),
          // Gestisci end_turn e gli altri casi
          _ => response.Content.Select(b => b.Value).OfType<BetaTextBlock>().FirstOrDefault()?.Text ?? "",
      };
  }
  ```

  ```go Go
  func handleResponse(response *anthropic.BetaMessage) string {
  	switch response.StopReason {
  	case anthropic.BetaStopReasonToolUse:
  		return handleToolUse(response)
  	case anthropic.BetaStopReasonMaxTokens:
  		return handleTruncation(response)
  	case anthropic.BetaStopReasonModelContextWindowExceeded:
  		return handleContextLimit(response)
  	case anthropic.BetaStopReasonPauseTurn:
  		return handlePause(response)
  	case anthropic.BetaStopReasonRefusal:
  		return handleRefusal(response)
  	default:
  		// Gestisci end_turn e gli altri casi
  		for _, block := range response.Content {
  			if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
  				return textBlock.Text
  			}
  		}
  		return ""
  	}
  }
  ```

  ```java Java
  static String handleResponse(BetaMessage response) {
      BetaStopReason reason = response.stopReason().orElse(BetaStopReason.END_TURN);
      if (reason.equals(BetaStopReason.TOOL_USE)) {
          return handleToolUse(response);
      } else if (reason.equals(BetaStopReason.MAX_TOKENS)) {
          return handleTruncation(response);
      } else if (reason.equals(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED)) {
          return handleContextLimit(response);
      } else if (reason.equals(BetaStopReason.PAUSE_TURN)) {
          return handlePause(response);
      } else if (reason.equals(BetaStopReason.REFUSAL)) {
          return handleRefusal(response);
      }
      // Gestisci end_turn e altri casi
      return response.content().stream()
          .filter(BetaContentBlock::isText)
          .findFirst()
          .map(block -> block.asText().text())
          .orElse("");
  }
  ```

  ```php PHP
  function handle_response($response): string
  {
      return match ($response->stopReason) {
          'tool_use' => handle_tool_use($response),
          'max_tokens' => handle_truncation($response),
          'model_context_window_exceeded' => handle_context_limit($response),
          'pause_turn' => handle_pause($response),
          'refusal' => handle_refusal($response),
          // Gestisci end_turn e altri casi
          default => array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '',
      };
  }
  ```

  ```ruby Ruby
  def handle_response(response)
    case response.stop_reason
    when :tool_use then handle_tool_use(response)
    when :max_tokens then handle_truncation(response)
    when :model_context_window_exceeded then handle_context_limit(response)
    when :pause_turn then handle_pause(response)
    when :refusal then handle_refusal(response)
    else
      # Gestisci end_turn e altri casi
      response.content.find { it.type == :text }&.text
    end
  end
  ```
</CodeGroup>

### Gestisci le risposte troncate in modo appropriato

Quando una risposta viene troncata a causa dei limiti di token o della finestra di contesto, aggiungi un avviso in modo che il lettore sappia che l’output è incompleto. Per continuare invece a generare dal punto in cui la risposta si è interrotta, consulta [Garantire risposte complete](https://platform.claude.com/docs/it/build-with-claude/handling-stop-reasons#ensuring-complete-responses).

<CodeGroup exclude="shell">
  ```python Python
  def handle_truncated_response(response):
      text = next((block.text for block in response.content if block.type == "text"), "")
      if response.stop_reason in ["max_tokens", "model_context_window_exceeded"]:
          if response.stop_reason == "max_tokens":
              note = "[Response truncated due to max_tokens limit]"
          else:
              note = "[Response truncated due to context window limit]"
          return f"{text}\n\n{note}"
      return text
  ```

  ```typescript TypeScript
  function handleTruncatedResponse(response: Anthropic.Beta.BetaMessage): string {
    const textBlock = response.content.find((block) => block.type === "text");
    const text = textBlock?.text ?? "";

    if (
      response.stop_reason === "max_tokens" ||
      response.stop_reason === "model_context_window_exceeded"
    ) {
      const note =
        response.stop_reason === "max_tokens"
          ? "[Response truncated due to max_tokens limit]"
          : "[Response truncated due to context window limit]";
      return `${text}\n\n${note}`;
    }
    return text;
  }
  ```

  ```csharp C#
  static string HandleTruncatedResponse(BetaMessage response)
  {
      var text = response.Content.Select(b => b.Value).OfType<BetaTextBlock>().FirstOrDefault()?.Text ?? "";
      var reason = response.StopReason?.Value();

      if (reason is BetaStopReason.MaxTokens or BetaStopReason.ModelContextWindowExceeded)
      {
          var note = reason == BetaStopReason.MaxTokens
              ? "[Response truncated due to max_tokens limit]"
              : "[Response truncated due to context window limit]";
          return $"{text}\n\n{note}";
      }
      return text;
  }
  ```

  ```go Go
  func handleTruncatedResponse(response *anthropic.BetaMessage) string {
  	text := ""
  	for _, block := range response.Content {
  		if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
  			text = textBlock.Text
  			break
  		}
  	}

  	if response.StopReason == anthropic.BetaStopReasonMaxTokens ||
  		response.StopReason == anthropic.BetaStopReasonModelContextWindowExceeded {
  		note := "[Response truncated due to context window limit]"
  		if response.StopReason == anthropic.BetaStopReasonMaxTokens {
  			note = "[Response truncated due to max_tokens limit]"
  		}
  		return text + "\n\n" + note
  	}
  	return text
  }
  ```

  ```java Java
  static String handleTruncatedResponse(BetaMessage response) {
      String text = response.content().stream()
          .filter(BetaContentBlock::isText)
          .findFirst()
          .map(block -> block.asText().text())
          .orElse("");
      BetaStopReason reason = response.stopReason().orElse(BetaStopReason.END_TURN);

      if (reason.equals(BetaStopReason.MAX_TOKENS)
              || reason.equals(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED)) {
          String note = reason.equals(BetaStopReason.MAX_TOKENS)
              ? "[Response truncated due to max_tokens limit]"
              : "[Response truncated due to context window limit]";
          return text + "\n\n" + note;
      }
      return text;
  }
  ```

  ```php PHP
  function handle_truncated_response($response): string
  {
      $text = array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '';

      if (in_array($response->stopReason, ['max_tokens', 'model_context_window_exceeded'], true)) {
          $note = $response->stopReason === 'max_tokens'
              ? '[Response truncated due to max_tokens limit]'
              : '[Response truncated due to context window limit]';
          return "{$text}\n\n{$note}";
      }
      return $text;
  }
  ```

  ```ruby Ruby
  def handle_truncated_response(response)
    text = response.content.find { it.type == :text }&.text

    if [:max_tokens, :model_context_window_exceeded].include?(response.stop_reason)
      note = if response.stop_reason == :max_tokens
        "[Response truncated due to max_tokens limit]"
      else
        "[Response truncated due to context window limit]"
      end
      return "#{text}\n\n#{note}"
    end
    text
  end
  ```
</CodeGroup>

### Implementa la logica di nuovo tentativo per pause\_turn

Quando usi gli [strumenti server](https://platform.claude.com/docs/it/agents-and-tools/tool-use/server-tools), l’API potrebbe restituire `pause_turn` se il ciclo di campionamento lato server raggiunge il suo limite di iterazioni (predefinito 10). Gestiscilo aggiungendo la risposta in pausa ai tuoi messaggi senza modificarla e inviando di nuovo la richiesta. Se la risposta include un `container`, [rinvia anche il suo ID](https://platform.claude.com/docs/it/agents-and-tools/tool-use/code-execution-tool#container-reuse). Senza di esso, la richiesta successiva avvia un nuovo container e i file creati in precedenza nel turno vanno persi.

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    Questo flusso di lavoro richiede più logica di un singolo comando shell. Usa l’[Anthropic SDK](https://platform.claude.com/docs/it/cli-sdks-libraries/overview) per eseguirlo.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Questo flusso di lavoro richiede più logica di un singolo comando shell. Usa l’[Anthropic SDK](https://platform.claude.com/docs/it/cli-sdks-libraries/overview) per eseguirlo.
  </CodeGroupItem>

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


  def handle_server_tool_conversation(client, user_query, tools, max_requests=5):
      messages = [{"role": "user", "content": user_query}]
      container_id = None

      for _ in range(max_requests):
          response = client.messages.create(
              model="claude-opus-5-5",
              max_tokens=4096,
              messages=messages,
              tools=tools,
              container=container_id,
          )

          if response.stop_reason != "pause_turn":
              # Non in pausa: restituisci la risposta
              return response

          # pause_turn: aggiungi la risposta in pausa come messaggio dell'assistente, poi continua
          messages.append({"role": "assistant", "content": response.content})

          # Se gli strumenti sono stati eseguiti in un container, rinvia il suo ID per conservarne i file
          if response.container:
              container_id = response.container.id

      # Ancora in pausa dopo max_requests richieste: restituisci l'ultima risposta
      return response


  response = handle_server_tool_conversation(
      client,
      "Use the code execution tool to find the 1,000th prime number.",
      [{"type": "code_execution_20250825", "name": "code_execution"}],
  )
  print(response.stop_reason)
  ```

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

  async function handleServerToolConversation(
    client: Anthropic,
    userQuery: string,
    tools: Anthropic.ToolUnion[],
    maxRequests = 5
  ): Promise<Anthropic.Message> {
    const messages: Anthropic.MessageParam[] = [{ role: "user", content: userQuery }];
    let containerId: string | null = null;
    let response: Anthropic.Message;
    let requestCount = 0;

    do {
      response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 4096,
        messages,
        tools,
        container: containerId
      });

      if (response.stop_reason !== "pause_turn") {
        // Non in pausa: restituisci la risposta
        return response;
      }

      // pause_turn: aggiungi la risposta in pausa come messaggio assistant, poi continua
      messages.push({ role: "assistant", content: response.content });

      // Se gli strumenti sono stati eseguiti in un container, reinvia il suo ID per conservarne i file
      if (response.container) {
        containerId = response.container.id;
      }
    } while (++requestCount < maxRequests);

    // Ancora in pausa dopo maxRequests richieste: restituisci l'ultima risposta
    return response;
  }

  const response = await handleServerToolConversation(
    client,
    "Use the code execution tool to find the 1,000th prime number.",
    [{ type: "code_execution_20250825", name: "code_execution" }]
  );
  console.log(response.stop_reason);
  ```

  ```csharp C#
  // Un turno con strumenti server può durare minuti, più del timeout predefinito dell'SDK,
  // che questo imposta in base a MaxTokens (circa 2 minuti con 4096).
  AnthropicClient client = new() { Timeout = TimeSpan.FromMinutes(10) };

  static async Task<Message> HandleServerToolConversation(
      AnthropicClient client,
      string userQuery,
      List<ToolUnion> tools,
      int maxRequests = 5)
  {
      List<MessageParam> messages = [new UserMessageParam { Content = userQuery }];
      MessageCreateParamsContainer? container = null;
      Message response;
      var requestCount = 0;

      do
      {
          response = await client.Messages.Create(new MessageCreateParams
          {
              Model = Model.ClaudeOpus5_5,
              MaxTokens = 4096,
              Messages = messages,
              Tools = tools,
              Container = container
          });

          if (response.StopReason != StopReason.PauseTurn)
          {
              // Non in pausa: restituisci la risposta
              return response;
          }

          // pause_turn: aggiungi la risposta in pausa come messaggio assistant, poi continua
          // I blocchi di richiesta e risposta sono tipi distinti: copia il JSON di ogni blocco invariato
          messages.Add(new AssistantMessageParam
          {
              Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList()
          });

          // Se gli strumenti sono stati eseguiti in un container, reinvia il suo ID per conservarne i file
          if (response.Container is not null)
          {
              container = response.Container.ID;
          }
      } while (++requestCount < maxRequests);

      // Ancora in pausa dopo maxRequests richieste: restituisci l'ultima risposta
      return response;
  }

  var response = await HandleServerToolConversation(
      client,
      "Use the code execution tool to find the 1,000th prime number.",
      [new CodeExecutionTool20250825()]);
  Console.WriteLine(response.StopReason?.Raw());
  ```

  ```go Go
  func handleServerToolConversation(
  	client anthropic.Client,
  	userQuery string,
  	tools []anthropic.ToolUnionParam,
  	maxRequests int,
  ) (*anthropic.Message, error) {
  	messages := []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock(userQuery)),
  	}
  	var container anthropic.MessageCreateParamsContainerUnion
  	var response *anthropic.Message
  	var err error

  	for range maxRequests {
  		response, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  			Model:     anthropic.ModelClaudeOpus5_5,
  			MaxTokens: 4096,
  			Messages:  messages,
  			Tools:     tools,
  			Container: container,
  		})
  		if err != nil {
  			return nil, err
  		}

  		if response.StopReason != anthropic.StopReasonPauseTurn {
  			// Non in pausa: restituisci la risposta
  			return response, nil
  		}

  		// pause_turn: aggiungi la risposta in pausa come messaggio dell'assistente, poi continua
  		messages = append(messages, response.ToParam())

  		// Se gli strumenti sono stati eseguiti in un container, rimanda il suo ID per conservarne i file
  		if response.Container.ID != "" {
  			container.OfString = anthropic.String(response.Container.ID)
  		}
  	}

  	// Ancora in pausa dopo maxRequests richieste: restituisci l'ultima risposta
  	return response, nil
  }

  func main() {
  	client := anthropic.NewClient()

  	response, err := handleServerToolConversation(
  		client,
  		"Use the code execution tool to find the 1,000th prime number.",
  		[]anthropic.ToolUnionParam{
  			{OfCodeExecutionTool20250825: &anthropic.CodeExecutionTool20250825Param{}},
  		},
  		5,
  	)
  	if err != nil {
  		log.Fatal(err)
  	}
  	fmt.Println(response.StopReason)
  }
  ```

  ```java Java
  Message handleServerToolConversation(
      AnthropicClient client,
      String userQuery,
      List<ToolUnion> tools,
      int maxRequests
  ) {
      var params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .tools(tools)
          .addUserMessage(userQuery);
      Message response = null;

      for (int request = 0; request < maxRequests; request++) {
          response = client.messages().create(params.build());

          boolean paused = response.stopReason().filter(StopReason.PAUSE_TURN::equals).isPresent();
          if (!paused) {
              // Non in pausa: restituisci la risposta
              return response;
          }

          // pause_turn: aggiungi la risposta in pausa come messaggio assistant, poi continua
          params.addMessage(response);

          // Se gli strumenti sono stati eseguiti in un container, reinvia il suo ID per conservarne i file
          response.container().ifPresent(container -> params.container(container.id()));
      }

      // Ancora in pausa dopo maxRequests richieste: restituisci l'ultima risposta
      return response;
  }

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      Message response = handleServerToolConversation(
          client,
          "Use the code execution tool to find the 1,000th prime number.",
          List.of(ToolUnion.ofCodeExecutionTool20250825(CodeExecutionTool20250825.builder().build())),
          5
      );
      response.stopReason().ifPresent(IO::println);
  }
  ```

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

  function handle_server_tool_conversation(
      Client $client,
      string $userQuery,
      array $tools,
      int $maxRequests = 5,
  ): Message {
      $messages = [['role' => 'user', 'content' => $userQuery]];
      $containerId = null;
      $requestCount = 0;

      do {
          $response = $client->messages->create(
              maxTokens: 4096,
              messages: $messages,
              model: Model::CLAUDE_OPUS_5_5,
              tools: $tools,
              container: $containerId,
          );

          if ($response->stopReason !== StopReason::PAUSE_TURN->value) {
              // Non in pausa: restituisci la risposta
              return $response;
          }

          // pause_turn: aggiungi la risposta in pausa come messaggio dell'assistente, poi continua
          $messages[] = ['role' => 'assistant', 'content' => $response->content];

          // Se gli strumenti sono stati eseguiti in un container, rinvia il suo ID per conservarne i file
          $containerId = $response->container->id ?? $containerId;
      } while (++$requestCount < $maxRequests);

      // Ancora in pausa dopo $maxRequests richieste: restituisci l'ultima risposta
      return $response;
  }

  $response = handle_server_tool_conversation(
      $client,
      'Use the code execution tool to find the 1,000th prime number.',
      [new CodeExecutionTool20250825()],
  );
  echo $response->stopReason, PHP_EOL;
  ```

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

  def handle_server_tool_conversation(client, user_query, tools, max_requests: 5)
    messages = [{ role: "user", content: user_query }]
    container_id = nil
    response = nil

    max_requests.times do
      response = client.messages.create(
        model: Anthropic::Model::CLAUDE_OPUS_5_5,
        max_tokens: 4096,
        messages:,
        tools:,
        container: container_id
      )

      # Non in pausa: restituisci la risposta
      return response unless response.stop_reason == :pause_turn

      # pause_turn: aggiungi la risposta in pausa come messaggio dell'assistente, poi continua
      messages << { role: "assistant", content: response.content }

      # Se gli strumenti sono stati eseguiti in un container, rinvia il suo ID per conservarne i file
      container_id = response.container&.id || container_id
    end

    # Ancora in pausa dopo max_requests richieste: restituisci l'ultima risposta
    response
  end

  response = handle_server_tool_conversation(
    client,
    "Use the code execution tool to find the 1,000th prime number.",
    [Anthropic::CodeExecutionTool20250825.new]
  )
  puts response.stop_reason
  ```
</CodeGroup>

La funzione restituisce l’ultima risposta, che contiene solo la parte finale del turno. Per mostrare l’intero turno o per continuare la conversazione, conserva anche le risposte in pausa.

## Motivi di arresto e errori a confronto

È importante distinguere tra i valori di `stop_reason` e gli errori veri e propri:

### Motivi di arresto (risposte riuscite)

* Fanno parte del corpo della risposta
* Indicano perché la generazione si è fermata normalmente
* La risposta contiene contenuto valido

### Errori (richieste fallite)

* Codici di stato HTTP 4xx o 5xx
* Indicano fallimenti nell’elaborazione della richiesta
* La risposta contiene i dettagli dell’errore

<CodeGroup>
  ```bash cURL
  # Con --fail-with-body cURL esce con codice diverso da zero sugli errori HTTP; controlla
  # $? per gli errori e stop_reason per le risposte riuscite.
  curl --fail-with-body https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello!"}]
    }'
  ```

  ```bash CLI
  # La CLI termina con codice diverso da zero in caso di errori API; stop_reason compare in caso di successo.
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello!"}'
  ```

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

  try:
      response = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          messages=[{"role": "user", "content": "Hello!"}],
      )

      # Gestisci la risposta riuscita con stop_reason
      if response.stop_reason == "max_tokens":
          print("Response was truncated")

  except anthropic.APIStatusError as e:
      # Gestisci gli errori effettivi
      match e.status_code:
          case 429:
              print("Rate limit exceeded")
          case 500:
              print("Server error")
  ```

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

  try {
    const response = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello!" }]
    });

    // Gestisci la risposta riuscita con stop_reason
    if (response.stop_reason === "max_tokens") {
      console.log("Response was truncated");
    }
  } catch (err) {
    // Gestisci gli errori effettivi
    if (err instanceof Anthropic.APIError) {
      switch (err.status) {
        case 429:
          console.log("Rate limit exceeded");
          break;
        case 500:
          console.log("Server error");
          break;
      }
    } else {
      throw err;
    }
  }
  ```

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

  try
  {
      var response = await client.Messages.Create(new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Messages = [new UserMessageParam { Content = "Hello!" }]
      });

      // Gestisci la risposta riuscita con stop_reason
      if (response.StopReason == "max_tokens")
      {
          Console.WriteLine("Response was truncated");
      }
  }
  catch (AnthropicRateLimitException)
  {
      // Gestisci gli errori effettivi
      Console.WriteLine("Rate limit exceeded");
  }
  catch (Anthropic5xxException)
  {
      Console.WriteLine("Server error");
  }
  ```

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello!")),
  	},
  })
  if err != nil {
  	// Gestisci gli errori effettivi
  	var apiErr *anthropic.Error
  	if errors.As(err, &apiErr) {
  		switch apiErr.StatusCode {
  		case 429:
  			fmt.Println("Rate limit exceeded")
  		case 500:
  			fmt.Println("Server error")
  		}
  	}
  	log.Fatal(err)
  }

  // Gestisci la risposta riuscita con stop_reason
  if response.StopReason == "max_tokens" {
  	fmt.Println("Response was truncated")
  }
  ```

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

  try {
      Message response = client.messages().create(
          MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(1024L)
              .addUserMessage("Hello!")
              .build()
      );

      // Gestisci la risposta riuscita con stop_reason
      if (response.stopReason().map(StopReason.MAX_TOKENS::equals).orElse(false)) {
          IO.println("Response was truncated");
      }
  } catch (RateLimitException e) {
      // Gestisci gli errori effettivi
      IO.println("Rate limit exceeded");
  } catch (AnthropicServiceException e) {
      if (e.statusCode() == 500) {
          IO.println("Server error");
      }
  }
  ```

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

  try {
      $response = $client->messages->create(
          maxTokens: 1024,
          messages: [['role' => 'user', 'content' => 'Hello!']],
          model: Model::CLAUDE_OPUS_5_5,
      );

      // Gestisci la risposta riuscita con stop_reason
      if ($response->stopReason === 'max_tokens') {
          echo 'Response was truncated', PHP_EOL;
      }
  } catch (RateLimitException $e) {
      // Gestisci gli errori effettivi
      echo 'Rate limit exceeded', PHP_EOL;
  } catch (InternalServerException $e) {
      echo 'Server error', PHP_EOL;
  }
  ```

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

  begin
    response = client.messages.create(
      model: Anthropic::Model::CLAUDE_OPUS_5_5,
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello!" }]
    )

    # Gestisci la risposta riuscita con stop_reason
    if response.stop_reason == :max_tokens
      puts "Response was truncated"
    end
  rescue Anthropic::Errors::RateLimitError
    # Gestisci gli errori effettivi
    puts "Rate limit exceeded"
  rescue Anthropic::Errors::APIStatusError => e
    puts "Server error" if e.status == 500
  end
  ```
</CodeGroup>

## Considerazioni sullo streaming

Quando usi lo streaming, `stop_reason` è:

* `null` nell’evento iniziale `message_start`
* Fornito nell’evento `message_delta`
* Non fornito in nessun altro evento

<CodeGroup>
  ```bash cURL
  # L'evento message_delta nello stream SSE contiene stop_reason.
  curl -N https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "stream": true,
      "messages": [{"role": "user", "content": "Hello!"}]
    }'
  ```

  ```bash CLI
  # stop_reason compare nell'evento message_delta.
  ant messages create --stream \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello!"}'
  ```

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

  with client.messages.stream(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello!"}],
  ) as stream:
      for event in stream:
          if event.type == "message_delta":
              stop_reason = event.delta.stop_reason
              if stop_reason:
                  print(f"Stream ended with: {stop_reason}")
  ```

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

  const stream = client.messages.stream({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello!" }]
  });

  for await (const event of stream) {
    if (event.type === "message_delta" && event.delta.stop_reason) {
      console.log(`Stream ended with: ${event.delta.stop_reason}`);
    }
  }
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new UserMessageParam { Content = "Hello!" }]
  };

  await foreach (var streamEvent in client.Messages.CreateStreaming(parameters))
  {
      switch (streamEvent.Value)
      {
          case RawMessageDeltaEvent deltaEvent when deltaEvent.Delta.StopReason is not null:
              Console.WriteLine($"Stream ended with: {deltaEvent.Delta.StopReason}");
              break;
      }
  }
  ```

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

  stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello!")),
  	},
  })

  // Accumula gli eventi nel Message finale, che contiene stop_reason.
  message := anthropic.Message{}
  for stream.Next() {
  	if err := message.Accumulate(stream.Current()); err != nil {
  		log.Fatal(err)
  	}
  }
  if err := stream.Err(); err != nil {
  	log.Fatal(err)
  }

  if message.StopReason != "" {
  	fmt.Printf("Stream ended with: %s\n", message.StopReason)
  }
  ```

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

  MessageCreateParams params = MessageCreateParams.builder()
      .model(Model.CLAUDE_OPUS_5_5)
      .maxTokens(1024L)
      .addUserMessage("Hello!")
      .build();

  // Accumula gli eventi nel Message finale, che contiene stop_reason.
  MessageAccumulator accumulator = MessageAccumulator.create();
  try (StreamResponse<RawMessageStreamEvent> streamResponse =
          client.messages().createStreaming(params)) {
      streamResponse.stream().forEach(accumulator::accumulate);
  }

  accumulator.message().stopReason().ifPresent(stopReason ->
      IO.println("Stream ended with: " + stopReason)
  );
  ```

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

  $stream = $client->messages->createStream(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello!']],
      model: Model::CLAUDE_OPUS_5_5,
  );

  foreach ($stream as $event) {
      if ($event instanceof \Anthropic\Messages\RawMessageDeltaEvent && $event->delta->stopReason !== null) {
          echo "Stream ended with: {$event->delta->stopReason}", PHP_EOL;
      }
  }
  ```

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

  stream = client.messages.stream(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello!" }]
  )

  stream.each do |event|
    next unless event.type == :message_delta
    stop_reason = event.delta.stop_reason
    puts "Stream ended with: #{stop_reason}" if stop_reason
  end
  ```
</CodeGroup>

## Pattern comuni

### Gestione dei flussi di lavoro con uso degli strumenti

<Tip>
  **Più semplice con il tool runner:** L’esempio seguente mostra la gestione manuale degli strumenti. Per la maggior parte dei casi d’uso, il [tool runner](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-runner) gestisce automaticamente l’esecuzione degli strumenti con molto meno codice.
</Tip>

<CodeGroup exclude="shell">
  ```python Python
  def complete_tool_workflow(client, user_query, tools):
      messages = [{"role": "user", "content": user_query}]

      while True:
          response = client.messages.create(
              model="claude-opus-5-5",
              max_tokens=1024,
              messages=messages,
              tools=tools,
          )

          if response.stop_reason == "tool_use":
              # Esegui gli strumenti e continua
              tool_results = execute_tools(response.content)
              messages.append({"role": "assistant", "content": response.content})
              messages.append({"role": "user", "content": tool_results})
          else:
              # Risposta finale
              return response
  ```

  ```typescript TypeScript
  async function completeToolWorkflow(
    client: Anthropic,
    userQuery: string,
    tools: Anthropic.ToolUnion[]
  ): Promise<Anthropic.Message> {
    const messages: Anthropic.MessageParam[] = [{ role: "user", content: userQuery }];

    while (true) {
      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages,
        tools
      });

      if (response.stop_reason === "tool_use") {
        // Esegui gli strumenti e continua
        const toolResults = executeTools(response.content);
        messages.push({ role: "assistant", content: response.content });
        messages.push({ role: "user", content: toolResults });
      } else {
        // Risposta finale
        return response;
      }
    }
  }
  ```

  ```csharp C#
  static async Task<Message> CompleteToolWorkflow(
      AnthropicClient client,
      string userQuery,
      List<ToolUnion> tools)
  {
      List<MessageParam> messages = [new UserMessageParam { Content = userQuery }];

      while (true)
      {
          var response = await client.Messages.Create(new MessageCreateParams
          {
              Model = Model.ClaudeOpus5_5,
              MaxTokens = 1024,
              Messages = messages,
              Tools = tools
          });

          if (response.StopReason == "tool_use")
          {
              // Esegui gli strumenti e continua
              var toolResults = ExecuteTools(response.Content);
              messages.Add(new AssistantMessageParam
              {
                  Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList()
              });
              messages.Add(new UserMessageParam { Content = toolResults });
          }
          else
          {
              // Risposta finale
              return response;
          }
      }
  }
  ```

  ```go Go
  func completeToolWorkflow(
  	client anthropic.Client,
  	userQuery string,
  	tools []anthropic.ToolUnionParam,
  ) (*anthropic.Message, error) {
  	messages := []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(userQuery))}

  	for {
  		response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  			Model:     anthropic.ModelClaudeOpus5_5,
  			MaxTokens: 1024,
  			Messages:  messages,
  			Tools:     tools,
  		})
  		if err != nil {
  			return nil, err
  		}

  		if response.StopReason != "tool_use" {
  			// Risposta finale
  			return response, nil
  		}

  		// Esegui gli strumenti e continua
  		toolResults := executeTools(response.Content)
  		var contentParams []anthropic.ContentBlockParamUnion
  		for _, block := range response.Content {
  			contentParams = append(contentParams, block.ToParam())
  		}
  		messages = append(messages, anthropic.NewAssistantMessage(contentParams...))
  		messages = append(messages, anthropic.NewUserMessage(toolResults...))
  	}
  }
  ```

  ```java Java
  static Message completeToolWorkflow(
      AnthropicClient client,
      String userQuery,
      List<Tool> tools
  ) {
      List<MessageParam> messages = new ArrayList<>();
      messages.add(MessageParam.ofUser(userQuery));

      while (true) {
          MessageCreateParams.Builder params = MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(1024L)
              .messages(messages);
          tools.forEach(params::addTool);

          Message response = client.messages().create(params.build());

          if (!response.stopReason().map(StopReason.TOOL_USE::equals).orElse(false)) {
              // Risposta finale
              return response;
          }

          // Esegui gli strumenti e continua
          List<ToolResultBlockParam> toolResults = executeTools(response.content());
          messages.add(response.toParam());
          messages.add(MessageParam.ofUserOfContentBlockParams(
              toolResults.stream().map(ContentBlockParam::ofToolResult).toList()));
      }
  }
  ```

  ```php PHP
  function complete_tool_workflow(Client $client, string $userQuery, array $tools)
  {
      $messages = [['role' => 'user', 'content' => $userQuery]];

      while (true) {
          $response = $client->messages->create(
              maxTokens: 1024,
              messages: $messages,
              model: 'claude-opus-5-5',
              tools: $tools,
          );

          if ($response->stopReason !== 'tool_use') {
              // Risposta finale
              return $response;
          }

          // Esegui gli strumenti e continua
          $toolResults = execute_tools($response->content);
          $messages[] = ['role' => 'assistant', 'content' => $response->content];
          $messages[] = ['role' => 'user', 'content' => $toolResults];
      }
  }
  ```

  ```ruby Ruby
  def complete_tool_workflow(client, user_query, tools)
    messages = [{ role: "user", content: user_query }]

    loop do
      response = client.messages.create(
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages: messages,
        tools: tools
      )

      # Risposta finale
      return response unless response.stop_reason == :tool_use

      # Esegui gli strumenti e continua
      tool_results = execute_tools(response.content)
      messages << { role: "assistant", content: response.content }
      messages << { role: "user", content: tool_results }
    end
  end
  ```
</CodeGroup>

### Garantire risposte complete

<CodeGroup exclude="shell">
  ```python Python
  def get_complete_response(client, prompt, max_attempts=3):
      messages = [{"role": "user", "content": prompt}]
      full_response = ""

      for _ in range(max_attempts):
          response = client.messages.create(
              model="claude-opus-5-5", messages=messages, max_tokens=4096
          )

          full_response += next(
              (block.text for block in response.content if block.type == "text"), ""
          )

          if response.stop_reason != "max_tokens":
              break

          # Riprendi da dove si era interrotto
          messages = [
              {"role": "user", "content": prompt},
              {"role": "assistant", "content": full_response},
              {"role": "user", "content": "Please continue from where you left off."},
          ]

      return full_response
  ```

  ```typescript TypeScript
  async function getCompleteResponse(
    client: Anthropic,
    prompt: string,
    maxAttempts = 3
  ): Promise<string> {
    let messages: Anthropic.MessageParam[] = [{ role: "user", content: prompt }];
    let fullResponse = "";

    for (let i = 0; i < maxAttempts; i++) {
      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 4096,
        messages
      });

      const textBlock = response.content.find((block) => block.type === "text");
      fullResponse += textBlock?.text ?? "";

      if (response.stop_reason !== "max_tokens") {
        break;
      }

      // Riprendi da dove si era interrotto
      messages = [
        { role: "user", content: prompt },
        { role: "assistant", content: fullResponse },
        { role: "user", content: "Please continue from where you left off." }
      ];
    }

    return fullResponse;
  }
  ```

  ```csharp C#
  static async Task<string> GetCompleteResponse(AnthropicClient client, string prompt, int maxAttempts = 3)
  {
      List<MessageParam> messages = [new UserMessageParam { Content = prompt }];
      var fullResponse = "";

      for (var i = 0; i < maxAttempts; i++)
      {
          var response = await client.Messages.Create(new MessageCreateParams
          {
              Model = Model.ClaudeOpus5_5,
              MaxTokens = 4096,
              Messages = messages
          });

          foreach (var block in response.Content)
          {
              if (block.TryPickText(out var textBlock))
              {
                  fullResponse += textBlock.Text;
                  break;
              }
          }

          if (response.StopReason != "max_tokens")
          {
              break;
          }

          // Riprendi da dove si era interrotto
          messages =
          [
              new UserMessageParam { Content = prompt },
              new AssistantMessageParam { Content = fullResponse },
              new UserMessageParam { Content = "Please continue from where you left off." }
          ];
      }

      return fullResponse;
  }
  ```

  ```go Go
  func getCompleteResponse(client anthropic.Client, prompt string, maxAttempts int) (string, error) {
  	messages := []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(prompt))}
  	fullResponse := ""

  	for range maxAttempts {
  		response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  			Model:     anthropic.ModelClaudeOpus5_5,
  			MaxTokens: 4096,
  			Messages:  messages,
  		})
  		if err != nil {
  			return "", err
  		}

  		for _, block := range response.Content {
  			if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  				fullResponse += textBlock.Text
  				break
  			}
  		}

  		if response.StopReason != "max_tokens" {
  			break
  		}

  		// Riprendi da dove si era interrotto
  		messages = []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),
  			anthropic.NewAssistantMessage(anthropic.NewTextBlock(fullResponse)),
  			anthropic.NewUserMessage(anthropic.NewTextBlock("Please continue from where you left off.")),
  		}
  	}

  	return fullResponse, nil
  }
  ```

  ```java Java
  static String getCompleteResponse(AnthropicClient client, String prompt, int maxAttempts) {
      List<MessageParam> messages = List.of(MessageParam.ofUser(prompt));
      StringBuilder fullResponse = new StringBuilder();

      for (int i = 0; i < maxAttempts; i++) {
          Message response = client.messages().create(
              MessageCreateParams.builder()
                  .model(Model.CLAUDE_OPUS_5_5)
                  .maxTokens(4096L)
                  .messages(messages)
                  .build()
          );

          response.content().stream()
              .filter(ContentBlock::isText)
              .findFirst()
              .ifPresent(block -> fullResponse.append(block.asText().text()));

          if (!response.stopReason().map(StopReason.MAX_TOKENS::equals).orElse(false)) {
              break;
          }

          // Riprendi da dove si era interrotto
          messages = List.of(
              MessageParam.ofUser(prompt),
              MessageParam.ofAssistant(fullResponse.toString()),
              MessageParam.ofUser("Please continue from where you left off.")
          );
      }

      return fullResponse.toString();
  }
  ```

  ```php PHP
  function get_complete_response(Client $client, string $prompt, int $maxAttempts = 3): string
  {
      $messages = [['role' => 'user', 'content' => $prompt]];
      $fullResponse = '';

      for ($i = 0; $i < $maxAttempts; $i++) {
          $response = $client->messages->create(
              maxTokens: 4096,
              messages: $messages,
              model: 'claude-opus-5-5',
          );

          $fullResponse .= array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '';

          if ($response->stopReason !== 'max_tokens') {
              break;
          }

          // Riprendi da dove si era interrotto
          $messages = [
              ['role' => 'user', 'content' => $prompt],
              ['role' => 'assistant', 'content' => $fullResponse],
              ['role' => 'user', 'content' => 'Please continue from where you left off.'],
          ];
      }

      return $fullResponse;
  }
  ```

  ```ruby Ruby
  def get_complete_response(client, prompt, max_attempts: 3)
    messages = [{ role: "user", content: prompt }]
    full_response = +""

    max_attempts.times do
      response = client.messages.create(
        model: "claude-opus-5-5",
        max_tokens: 4096,
        messages: messages
      )

      full_response << response.content.find { it.type == :text }&.text.to_s

      break unless response.stop_reason == :max_tokens

      # Riprendi da dove si era interrotto
      messages = [
        { role: "user", content: prompt },
        { role: "assistant", content: full_response },
        { role: "user", content: "Please continue from where you left off." }
      ]
    end

    full_response
  end
  ```
</CodeGroup>

### Ottenere il massimo numero di token senza conoscere la dimensione dell’input

Con il motivo di arresto `model_context_window_exceeded`, puoi richiedere il massimo numero possibile di token senza calcolare la dimensione dell’input:

<CodeGroup exclude="shell">
  ```python Python
  def get_max_possible_tokens(client, prompt):
      """
      Get as many tokens as possible within the model's context window
      without needing to calculate input token count
      """
      response = client.beta.messages.create(
          model="claude-opus-5-5",
          messages=[{"role": "user", "content": prompt}],
          max_tokens=20000,  # Python SDK requires streaming for max_tokens above ~21k
      )

      match response.stop_reason:
          case "model_context_window_exceeded":
              # Ottenuto il numero massimo di token possibile data la dimensione dell'input
              print(
                  f"Generated {response.usage.output_tokens} tokens (context limit reached)"
              )
          case "max_tokens":
              # Ottenuto esattamente il numero di token richiesto
              print(
                  f"Generated {response.usage.output_tokens} tokens (max_tokens reached)"
              )
          case _:
              # Completamento naturale
              print(
                  f"Generated {response.usage.output_tokens} tokens (natural completion)"
              )

      return next((block.text for block in response.content if block.type == "text"), "")
  ```

  ```typescript TypeScript
  async function getMaxPossibleTokens(client: Anthropic, prompt: string): Promise<string> {
    const response = await client.beta.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 20000,
      messages: [{ role: "user", content: prompt }]
    });

    const tokens = response.usage.output_tokens;
    switch (response.stop_reason) {
      case "model_context_window_exceeded":
        // Ottenuto il numero massimo di token possibile data la dimensione dell'input
        console.log(`Generated ${tokens} tokens (context limit reached)`);
        break;
      case "max_tokens":
        // Ottenuto esattamente il numero di token richiesto
        console.log(`Generated ${tokens} tokens (max_tokens reached)`);
        break;
      default:
        // Completamento naturale
        console.log(`Generated ${tokens} tokens (natural completion)`);
    }

    const textBlock = response.content.find((block) => block.type === "text");
    return textBlock?.text ?? "";
  }
  ```

  ```csharp C#
  using Anthropic.Models.Beta.Messages;
  using Model = Anthropic.Models.Messages.Model;

  static async Task<string> GetMaxPossibleTokens(AnthropicClient client, string prompt)
  {
      var response = await client.Beta.Messages.Create(new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 20000,
          Messages = [new BetaUserMessageParam { Content = prompt }]
      });

      var tokens = response.Usage.OutputTokens;
      var reason = response.StopReason?.Value();
      if (reason == BetaStopReason.ModelContextWindowExceeded)
      {
          // Ottenuto il numero massimo di token possibile data la dimensione dell'input
          Console.WriteLine($"Generated {tokens} tokens (context limit reached)");
      }
      else if (reason == BetaStopReason.MaxTokens)
      {
          // Ottenuto esattamente il numero di token richiesto
          Console.WriteLine($"Generated {tokens} tokens (max_tokens reached)");
      }
      else
      {
          // Completamento naturale
          Console.WriteLine($"Generated {tokens} tokens (natural completion)");
      }

      return response.Content.Select(b => b.Value).OfType<BetaTextBlock>().FirstOrDefault()?.Text ?? "";
  }
  ```

  ```go Go
  func getMaxPossibleTokens(client anthropic.Client, prompt string) (string, error) {
  	response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
  		Model:     anthropic.ModelClaudeOpus5_5,
  		MaxTokens: 20000,
  		Messages: []anthropic.BetaMessageParam{
  			anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(prompt)),
  		},
  	})
  	if err != nil {
  		return "", err
  	}

  	tokens := response.Usage.OutputTokens
  	switch response.StopReason {
  	case anthropic.BetaStopReasonModelContextWindowExceeded:
  		// Ottenuto il numero massimo di token possibile data la dimensione dell'input
  		fmt.Printf("Generated %d tokens (context limit reached)\n", tokens)
  	case anthropic.BetaStopReasonMaxTokens:
  		// Ottenuto esattamente il numero di token richiesto
  		fmt.Printf("Generated %d tokens (max_tokens reached)\n", tokens)
  	default:
  		// Completamento naturale
  		fmt.Printf("Generated %d tokens (natural completion)\n", tokens)
  	}

  	for _, block := range response.Content {
  		if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
  			return textBlock.Text, nil
  		}
  	}
  	return "", nil
  }
  ```

  ```java Java
  import com.anthropic.models.beta.messages.BetaContentBlock;
  import com.anthropic.models.beta.messages.BetaMessage;
  import com.anthropic.models.beta.messages.BetaStopReason;
  import com.anthropic.models.beta.messages.MessageCreateParams;

  static String getMaxPossibleTokens(AnthropicClient client, String prompt) {
      BetaMessage response = client.beta().messages().create(
          MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(20000L)
              .addUserMessage(prompt)
              .build()
      );

      long tokens = response.usage().outputTokens();
      BetaStopReason reason = response.stopReason().orElse(BetaStopReason.END_TURN);
      if (reason.equals(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED)) {
          // Ottenuto il numero massimo di token possibile data la dimensione dell'input
          IO.println("Generated " + tokens + " tokens (context limit reached)");
      } else if (reason.equals(BetaStopReason.MAX_TOKENS)) {
          // Ottenuto esattamente il numero di token richiesto
          IO.println("Generated " + tokens + " tokens (max_tokens reached)");
      } else {
          // Completamento naturale
          IO.println("Generated " + tokens + " tokens (natural completion)");
      }

      return response.content().stream()
          .filter(BetaContentBlock::isText)
          .findFirst()
          .map(block -> block.asText().text())
          .orElse("");
  }
  ```

  ```php PHP
  function get_max_possible_tokens(Client $client, string $prompt): string
  {
      $response = $client->beta->messages->create(
          maxTokens: 20000,
          messages: [['role' => 'user', 'content' => $prompt]],
          model: 'claude-opus-5-5',
      );

      $tokens = $response->usage->outputTokens;
      echo match ($response->stopReason) {
          // Ottenuto il numero massimo di token possibile data la dimensione dell'input
          'model_context_window_exceeded' => "Generated {$tokens} tokens (context limit reached)",
          // Ottenuto esattamente il numero di token richiesto
          'max_tokens' => "Generated {$tokens} tokens (max_tokens reached)",
          // Completamento naturale
          default => "Generated {$tokens} tokens (natural completion)",
      }, PHP_EOL;

      return array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '';
  }
  ```

  ```ruby Ruby
  def get_max_possible_tokens(client, prompt)
    response = client.beta.messages.create(
      model: "claude-opus-5-5",
      max_tokens: 20000,
      messages: [{ role: "user", content: prompt }]
    )

    tokens = response.usage.output_tokens
    case response.stop_reason
    when :model_context_window_exceeded
      # Ottenuto il numero massimo di token possibile data la dimensione dell'input
      puts "Generated #{tokens} tokens (context limit reached)"
    when :max_tokens
      # Ottenuto esattamente il numero di token richiesto
      puts "Generated #{tokens} tokens (max_tokens reached)"
    else
      # Completamento naturale
      puts "Generated #{tokens} tokens (natural completion)"
    end

    response.content.find { it.type == :text }.text
  end
  ```
</CodeGroup>

## Prossimi passi

<CardGroup cols={2}>
  <Card title="Rifiuti e fallback" icon="arrows-clockwise" href="https://platform.claude.com/docs/it/build-with-claude/refusals-and-fallback">
    Riprova le richieste rifiutate su un modello di fallback, lato server o nel tuo client.
  </Card>

  <Card title="Tool runner (SDK)" icon="wrench" href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-runner">
    Lascia che l’SDK gestisca per te il ciclo `tool_use`, la formattazione dei risultati e i nuovi tentativi.
  </Card>

  <Card title="Messaggi in streaming" icon="lightning" href="https://platform.claude.com/docs/it/build-with-claude/streaming">
    Leggi `stop_reason` dall’evento `message_delta` durante lo streaming.
  </Card>

  <Card title="Errori" icon="info" href="https://platform.claude.com/docs/it/api/errors">
    Gestisci gli errori HTTP 4xx e 5xx, che sono distinti dai motivi di arresto.
  </Card>
</CardGroup>
