---
title: Il ragionamento nei flussi di lavoro con strumenti e multi-turno
url: https://platform.claude.com/docs/it/build-with-claude/thinking-tool-workflows
description: Segui passo dopo passo un ciclo completo di uso degli strumenti in due turni che preserva correttamente i blocchi di ragionamento, e osserva come il ragionamento interlacciato modifica il flusso.
---

<Note>
  Per scoprire come la "zero data retention" (conservazione zero dei dati), o ZDR, si applica a questa funzionalità, consulta [API e conservazione dei dati](https://platform.claude.com/docs/it/manage-claude/api-and-data-retention).
</Note>

Questa pagina illustra passo dopo passo un ciclo completo di "tool use" (uso degli strumenti) in due turni con il ragionamento abilitato: Claude pensa, richiede una chiamata a uno strumento, riceve il risultato e completa la sua risposta, con i blocchi di ragionamento gestiti correttamente in ogni fase. Le regole complete si trovano nella pagina [Ragionamento](https://platform.claude.com/docs/it/build-with-claude/thinking), in [Ragionamento con uso degli strumenti](https://platform.claude.com/docs/it/build-with-claude/thinking#thinking-with-tool-use) e [Preservare i blocchi di ragionamento](https://platform.claude.com/docs/it/build-with-claude/thinking#preserving-thinking-blocks); questa pagina mostra tali regole applicate in codice eseguibile.

## Le regole applicate in questa guida

Ogni link porta all'enunciazione completa nella pagina Ragionamento:

* [Limita la scelta dello strumento ad `auto` o `none` in modalità manuale](https://platform.claude.com/docs/it/build-with-claude/thinking#thinking-with-tool-use): le opzioni di `tool_choice` che forzano l'uso degli strumenti restituiscono un errore con il ragionamento esteso manuale (`thinking: {type: "enabled"}`). L'"adaptive thinking" (ragionamento adattivo) supporta l'uso forzato degli strumenti, tranne su Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 e Claude Mythos 5.1, che restituiscono un errore 400. Dove l'uso forzato degli strumenti è accettato, il ragionamento viene saltato: la risposta inizia con la chiamata allo strumento.
* [Mantieni una sola configurazione di ragionamento per turno dell'assistente](https://platform.claude.com/docs/it/build-with-claude/thinking#thinking-with-tool-use): un ciclo di uso degli strumenti è un singolo turno dell'assistente, quindi modifica la configurazione solo tra un turno e l'altro.
* [Restituisci i blocchi di ragionamento completi e non modificati](https://platform.claude.com/docs/it/build-with-claude/thinking#preserving-thinking-blocks): quando restituisci un risultato di uno strumento, i blocchi di ragionamento del messaggio dell'assistente devono tornare insieme ad esso.
* [Ripeti il messaggio dell'assistente esattamente come ricevuto](https://platform.claude.com/docs/it/build-with-claude/thinking#preserving-thinking-blocks): ricostruire il messaggio o filtrare i blocchi `redacted_thinking` provoca un errore 400.

Gli esempi usano il ragionamento adattivo; sui modelli che supportano solo il ragionamento esteso, sostituisci con `thinking: {type: "enabled", budget_tokens: N}`. Le regole del ciclo sono identiche.

## Segui un ciclo di uso degli strumenti in due turni

L'esempio definisce uno strumento `get_weather`, lascia che Claude pensi e richieda una chiamata allo strumento, quindi restituisce il risultato dello strumento insieme al turno dell'assistente ripetuto esattamente come ricevuto, blocco di ragionamento incluso.

<Steps>
  <Step title="Effettua la prima richiesta con uno strumento disponibile">
    Invia una richiesta con il ragionamento adattivo abilitato e lo strumento definito. A parte il parametro `thinking`, si tratta di una richiesta standard di [uso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/overview):

    <CodeGroup>
      ```bash cURL
      curl https://api.anthropic.com/v1/messages \
        -H "anthropic-version: 2023-06-01" \
        -H "content-type: application/json" \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -d '{
          "model": "claude-opus-5-5",
          "max_tokens": 16000,
          "thinking": {"type": "adaptive"},
          "tools": [{
            "name": "get_weather",
            "description": "Get current weather for a location",
            "input_schema": {
              "type": "object",
              "properties": {
                "location": {"type": "string", "description": "City name"}
              },
              "required": ["location"]
            }
          }],
          "messages": [{"role": "user", "content": "What is the weather in Paris?"}]
        }'
      ```

      ```bash CLI
      ant messages create --transform content <<'YAML'
      model: claude-opus-5-5
      max_tokens: 16000
      thinking:
        type: adaptive
      tools:
        - name: get_weather
          description: Get current weather for a location
          input_schema:
            type: object
            properties:
              location:
                type: string
                description: City name
            required:
              - location
      messages:
        - role: user
          content: "What's the weather in Paris?"
      YAML
      ```

      ```python Python

      client = anthropic.Anthropic()

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

      # Prima richiesta - Claude risponde con il ragionamento e una richiesta di strumento
      response = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=16000,
          thinking={"type": "adaptive"},
          tools=[weather_tool],
          messages=[{"role": "user", "content": "What's the weather in Paris?"}],
      )
      print(response)
      ```

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

      const weatherTool: Anthropic.Tool = {
        name: "get_weather",
        description: "Get current weather for a location",
        input_schema: {
          type: "object",
          properties: {
            location: { type: "string", description: "City name" }
          },
          required: ["location"]
        }
      };

      // Prima richiesta - Claude risponde con il ragionamento e la richiesta dello strumento
      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 16000,
        thinking: {
          type: "adaptive"
        },
        tools: [weatherTool],
        messages: [{ role: "user", content: "What's the weather in Paris?" }]
      });
      console.log(response);
      ```

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

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

      var parameters = new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 16000,
          Thinking = new ThinkingConfigAdaptive(),
          Tools = [weatherTool],
          Messages = [new() { Role = Role.User, Content = "What's the weather in Paris?" }]
      };

      var message = await client.Messages.Create(parameters);
      Console.WriteLine(message);
      ```

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

      weatherTool := anthropic.ToolUnionParam{
      	OfTool: &anthropic.ToolParam{
      		Name:        "get_weather",
      		Description: anthropic.String("Get current weather for a location"),
      		InputSchema: anthropic.ToolInputSchemaParam{
      			Properties: map[string]any{
      				"location": map[string]any{
      					"type":        "string",
      					"description": "City name",
      				},
      			},
      			Required: []string{"location"},
      		},
      	},
      }

      response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
      	Model:     anthropic.ModelClaudeOpus5_5,
      	MaxTokens: 16000,
      	Thinking: anthropic.ThinkingConfigParamUnion{
      		OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
      	},
      	Tools: []anthropic.ToolUnionParam{weatherTool},
      	Messages: []anthropic.MessageParam{
      		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather in Paris?")),
      	},
      })
      if err != nil {
      	log.Fatal(err)
      }
      fmt.Println(response)
      ```

      ```java Java
      import com.anthropic.models.messages.ThinkingConfigAdaptive;
      // ...
          AnthropicClient client = AnthropicOkHttpClient.fromEnv();

          MessageCreateParams params = MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(16000L)
              .thinking(ThinkingConfigAdaptive.builder().build())
              .addTool(Tool.builder()
                  .name("get_weather")
                  .description("Get current weather for a location")
                  .inputSchema(Tool.InputSchema.builder()
                      .properties(JsonValue.from(Map.of(
                          "location", Map.of("type", "string", "description", "City name")
                      )))
                      .required(List.of("location"))
                      .build())
                  .build())
              .addUserMessage("What's the weather in Paris?")
              .build();

          Message response = client.messages().create(params);
          IO.println(response);
      ```

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

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

      $message = $client->messages->create(
          maxTokens: 16000,
          messages: [
              ['role' => 'user', 'content' => "What's the weather in Paris?"]
          ],
          model: 'claude-opus-5-5',
          thinking: ['type' => 'adaptive'],
          tools: [$weatherTool],
      );
      echo $message;
      ```

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

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

      message = client.messages.create(
        model: "claude-opus-5-5",
        max_tokens: 16000,
        thinking: {
          type: "adaptive"
        },
        tools: [weather_tool],
        messages: [
          { role: "user", content: "What's the weather in Paris?" }
        ]
      )
      puts message
      ```
    </CodeGroup>
  </Step>

  <Step title="Cattura l'array content da restituire">
    Dovresti vedere i blocchi `thinking` e `tool_use` nel contenuto della risposta in un'esecuzione in cui Claude ha scelto di ragionare (con richieste più semplici, la modalità adattiva può saltare il blocco di ragionamento). Una nota che Claude scrive prima della chiamata allo strumento viene restituita come blocco `text` oppure, sui modelli che scrivono [aggiornamenti di avanzamento](https://platform.claude.com/docs/it/build-with-claude/thinking#progress-updates), come un ulteriore blocco `thinking`. Mantieni intatto questo array content: il passaggio successivo lo rimanda indietro alla lettera.

    <Note>
      Per vedere il testo del ragionamento come in questo output, aggiungi `display: "summarized"` alla richiesta. Sui modelli in cui la visualizzazione è omessa per impostazione predefinita, incluso Claude Opus 5.5, il campo `thinking` viene altrimenti restituito come stringa vuota con solo il campo `signature` popolato. In entrambi i casi, restituisci l'array content invariato; consulta [Controllare la visualizzazione del ragionamento](https://platform.claude.com/docs/it/build-with-claude/thinking#controlling-thinking-display).
    </Note>

    ```json Output
    {
      "content": [
        {
          "type": "thinking",
          "thinking": "The user wants to know the current weather in Paris. I have access to a function `get_weather`...",
          "signature": "BDaL4VrbR2Oj0hO4XpJxT28J5T...."
        },
        {
          "type": "tool_use",
          "id": "toolu_01CswdEQBMshySk6Y9DFKrfq",
          "name": "get_weather",
          "input": {
            "location": "Paris"
          }
        }
      ]
    }
    ```
  </Step>

  <Step title="Restituisci il risultato dello strumento, ripetendo il turno dell'assistente alla lettera">
    Esegui lo strumento dal tuo lato, quindi invia una seconda richiesta che aggiunge due messaggi alla conversazione. Il primo è il contenuto dell'assistente restituito esattamente come ricevuto, in modo che il blocco di ragionamento rimanga invariato accanto al blocco `tool_use`. Il secondo è un messaggio utente che contiene il `tool_result`.

    Ogni esempio è uno script autonomo: ripete la prima richiesta, quindi invia immediatamente il seguito usando la risposta appena ricevuta.

    <CodeGroup exclude="shell:cURL">
      <CodeGroupItem language="cURL">
        Questo flusso di lavoro richiede più logica di un singolo comando shell. Usa il Claude SDK per eseguirlo.
      </CodeGroupItem>

      ```bash CLI
      # Primo turno: scrivi l'array di contenuto dell'assistente (blocchi thinking e tool_use,
      # con firme intatte) in un file. Far passare il testo generato dal modello
      # da un file lo tiene lontano da posizioni soggette a espansione della shell.
      ant messages create --transform content --format jsonl \
        > assistant_content.json <<'YAML'
      model: claude-opus-5-5
      max_tokens: 16000
      thinking:
        type: adaptive
      tools:
        - name: get_weather
          description: Get current weather for a location
          input_schema:
            type: object
            properties:
              location:
                type: string
                description: City name
            required: [location]
      messages:
        - role: user
          content: What's the weather in Paris?
      YAML

      # Secondo turno: jq riempie i due segnaposto null dal file salvato,
      # così i blocchi tornano invariati come messaggio dell'assistente. Il blocco
      # thinking DEVE accompagnare il blocco tool_use. Il delimitatore tra virgolette
      # impedisce alla shell di espandere qualsiasi cosa nel corpo.
      jq --slurpfile blocks assistant_content.json '
        .messages[1].content = $blocks[0] |
        .messages[2].content[0].tool_use_id =
          ($blocks[0][] | select(.type == "tool_use") | .id)
      ' <<'JSON' | ant messages create
      {
        "model": "claude-opus-5-5",
        "max_tokens": 16000,
        "thinking": {"type": "adaptive"},
        "tools": [{
          "name": "get_weather",
          "description": "Get current weather for a location",
          "input_schema": {
            "type": "object",
            "properties": {
              "location": {"type": "string", "description": "City name"}
            },
            "required": ["location"]
          }
        }],
        "messages": [
          {"role": "user", "content": "What's the weather in Paris?"},
          {"role": "assistant", "content": null},
          {"role": "user", "content": [{
            "type": "tool_result",
            "tool_use_id": null,
            "content": "Current temperature: 88°F"
          }]}
        ]
      }
      JSON
      ```

      ```python Python

      client = anthropic.Anthropic()
      weather_tool = {
          "name": "get_weather",
          "description": "Get current weather for a location",
          "input_schema": {
              "type": "object",
              "properties": {"location": {"type": "string", "description": "City name"}},
              "required": ["location"],
          },
      }
      response = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=16000,
          thinking={"type": "adaptive"},
          tools=[weather_tool],
          messages=[{"role": "user", "content": "What's the weather in Paris?"}],
      )
      # Estrai il blocco tool_use per ottenere il suo ID per il tool_result
      tool_use_block = next(block for block in response.content if block.type == "tool_use")

      # Chiama la tua vera API meteo, qui andrebbe la tua chiamata API effettiva
      # Facciamo finta che questo sia ciò che riceviamo
      weather_data = {"temperature": 88}

      # Seconda richiesta - Includi il turno dell'assistente e il tool_result
      continuation = client.messages.create(
          model="claude-opus-5-5",
          max_tokens=16000,
          thinking={"type": "adaptive"},
          tools=[weather_tool],
          messages=[
              {"role": "user", "content": "What's the weather in Paris?"},
              # Ripeti il contenuto dell'assistente esattamente come ricevuto. Quando un blocco
              # thinking è presente, deve accompagnare il blocco tool_use.
              {"role": "assistant", "content": response.content},
              {
                  "role": "user",
                  "content": [
                      {
                          "type": "tool_result",
                          "tool_use_id": tool_use_block.id,
                          "content": f"Current temperature: {weather_data['temperature']}°F",
                      }
                  ],
              },
          ],
      )
      print(continuation)
      ```

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

      const weatherTool: Anthropic.Tool = {
        name: "get_weather",
        description: "Get current weather for a location",
        input_schema: {
          type: "object",
          properties: {
            location: { type: "string", description: "City name" }
          },
          required: ["location"]
        }
      };

      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 16000,
        thinking: {
          type: "adaptive"
        },
        tools: [weatherTool],
        messages: [{ role: "user", content: "What's the weather in Paris?" }]
      });

      // Estrai il blocco tool_use per ottenere il suo ID per il tool_result
      const toolUseBlock = response.content.find(
        (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"
      );

      // Chiama la tua API meteo reale, qui andrebbe la tua chiamata API effettiva
      // Facciamo finta che questo sia ciò che riceviamo
      const weatherData = { temperature: 88 };

      if (toolUseBlock) {
        // Seconda richiesta - Includi il turno dell'assistente e il tool_result
        const continuation = await client.messages.create({
          model: "claude-opus-5-5",
          max_tokens: 16000,
          thinking: {
            type: "adaptive"
          },
          tools: [weatherTool],
          messages: [
            { role: "user", content: "What's the weather in Paris?" },
            // Ripeti il contenuto dell'assistente esattamente come ricevuto. Quando un blocco
            // thinking è presente, deve accompagnare il blocco tool_use.
            { role: "assistant", content: response.content },
            {
              role: "user",
              content: [
                {
                  type: "tool_result" as const,
                  tool_use_id: toolUseBlock.id,
                  content: `Current temperature: ${weatherData.temperature}°F`
                }
              ]
            }
          ]
        });
        console.log(continuation);
      }
      ```

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

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

      var parameters = new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 16000,
          Thinking = new ThinkingConfigAdaptive(),
          Tools = [weatherTool],
          Messages = [
              new() { Role = Role.User, Content = "What's the weather in Paris?" }
          ]
      };

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

      // Estrai il blocco tool_use per ottenere il suo ID per il tool_result
      ToolUseBlock? toolUseBlock = null;
      foreach (var block in response.Content)
      {
          if (block.TryPickToolUse(out var toolUse))
          {
              toolUseBlock = toolUse;
              break;
          }
      }

      var weatherData = new { temperature = 88 };

      // Costruisci la continuazione con il risultato dello strumento
      var continuationParams = new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 16000,
          Thinking = new ThinkingConfigAdaptive(),
          Tools = [weatherTool],
          Messages = [
              new() { Role = Role.User, Content = "What's the weather in Paris?" },
              // response.Content include i blocchi di ragionamento; è obbligatorio ripassarli indietro
              new() { Role = Role.Assistant, Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList() },
              new() { Role = Role.User, Content = new MessageParamContent(new List<ContentBlockParam>
              {
                  new ContentBlockParam(new ToolResultBlockParam()
                  {
                      ToolUseID = toolUseBlock?.ID ?? "",
                      Content = $"Current temperature: {weatherData.temperature}°F"
                  })
              })}
          ]
      };

      var continuation = await client.Messages.Create(continuationParams);
      Console.WriteLine(continuation);
      ```

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

      weatherTool := anthropic.ToolUnionParam{
      	OfTool: &anthropic.ToolParam{
      		Name:        "get_weather",
      		Description: anthropic.String("Get current weather for a location"),
      		InputSchema: anthropic.ToolInputSchemaParam{
      			Properties: map[string]any{
      				"location": map[string]any{
      					"type":        "string",
      					"description": "City name",
      				},
      			},
      			Required: []string{"location"},
      		},
      	},
      }

      response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
      	Model:     anthropic.ModelClaudeOpus5_5,
      	MaxTokens: 16000,
      	Thinking: anthropic.ThinkingConfigParamUnion{
      		OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
      	},
      	Tools: []anthropic.ToolUnionParam{weatherTool},
      	Messages: []anthropic.MessageParam{
      		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather in Paris?")),
      	},
      })
      if err != nil {
      	log.Fatal(err)
      }

      var toolUseBlock anthropic.ToolUseBlock
      for _, block := range response.Content {
      	if v, ok := block.AsAny().(anthropic.ToolUseBlock); ok {
      		toolUseBlock = v
      		break
      	}
      }

      weatherData := map[string]int{"temperature": 88}

      continuation, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
      	Model:     anthropic.ModelClaudeOpus5_5,
      	MaxTokens: 16000,
      	Thinking: anthropic.ThinkingConfigParamUnion{
      		OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
      	},
      	Tools: []anthropic.ToolUnionParam{weatherTool},
      	Messages: []anthropic.MessageParam{
      		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather in Paris?")),
      		response.ToParam(),
      		anthropic.NewUserMessage(
      			anthropic.NewToolResultBlock(toolUseBlock.ID, fmt.Sprintf("Current temperature: %d°F", weatherData["temperature"]), false),
      		),
      	},
      })
      if err != nil {
      	log.Fatal(err)
      }

      fmt.Println(continuation)
      ```

      ```java Java
      import com.anthropic.models.messages.ThinkingConfigAdaptive;
      // ...

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

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

          MessageCreateParams initialParams = MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(16000L)
              .thinking(ThinkingConfigAdaptive.builder().build())
              .addTool(weatherTool)
              .addUserMessage("What's the weather in Paris?")
              .build();

          Message response = client.messages().create(initialParams);

          ToolUseBlock toolUseBlock = null;
          for (var block : response.content()) {
              if (block.toolUse().isPresent()) {
                  toolUseBlock = block.toolUse().get();
                  break;
              }
          }

          int temperature = 88;

          // Seconda richiesta: ripeti il turno dell'assistente così come ricevuto, poi il tool result
          MessageCreateParams continuationParams = MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(16000L)
              .thinking(ThinkingConfigAdaptive.builder().build())
              .addTool(weatherTool)
              .addUserMessage("What's the weather in Paris?")
              .addMessage(response)
              .addUserMessageOfBlockParams(List.of(
                  ContentBlockParam.ofToolResult(
                      ToolResultBlockParam.builder()
                          .toolUseId(toolUseBlock.id())
                          .content("Current temperature: " + temperature + "°F")
                          .build()
                  )
              ))
              .build();

          Message continuation = client.messages().create(continuationParams);
          IO.println(continuation);
      }
      ```

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

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

      $response = $client->messages->create(
          maxTokens: 16000,
          messages: [
              ['role' => 'user', 'content' => "What's the weather in Paris?"]
          ],
          model: 'claude-opus-5-5',
          thinking: ['type' => 'adaptive'],
          tools: [$weatherTool],
      );

      $toolUseBlock = null;
      foreach ($response->content as $block) {
          if ($block->type === 'tool_use') {
              $toolUseBlock = $block;
              break;
          }
      }

      $weatherData = ['temperature' => 88];

      $continuation = $client->messages->create(
          maxTokens: 16000,
          messages: [
              ['role' => 'user', 'content' => "What's the weather in Paris?"],
              ['role' => 'assistant', 'content' => $response->content],
              ['role' => 'user', 'content' => [
                  [
                      'type' => 'tool_result',
                      'tool_use_id' => $toolUseBlock->id,
                      'content' => "Current temperature: {$weatherData['temperature']}°F"
                  ]
              ]]
          ],
          model: 'claude-opus-5-5',
          thinking: ['type' => 'adaptive'],
          tools: [$weatherTool],
      );

      echo $continuation;
      ```

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

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

      response = client.messages.create(
        model: "claude-opus-5-5",
        max_tokens: 16000,
        thinking: {
          type: "adaptive"
        },
        tools: [weather_tool],
        messages: [
          { role: "user", content: "What's the weather in Paris?" }
        ]
      )

      tool_use_block = response.content.find { |block| block.type == :tool_use }

      raise "No tool_use block found" unless tool_use_block

      weather_data = { temperature: 88 }

      continuation = client.messages.create(
        model: "claude-opus-5-5",
        max_tokens: 16000,
        thinking: {
          type: "adaptive"
        },
        tools: [weather_tool],
        messages: [
          { role: "user", content: "What's the weather in Paris?" },
          { role: "assistant", content: response.content },
          { role: "user", content: [
            {
              type: "tool_result",
              tool_use_id: tool_use_block.id,
              content: "Current temperature: #{weather_data[:temperature]}°F"
            }
          ] }
        ]
      )

      puts continuation
      ```
    </CodeGroup>
  </Step>

  <Step title="Leggi la risposta finale">
    Dovresti vedere Claude completare il turno con del testo. Poiché il [ragionamento interlacciato](https://platform.claude.com/docs/it/build-with-claude/thinking#interleaved-thinking) è automatico in modalità adattiva, la continuazione può anche aprirsi con un nuovo blocco di ragionamento prima del testo finale:

    ```json Output
    {
      "content": [
        {
          "type": "text",
          "text": "Currently in Paris, the temperature is 88°F (31°C)"
        }
      ]
    }
    ```
  </Step>
</Steps>

## Come il ragionamento interlacciato modifica il flusso

Il "interleaved thinking" (ragionamento interlacciato) consente a Claude di pensare tra una chiamata a uno strumento e l'altra, ragionando su ciascun risultato prima di agire di conseguenza. Il concetto e la disponibilità per modello sono trattati in [Ragionamento interlacciato](https://platform.claude.com/docs/it/build-with-claude/thinking#interleaved-thinking) nella pagina Ragionamento; l'interleaving modifica dove compaiono i blocchi di ragionamento, non se le chiamate agli strumenti possano concatenarsi. Il confronto seguente mostra cosa cambia con il ragionamento interlacciato in un flusso di lavoro con due strumenti:

<AccordionGroup>
  <Accordion title="Uso degli strumenti senza ragionamento interlacciato">
    Senza ragionamento interlacciato, Claude pensa una sola volta all'inizio del turno dell'assistente. Le risposte successive dopo i risultati degli strumenti proseguono senza nuovi blocchi di ragionamento.

    ```text
    User: "What's the total revenue if we sold 150 units at $50 each,
           and how does this compare to our average monthly revenue?"

    Response 1: [thinking] "I need to calculate 150 * $50, then check the database..."
                [tool_use: calculator] { "expression": "150 * 50" }
      ↓ tool result: "7500"

    Response 2: [tool_use: database_query] { "query": "SELECT AVG(revenue)..." }
                ↑ no thinking block
      ↓ tool result: "5200"

    Response 3: [text] "The total revenue is $7,500, which is 44% above your
                average monthly revenue of $5,200."
                ↑ no thinking block
    ```
  </Accordion>

  <Accordion title="Uso degli strumenti con ragionamento interlacciato">
    Con il ragionamento interlacciato abilitato, Claude può pensare dopo aver ricevuto ciascun risultato di uno strumento, il che gli consente di ragionare sui risultati intermedi prima di proseguire.

    ```text
    User: "What's the total revenue if we sold 150 units at $50 each,
           and how does this compare to our average monthly revenue?"

    Response 1: [thinking] "I need to calculate 150 * $50 first..."
                [tool_use: calculator] { "expression": "150 * 50" }
      ↓ tool result: "7500"

    Response 2: [thinking] "Got $7,500. Now I should query the database to compare..."
                [tool_use: database_query] { "query": "SELECT AVG(revenue)..." }
                ↑ thinking after receiving calculator result
      ↓ tool result: "5200"

    Response 3: [thinking] "$7,500 vs $5,200 average - that's a 44% increase..."
                [text] "The total revenue is $7,500, which is 44% above your
                average monthly revenue of $5,200."
                ↑ thinking before final answer
    ```
  </Accordion>
</AccordionGroup>

## Prossimi passi

<CardGroup cols={3}>
  <Card title="Ragionamento" icon="brain" href="https://platform.claude.com/docs/it/build-with-claude/thinking">
    La panoramica: attiva il ragionamento, leggi l'output del ragionamento e consulta le regole complete per uso degli strumenti, cache e streaming.
  </Card>

  <Card title="Orientare il ragionamento" icon="compass" href="https://platform.claude.com/docs/it/build-with-claude/thinking-steering-and-cost">
    Orienta quanto spesso e quanto a fondo Claude pensa con i livelli di effort e le indicazioni basate sui prompt.
  </Card>

  <Card title="Ragionamento esteso" icon="clock" href="https://platform.claude.com/docs/it/build-with-claude/extended-thinking">
    Budget di ragionamento manuali sui modelli meno recenti: funzionamento di `budget_tokens` e migrazione al ragionamento adattivo.
  </Card>
</CardGroup>
