---
title: Размышления в рабочих процессах с инструментами и несколькими ходами
url: https://platform.claude.com/docs/ru/build-with-claude/thinking-tool-workflows
description: Пройдите полный двухходовой цикл использования инструментов, который корректно сохраняет блоки размышлений, и посмотрите, как чередующиеся размышления меняют поток.
---

<Note>
  Чтобы узнать, как «zero data retention» (нулевое хранение данных), или ZDR, применяется к этой функции, см. раздел [API и хранение данных](https://platform.claude.com/docs/ru/manage-claude/api-and-data-retention).
</Note>

На этой странице разбирается полный двухходовой цикл «tool use» (использование инструментов) с включёнными размышлениями: Claude думает, запрашивает вызов инструмента, получает результат и завершает свой ответ, при этом блоки размышлений корректно обрабатываются на каждом шаге. Полные правила находятся на странице [Размышления](https://platform.claude.com/docs/ru/build-with-claude/thinking), в разделах [Размышления с использованием инструментов](https://platform.claude.com/docs/ru/build-with-claude/thinking#thinking-with-tool-use) и [Сохранение блоков размышлений](https://platform.claude.com/docs/ru/build-with-claude/thinking#preserving-thinking-blocks); эта страница показывает применение этих правил в исполняемом коде.

## Правила, применяемые в этом разборе

Каждая ссылка ведёт к полной формулировке на странице «Размышления»:

* [Ограничьте выбор инструмента значениями `auto` или `none` в ручном режиме](https://platform.claude.com/docs/ru/build-with-claude/thinking#thinking-with-tool-use): варианты `tool_choice`, принудительно требующие использования инструментов, возвращают ошибку при ручных «extended thinking» (расширенных размышлениях) (`thinking: {type: "enabled"}`). Адаптивные размышления поддерживают принудительное использование инструментов, за исключением Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 и Claude Mythos 5.1, которые возвращают ошибку 400. Там, где принудительное использование инструментов допускается, размышления пропускаются: ответ начинается с вызова инструмента.
* [Сохраняйте одну конфигурацию размышлений на один ход ассистента](https://platform.claude.com/docs/ru/build-with-claude/thinking#thinking-with-tool-use): цикл использования инструментов — это один ход ассистента, поэтому меняйте конфигурацию только между ходами.
* [Передавайте блоки размышлений обратно полностью и без изменений](https://platform.claude.com/docs/ru/build-with-claude/thinking#preserving-thinking-blocks): когда вы возвращаете результат инструмента, блоки размышлений из сообщения ассистента должны вернуться вместе с ним.
* [Повторяйте сообщение ассистента точно в том виде, в каком оно получено](https://platform.claude.com/docs/ru/build-with-claude/thinking#preserving-thinking-blocks): пересборка сообщения или отфильтровывание блоков `redacted_thinking` вызывает ошибку 400.

В примерах используются адаптивные размышления; на моделях, поддерживающих только расширенные размышления, подставьте `thinking: {type: "enabled", budget_tokens: N}`. Правила цикла идентичны.

## Разбор двухходового цикла использования инструментов

В примере определяется инструмент `get_weather`, Claude получает возможность подумать и запросить вызов инструмента, а затем возвращается результат инструмента вместе с ходом ассистента, повторённым точно в том виде, в каком он был получен, включая блок размышлений.

<Steps>
  <Step title="Выполните первый запрос с доступным инструментом">
    Отправьте запрос с включёнными адаптивными размышлениями и определённым инструментом. За исключением параметра `thinking`, это стандартный запрос на [использование инструментов](https://platform.claude.com/docs/ru/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"],
          },
      }

      # Первый запрос — Claude отвечает размышлениями и запросом инструмента
      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"]
        }
      };

      // Первый запрос — Claude отвечает размышлениями и запросом инструмента
      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="Сохраните массив content для обратной отправки">
    В запуске, где Claude решил поразмышлять, вы должны увидеть в содержимом ответа блоки `thinking` и `tool_use` (на более простых запросах адаптивный режим может пропустить блок размышлений). Заметка, которую Claude пишет перед вызовом инструмента, возвращается в виде блока `text` или, на моделях, которые пишут [обновления о ходе работы](https://platform.claude.com/docs/ru/build-with-claude/thinking#progress-updates), в виде ещё одного блока `thinking`. Сохраните этот массив content нетронутым: на следующем шаге он отправляется обратно дословно.

    <Note>
      Чтобы увидеть текст размышлений, как в этом выводе, добавьте в запрос `display: "summarized"`. На моделях, где по умолчанию отображение опущено, включая Claude Opus 5.5, поле `thinking` в противном случае возвращается пустой строкой, и заполнено только поле `signature`. В любом случае возвращайте массив content без изменений; см. [Управление отображением размышлений](https://platform.claude.com/docs/ru/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="Верните результат инструмента, дословно повторив ход ассистента">
    Выполните инструмент на своей стороне, затем отправьте второй запрос, который добавляет к разговору два сообщения. Первое — это содержимое ассистента, повторённое точно в том виде, в каком оно получено, так что блок размышлений остаётся неизменным рядом с блоком `tool_use`. Второе — пользовательское сообщение, содержащее `tool_result`.

    Каждый пример — это самодостаточный скрипт: он повторяет первый запрос, а затем сразу отправляет последующий, используя только что полученный ответ.

    <CodeGroup exclude="shell:cURL">
      <CodeGroupItem language="cURL">
        Этот рабочий процесс требует больше логики, чем одна команда оболочки. Используйте Claude SDK для его запуска.
      </CodeGroupItem>

      ```bash CLI
      # Первый ход: запишите массив содержимого ассистента (блоки thinking и tool_use
      # с неизменёнными подписями) в файл. Передача сгенерированного моделью текста
      # через файл не даёт ему позже оказаться в позиции раскрытия оболочкой.
      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

      # Второй ход: jq заполняет два заполнителя null из сохранённого файла,
      # поэтому блоки возвращаются дословно как сообщение ассистента. Блок thinking
      # ОБЯЗАТЕЛЬНО должен сопровождать блок tool_use. Разделитель в кавычках не даёт
      # оболочке раскрывать что-либо в теле.
      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?"}],
      )
      # Извлекаем блок tool_use, чтобы получить его ID для tool_result
      tool_use_block = next(block for block in response.content if block.type == "tool_use")

      # Вызовите ваш реальный погодный API — здесь должен быть ваш фактический вызов API
      # Представим, что мы получили вот такой ответ
      weather_data = {"temperature": 88}

      # Второй запрос — включаем ход ассистента и 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?"},
              # Передаём содержимое ассистента точно в том виде, в каком получили. Если присутствует
              # блок thinking, он должен сопровождать блок 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?" }]
      });

      // Извлекаем блок tool_use, чтобы получить его ID для tool_result
      const toolUseBlock = response.content.find(
        (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"
      );

      // Вызовите ваш реальный погодный API — здесь должен быть ваш фактический вызов API
      // Представим, что мы получили такой ответ
      const weatherData = { temperature: 88 };

      if (toolUseBlock) {
        // Второй запрос — включаем ход ассистента и 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?" },
            // Передаём содержимое ассистента точно в полученном виде. Если присутствует
            // блок thinking, он должен сопровождать блок 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);

      // Извлекаем блок tool_use, чтобы получить его ID для результата инструмента
      ToolUseBlock? toolUseBlock = null;
      foreach (var block in response.Content)
      {
          if (block.TryPickToolUse(out var toolUse))
          {
              toolUseBlock = toolUse;
              break;
          }
      }

      var weatherData = new { temperature = 88 };

      // Формируем продолжение с результатом инструмента
      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 содержит блоки размышлений; их обязательно нужно передать обратно
              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;

          // Второй запрос: повторяем ход ассистента как получен, затем результат инструмента
          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="Прочитайте финальный ответ">
    Вы должны увидеть, как Claude завершает ход текстом. Поскольку «interleaved thinking» ([чередующиеся размышления](https://platform.claude.com/docs/ru/build-with-claude/thinking#interleaved-thinking)) в адаптивном режиме включаются автоматически, продолжение также может начинаться с нового блока размышлений перед финальным текстом:

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

## Как чередующиеся размышления меняют поток

Чередующиеся размышления позволяют Claude думать между вызовами инструментов, рассуждая о каждом результате инструмента, прежде чем действовать на его основе. Концепция и доступность по моделям описаны в разделе [Чередующиеся размышления](https://platform.claude.com/docs/ru/build-with-claude/thinking#interleaved-thinking) на странице «Размышления»; чередование меняет то, где появляются блоки размышлений, а не то, могут ли вызовы инструментов выстраиваться в цепочку. Следующее сравнение показывает, что меняют чередующиеся размышления в рабочем процессе с двумя инструментами:

<AccordionGroup>
  <Accordion title="Использование инструментов без чередующихся размышлений">
    Без чередующихся размышлений Claude думает один раз в начале хода ассистента. Последующие ответы после результатов инструментов продолжаются без новых блоков размышлений.

    ```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="Использование инструментов с чередующимися размышлениями">
    При включённых чередующихся размышлениях Claude может думать после получения каждого результата инструмента, что позволяет ему рассуждать о промежуточных результатах перед продолжением.

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

## Следующие шаги

<CardGroup cols={3}>
  <Card title="Размышления" icon="brain" href="https://platform.claude.com/docs/ru/build-with-claude/thinking">
    Обзор: включите размышления, прочитайте вывод размышлений и ознакомьтесь с полными правилами для использования инструментов, кэширования и потоковой передачи.
  </Card>

  <Card title="Управление размышлениями" icon="compass" href="https://platform.claude.com/docs/ru/build-with-claude/thinking-steering-and-cost">
    Управляйте тем, как часто и насколько глубоко думает Claude, с помощью уровней усилий и указаний в подсказках.
  </Card>

  <Card title="Расширенные размышления" icon="clock" href="https://platform.claude.com/docs/ru/build-with-claude/extended-thinking">
    Ручные бюджеты размышлений на старых моделях: механика `budget_tokens` и миграция на адаптивные размышления.
  </Card>
</CardGroup>
