---
title: Pensamiento en flujos de trabajo con herramientas y de múltiples turnos
url: https://platform.claude.com/docs/es/build-with-claude/thinking-tool-workflows
description: Recorre un ciclo completo de uso de herramientas de dos turnos que preserva correctamente los bloques de pensamiento, y observa cómo el pensamiento intercalado cambia el flujo.
---

<Note>
  Para saber cómo se aplica la "zero data retention" (retención cero de datos), o ZDR, a esta función, consulta [API y retención de datos](https://platform.claude.com/docs/es/manage-claude/api-and-data-retention).
</Note>

Esta página recorre un ciclo completo de "tool use" (uso de herramientas) de dos turnos con el pensamiento habilitado: Claude piensa, solicita una llamada a una herramienta, recibe el resultado y termina su respuesta, con los bloques de pensamiento manejados correctamente en cada paso. Las reglas completas se encuentran en la página de [Pensamiento](https://platform.claude.com/docs/es/build-with-claude/thinking), en [Pensamiento con uso de herramientas](https://platform.claude.com/docs/es/build-with-claude/thinking#thinking-with-tool-use) y [Preservación de bloques de pensamiento](https://platform.claude.com/docs/es/build-with-claude/thinking#preserving-thinking-blocks); esta página muestra esas reglas aplicadas en código ejecutable.

## Las reglas que aplica este recorrido

Cada enlace lleva al enunciado completo en la página de Pensamiento:

* [Limita la elección de herramientas a `auto` o `none` en modo manual](https://platform.claude.com/docs/es/build-with-claude/thinking#thinking-with-tool-use): las opciones de `tool_choice` que fuerzan el uso de herramientas devuelven un error con el "extended thinking" (pensamiento extendido) manual (`thinking: {type: "enabled"}`). El pensamiento adaptativo admite el uso forzado de herramientas, excepto en Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 y Claude Mythos 5.1, que devuelven un error 400. Donde se acepta el uso forzado de herramientas, este omite el pensamiento: la respuesta comienza con la llamada a la herramienta.
* [Mantén una sola configuración de pensamiento por turno del asistente](https://platform.claude.com/docs/es/build-with-claude/thinking#thinking-with-tool-use): un bucle de uso de herramientas es un solo turno del asistente, así que cambia la configuración solo entre turnos.
* [Devuelve los bloques de pensamiento completos y sin modificar](https://platform.claude.com/docs/es/build-with-claude/thinking#preserving-thinking-blocks): cuando devuelves un resultado de herramienta, los bloques de pensamiento del mensaje del asistente deben regresar junto con él.
* [Repite el mensaje del asistente exactamente como lo recibiste](https://platform.claude.com/docs/es/build-with-claude/thinking#preserving-thinking-blocks): reconstruir el mensaje o filtrar los bloques `redacted_thinking` provoca un error 400.

Los ejemplos usan pensamiento adaptativo; en modelos que solo admiten pensamiento extendido, sustituye `thinking: {type: "enabled", budget_tokens: N}`. Las reglas del ciclo son idénticas.

## Recorre un ciclo de uso de herramientas de dos turnos

El ejemplo define una herramienta `get_weather`, deja que Claude piense y solicite una llamada a la herramienta, y luego devuelve el resultado de la herramienta junto con el turno del asistente repetido exactamente como se recibió, incluido el bloque de pensamiento.

<Steps>
  <Step title="Haz la primera solicitud con una herramienta disponible">
    Envía una solicitud con el pensamiento adaptativo habilitado y la herramienta definida. Aparte del parámetro `thinking`, esta es una solicitud estándar de [uso de herramientas](https://platform.claude.com/docs/es/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"],
          },
      }

      # Primera solicitud: Claude responde con pensamiento y solicitud de herramienta
      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"]
        }
      };

      // Primera solicitud: Claude responde con pensamiento y una solicitud de herramienta
      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="Captura el arreglo de contenido para devolverlo">
    Deberías ver bloques `thinking` y `tool_use` en el contenido de la respuesta en una ejecución en la que Claude eligió pensar (en solicitudes más simples, el modo adaptativo puede omitir el bloque de pensamiento). Una nota que Claude escribe antes de la llamada a la herramienta regresa como un bloque `text` o, en modelos que escriben [actualizaciones de progreso](https://platform.claude.com/docs/es/build-with-claude/thinking#progress-updates), como otro bloque `thinking`. Mantén este arreglo de contenido intacto: el siguiente paso lo reenvía textualmente.

    <Note>
      Para ver texto de pensamiento como esta salida, agrega `display: "summarized"` a la solicitud. En modelos donde la visualización se omite de forma predeterminada, incluido Claude Opus 5.5, el campo `thinking` regresa de lo contrario como una cadena vacía con solo `signature` completado. En cualquier caso, reenvía el arreglo de contenido sin cambios; consulta [Controlar la visualización del pensamiento](https://platform.claude.com/docs/es/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="Devuelve el resultado de la herramienta, repitiendo el turno del asistente textualmente">
    Ejecuta la herramienta de tu lado y luego envía una segunda solicitud que agrega dos mensajes a la conversación. El primero es el contenido del asistente devuelto exactamente como se recibió, de modo que el bloque de pensamiento permanece sin cambios junto al bloque `tool_use`. El segundo es un mensaje de usuario que lleva el `tool_result`.

    Cada ejemplo es un script autocontenido: repite la primera solicitud y luego envía inmediatamente la continuación usando la respuesta que acaba de recibir.

    <CodeGroup exclude="shell:cURL">
      <CodeGroupItem language="cURL">
        Este flujo de trabajo necesita más lógica que un solo comando de shell. Usa el SDK de Claude para ejecutarlo.
      </CodeGroupItem>

      ```bash CLI
      # Primer turno: escribe el array de contenido del asistente (bloques thinking y tool_use,
      # con las firmas intactas) en un archivo. Pasar el texto generado por el modelo
      # por un archivo evita que luego quede en posición de expansión del 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

      # Segundo turno: jq rellena los dos marcadores null con el archivo capturado,
      # así los bloques vuelven textualmente como mensaje del asistente. El bloque
      # thinking DEBE acompañar al bloque tool_use. El delimitador entre comillas evita que el
      # shell expanda cualquier cosa del cuerpo.
      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?"}],
      )
      # Extrae el bloque de uso de herramientas para obtener su ID para el resultado de la herramienta
      tool_use_block = next(block for block in response.content if block.type == "tool_use")

      # Llama a tu API de clima real; aquí iría tu llamada real a la API
      # Supongamos que esto es lo que recibimos
      weather_data = {"temperature": 88}

      # Segunda solicitud: incluye el turno del asistente y el resultado de la herramienta
      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?"},
              # Repite el contenido del asistente exactamente como se recibió. Cuando hay un bloque
              # de pensamiento presente, debe acompañar al bloque 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?" }]
      });

      // Extrae el bloque tool_use para obtener su ID para el tool_result
      const toolUseBlock = response.content.find(
        (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"
      );

      // Llama a tu API de clima real; aquí iría tu llamada real a la API
      // Supongamos que esto es lo que recibimos
      const weatherData = { temperature: 88 };

      if (toolUseBlock) {
        // Segunda solicitud: incluye el turno del asistente y el 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?" },
            // Repite el contenido del asistente exactamente como se recibió. Cuando hay un bloque
            // de pensamiento presente, debe acompañar al bloque 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);

      // Extrae el bloque tool_use para obtener su ID para el resultado de la herramienta
      ToolUseBlock? toolUseBlock = null;
      foreach (var block in response.Content)
      {
          if (block.TryPickToolUse(out var toolUse))
          {
              toolUseBlock = toolUse;
              break;
          }
      }

      var weatherData = new { temperature = 88 };

      // Construye la continuación con el resultado de la herramienta
      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 incluye los bloques de pensamiento; es obligatorio devolverlos
              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;

          // Segunda solicitud: repite el turno del asistente tal como se recibió, luego el resultado de la herramienta
          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="Lee la respuesta final">
    Deberías ver a Claude completar el turno con texto. Dado que el [pensamiento intercalado](https://platform.claude.com/docs/es/build-with-claude/thinking#interleaved-thinking) es automático en el modo adaptativo, la continuación también puede comenzar con un nuevo bloque de pensamiento antes del texto final:

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

## Cómo el pensamiento intercalado cambia el flujo

El "interleaved thinking" (pensamiento intercalado) permite que Claude piense entre llamadas a herramientas, razonando sobre cada resultado de herramienta antes de actuar en consecuencia. El concepto y la disponibilidad por modelo se cubren en [Pensamiento intercalado](https://platform.claude.com/docs/es/build-with-claude/thinking#interleaved-thinking) en la página de Pensamiento; el intercalado cambia dónde aparecen los bloques de pensamiento, no si las llamadas a herramientas pueden encadenarse. La siguiente comparación muestra qué cambia el pensamiento intercalado en un flujo de trabajo de dos herramientas:

<AccordionGroup>
  <Accordion title="Uso de herramientas sin pensamiento intercalado">
    Sin pensamiento intercalado, Claude piensa una vez al inicio del turno del asistente. Las respuestas posteriores tras los resultados de herramientas continúan sin nuevos bloques de pensamiento.

    ```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 de herramientas con pensamiento intercalado">
    Con el pensamiento intercalado habilitado, Claude puede pensar después de recibir cada resultado de herramienta, lo que le permite razonar sobre resultados intermedios antes de continuar.

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

## Próximos pasos

<CardGroup cols={3}>
  <Card title="Pensamiento" icon="brain" href="https://platform.claude.com/docs/es/build-with-claude/thinking">
    La descripción general: activa el pensamiento, lee la salida de pensamiento y revisa las reglas completas para el uso de herramientas, el almacenamiento en caché y el streaming.
  </Card>

  <Card title="Dirigir el pensamiento" icon="compass" href="https://platform.claude.com/docs/es/build-with-claude/thinking-steering-and-cost">
    Dirige con qué frecuencia y profundidad piensa Claude mediante niveles de esfuerzo y orientación basada en prompts.
  </Card>

  <Card title="Pensamiento extendido" icon="clock" href="https://platform.claude.com/docs/es/build-with-claude/extended-thinking">
    Presupuestos de pensamiento manuales en modelos anteriores: mecánica de `budget_tokens` y migración al modo adaptativo.
  </Card>
</CardGroup>
