Модели Gemini используют "мыслительный процесс", который значительно улучшает их способность рассуждать и планировать многоэтапные действия. Это делает их очень эффективными для сложных задач, таких как программирование, высшая математика и анализ данных.
Когда вы используете думающую модель, Gemini рассуждает, прежде чем ответить. В Interactions API это обоснование представлено в виде thought шагов, которые появляются в хронологическом порядке рядом с вызовами функций, вводом данных пользователем или результатами работы модели в массиве steps.
Каждый шаг содержит два поля:
| Поле | Обязательно? | Описание |
|---|---|---|
signature |
✅ Да | Зашифрованное представление внутреннего состояния модели. Всегда присутствует, даже если модель выполняет минимальное рассуждение. |
summary |
❌ Нет | Массив контента (текста и/или изображений), в котором излагается обоснование. Может быть пустым в зависимости от конфигурации thinking_summaries, того, насколько хорошо модель выполнила рассуждение, или типа контента (например, у скрытых изображений может не быть текстовых описаний). |
Взаимодействие с функцией "Думать"
Начать взаимодействие с думающей моделью можно так же, как и с любой другой. Укажите одну из моделей с поддержкой рассуждений в поле model:
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Explain the concept of Occam's Razor and provide a simple, everyday example."
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3.8-flash",
input: "Explain the concept of Occam's Razor and provide a simple, everyday example."
});
console.log(interaction.output_text);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(
InteractionsInput.of(
"Explain the concept of Occam's Razor and provide a simple, everyday example."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("Explain the concept of Occam's Razor and provide a simple, everyday example."),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "Explain the concept of Occam'\''s Razor and provide a simple example."
}'
Краткие пересказы рассуждений
Краткие изложения мыслей позволяют понять внутренние рассуждения модели.
По умолчанию возвращается только конечный результат. Вы можете включить краткий пересказ мыслей
с помощью thinking_summaries:
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="What is the sum of the first 50 prime numbers?",
generation_config={
"thinking_summaries": "auto"
}
)
for step in interaction.steps:
if step.type == "thought":
print("Thought summary:")
if step.summary:
for content_block in step.summary:
if content_block.type == "text":
print(content_block.text)
print()
elif step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print("Answer:")
print(content_block.text)
print()
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3.8-flash",
input: "What is the sum of the first 50 prime numbers?",
generation_config: {
thinking_summaries: "auto"
}
});
for (const step of interaction.steps) {
if (step.type === "thought") {
console.log("Thought summary:");
if (step.summary) {
for (const contentBlock of step.summary) {
if (contentBlock.type === "text") console.log(contentBlock.text);
}
}
} else if (step.type === "model_output") {
for (const contentBlock of step.content) {
if (contentBlock.type === "text") {
console.log("Answer:");
console.log(contentBlock.text);
}
}
}
}
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GenerationConfig;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.ThinkingSummaries;
import com.google.genai.gaos.models.interactions.ThoughtStep;
import com.google.genai.gaos.models.interactions.ThoughtSummaryContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Collections;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("What is the sum of the first 50 prime numbers?"))
.generationConfig(
GenerationConfig.builder().thinkingSummaries(ThinkingSummaries.AUTO).build())
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
for (Step step : interaction.steps().orElse(Collections.emptyList())) {
if (step instanceof ThoughtStep thoughtStep) {
System.out.println("Thought summary:");
for (ThoughtSummaryContent contentBlock : thoughtStep.summary().orElse(Collections.emptyList())) {
if (contentBlock instanceof TextContent textContent) {
System.out.println(textContent.text().orElse(""));
}
}
System.out.println();
} else if (step instanceof ModelOutputStep outputStep) {
for (Content contentBlock : outputStep.content().orElse(Collections.emptyList())) {
if (contentBlock instanceof TextContent textContent) {
System.out.println("Answer:");
System.out.println(textContent.text().orElse(""));
System.out.println();
}
}
}
}
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("Provide a list of 3 famous physicists and their key contributions"),
GenerationConfig: &interactions.GenerationConfig{
ThinkingLevel: interactions.ThinkingLevelLow.ToPointer(),
},
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "What is the sum of the first 50 prime numbers?",
"generation_config": {
"thinking_summaries": "auto"
}
}'
Блок размышлений может содержать только подпись без краткого пересказа в следующих случаях:
- Простые запросы, в которых модель не смогла достаточно обосновать ответ, чтобы создать краткий пересказ.
thinking_summaries: "none", где сводки явно отключены;- Для некоторых типов контента, например изображений, текстовые сводки могут быть недоступны.
Ваш код должен всегда обрабатывать блоки рассуждений, в которых summary отсутствует или является пустым.
Трансляция с рассуждениями
Используйте потоковую передачу, чтобы получать промежуточные сводки во время генерации. Блоки мыслей передаются с помощью Server-Sent Events (SSE) с двумя типами дельты:
| Тип дельты | Содержит | Когда отправляются данные |
|---|---|---|
thought_summary |
Текстовое или графическое резюме контента | Одно или несколько изменений с дополнительной сводкой |
thought_signature |
Криптографическая подпись | последнее изменение до step.stop |
Python
from google import genai
client = genai.Client()
prompt = """
Alice, Bob, and Carol each live in a different house on the same street: red, green, and blue.
Alice does not live in the red house.
Bob does not live in the green house.
Carol does not live in the red or green house.
Which house does each person live in?
"""
thoughts = ""
answer = ""
stream = client.interactions.create(
model="gemini-3.8-flash",
input=prompt,
generation_config={
"thinking_summaries": "auto"
},
stream=True
)
for event in stream:
if event.event_type == "step.delta":
if event.delta.type == "thought_summary":
if not thoughts:
print("Thinking...")
summary_text = event.delta.content.text
print(f"[Thought] {summary_text}", end="")
thoughts += summary_text
elif event.delta.type == "text" and event.delta.text:
if not answer:
print("\nAnswer:")
print(event.delta.text, end="")
answer += event.delta.text
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const prompt = `Alice, Bob, and Carol each live in a different house on the same
street: red, green, and blue. Alice does not live in the red house.
Bob does not live in the green house.
Carol does not live in the red or green house.
Which house does each person live in?`;
let thoughts = "";
let answer = "";
const stream = await client.interactions.create({
model: "gemini-3.8-flash",
input: prompt,
generation_config: {
thinking_summaries: "auto"
},
stream: true
});
for await (const event of stream) {
if (event.event_type === "step.delta") {
if (event.delta.type === "thought_summary") {
if (!thoughts) console.log("Thinking...");
const text = event.delta.content?.text || "";
process.stdout.write(`[Thought] ${text}`);
thoughts += text;
} else if (event.delta.type === "text" && event.delta.text) {
if (!answer) console.log("\nAnswer:");
process.stdout.write(event.delta.text);
answer += event.delta.text;
}
}
}
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GenerationConfig;
import com.google.genai.gaos.models.interactions.InteractionSSEEvent;
import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.StepDelta;
import com.google.genai.gaos.models.interactions.StepDeltaData;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.TextDelta;
import com.google.genai.gaos.models.interactions.ThinkingSummaries;
import com.google.genai.gaos.models.interactions.ThoughtSummaryDelta;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.gaos.models.operations.CreateInteractionResponse;
import com.google.genai.gaos.utils.EventStream;
Client client = new Client();
String prompt =
"Alice, Bob, and Carol each live in a different house on the same street: red, green, and blue.\n"
+ "Alice does not live in the red house.\n"
+ "Bob does not live in the green house.\n"
+ "Carol does not live in the red or green house.\n"
+ "Which house does each person live in?";
StringBuilder thoughts = new StringBuilder();
StringBuilder answer = new StringBuilder();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of(prompt))
.generationConfig(
GenerationConfig.builder().thinkingSummaries(ThinkingSummaries.AUTO).build())
.stream(true)
.build();
CreateInteractionResponse response =
client.interactions.create(CreateInteractionRequestBody.of(params));
try (EventStream<InteractionSSEStreamEvent> stream = response.events()) {
for (InteractionSSEStreamEvent streamEvent : stream) {
InteractionSSEEvent event = streamEvent.data().orElse(null);
if (event instanceof StepDelta stepDelta) {
StepDeltaData delta = stepDelta.delta().orElse(null);
if (delta instanceof ThoughtSummaryDelta thoughtDelta) {
Content content = thoughtDelta.content().orElse(null);
if (content instanceof TextContent textContent) {
if (thoughts.length() == 0) {
System.out.println("Thinking...");
}
String summaryText = textContent.text().orElse("");
System.out.print("[Thought] " + summaryText);
thoughts.append(summaryText);
}
} else if (delta instanceof TextDelta textDelta) {
String text = textDelta.text().orElse("");
if (!text.isEmpty()) {
if (answer.length() == 0) {
System.out.println("\nAnswer:");
}
System.out.print(text);
answer.append(text);
}
}
}
}
}
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("What is the sum of the first 50 prime numbers?"),
GenerationConfig: &interactions.GenerationConfig{
ThinkingLevel: interactions.ThinkingLevelHigh.ToPointer(),
ThinkingSummaries: interactions.ThinkingSummariesAuto.ToPointer(),
},
}),
})
if err != nil {
log.Fatal(err)
}
for _, step := range res.Interaction.Steps {
if thought := step.ThoughtStep; thought != nil {
for _, part := range thought.Summary {
if part.TextContent != nil {
fmt.Printf("Thought summary:\n%s\n\n", part.TextContent.Text)
}
}
}
}
if res.Interaction.OutputText != nil {
fmt.Printf("Answer:\n%s\n", *res.Interaction.OutputText)
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{
"model": "gemini-3.8-flash",
"input": "Alice, Bob, and Carol each live in a different house on the same street: red, green, and blue. Alice does not live in the red house. Bob does not live in the green house. Carol does not live in the red or green house. Which house does each person live in?",
"generation_config": {
"thinking_summaries": "auto"
},
"stream": true
}'
В потоковом ответе используются события, отправляемые сервером (SSE), и он состоит из шагов и событий, например:
event: interaction.created
data: {"interaction":{"id":"v1_xxx","status":"in_progress","object":"interaction","model":"gemini-3.8-flash"},"event_type":"interaction.created"}
event: step.start
data: {"index":0,"step":{"signature":"","summary":[{"text":"**Evaluating the clues**\n\nI'm considering...","type":"text"}],"type":"thought"},"event_type":"step.start"}
event: step.delta
data: {"index":0,"delta":{"signature":"EpoGCpcGAXLI2nx/...","type":"thought_signature"},"event_type":"step.delta"}
event: step.stop
data: {"index":0,"event_type":"step.stop"}
event: step.start
data: {"index":1,"step":{"content":[{"text":"Based on the clues provided, here","type":"text"}],"type":"model_output"},"event_type":"step.start"}
event: step.delta
data: {"index":1,"delta":{"text":" is the answer to your question...","type":"text"},"event_type":"step.delta"}
event: step.stop
data: {"index":1,"event_type":"step.stop"}
event: interaction.completed
data: {"interaction":{"id":"v1_xxx","status":"completed","usage":{"total_tokens":530,"total_input_tokens":62,"total_output_tokens":171,"total_thought_tokens":297}},"event_type":"interaction.completed"}
event: done
data: [DONE]
Контроль мышления
По умолчанию модели Gemini используют динамическое мышление, автоматически регулируя объем рассуждений в зависимости от сложности запроса. Вы можете управлять этим поведением с помощью параметра thinking_level.
| Модель | Стандартное мышление | Поддерживаемые уровни |
|---|---|---|
| gemini-4-argon | Включено (средний) | низкий, средний, высокий |
| gemini-3.8-flash | Включено (средний уровень) | низкий, средний, высокий |
| gemini-3.6-flash | Включено (средний) | минимальный, низкий, средний, высокий |
| gemini-3.5-flash-lite | Включено (минимальный) | минимальный, низкий, средний, высокий; |
| gemini-3.1-pro-preview | Включено (высокий уровень) | низкий, средний, высокий |
| gemini-3.1-flash-lite-image | Включено (минимальный) | минимальный, высокий |
| gemini-3-flash-preview | Включено (высокий уровень) | минимальный, низкий, средний, высокий; |
| gemini-3-pro-preview | Включено (высокий уровень) | низкий, высокий |
| gemini-2.5-pro | Включено | низкий, средний, высокий |
| gemini-2.5-flash | Включено | низкий, средний, высокий |
| gemini-2.5-flash-lite | Отключено | низкий, средний, высокий |
| gemini-robotics-er-2-preview | Включено (высокая) | минимальный, низкий, средний, высокий |
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Provide a list of 3 famous physicists and their key contributions",
generation_config={
"thinking_level": "low"
}
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3.8-flash",
input: "Provide a list of 3 famous physicists and their key contributions",
generation_config: {
thinking_level: "low"
}
});
console.log(interaction.output_text);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GenerationConfig;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ThinkingLevel;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(
InteractionsInput.of(
"Provide a list of 3 famous physicists and their key contributions"))
.generationConfig(GenerationConfig.builder().thinkingLevel(ThinkingLevel.LOW).build())
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-pro"),
Input: interactions.NewInteractionsInput("What is the sum of the first 50 prime numbers?"),
GenerationConfig: &interactions.GenerationConfig{
ThinkingLevel: interactions.ThinkingLevelHigh.ToPointer(),
ThinkingSummaries: interactions.ThinkingSummariesAuto.ToPointer(),
},
Stream: genai.Ptr(true),
}),
})
if err != nil {
log.Fatal(err)
}
stream := res.InteractionSSEStreamEvent
defer stream.Close()
for stream.Next() {
event := stream.Value()
if stepDelta := event.GetDataStepDelta(); stepDelta != nil {
if thoughtDelta := stepDelta.GetDeltaThoughtSummary(); thoughtDelta != nil {
if textContent := thoughtDelta.GetContentText(); textContent != nil {
fmt.Printf("[Thought Summary] %s\n", textContent.Text)
}
}
if textDelta := stepDelta.GetDeltaText(); textDelta != nil {
fmt.Print(textDelta.GetText())
}
}
}
if err := stream.Err(); err != nil {
log.Fatal(err)
}
}
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.8-flash",
"input": "Provide a list of 3 famous physicists and their key contributions",
"generation_config": {
"thinking_level": "low"
}
}'
Ограничения на количество токенов и max_output_tokens
Параметр генерации max_output_tokens задает максимальное количество токенов, которое может сгенерировать ответ, включая токены размышлений.
Если этот параметр задан, он действует как жесткое ограничение, применяемое инфраструктурой, без изменения того, как модель распределяет свой бюджет на рассуждения (thinking_level).
Если модель достигает этого лимита во время рассуждений, она прекращает генерировать ответ со статусом "incomplete" и возвращает усеченный или пустой результат (при этом плата за все сгенерированные токены рассуждений взимается). Чтобы снизить стоимость или задержку без усечения ответов, уменьшите значение thinking_level (low или medium), а не задавайте небольшое значение max_output_tokens.
Для моделей Gemini 4 (gemini-4-argon) действуют следующие ограничения на контекст и выходные данные:
- Общее окно контекста на 1 млн токенов. Входные, промежуточные и выходные токены используют одно окно контекста на 1 млн токенов (
1,048,576токенов). Если сумма входных токенов иmax_output_tokensпревышает 1 048 576 токенов, API автоматически ограничивает выходные токены оставшимся местом в окне контекста (1,048,576минус входные токены). - Ограничение на синхронный вывод по умолчанию (64 000). Если
background=False(для потоковых и непотоковых запросов), то по умолчанию и максимальноmax_output_tokensограничено65,536токенов. Если задать дляmax_output_tokens > 65536значениеbackground=False, возвращается ошибка400. - Длинное декодирование (до 1 млн токенов). Чтобы Gemini 4 могла рассуждать и генерировать ответы, содержащие более
65,536токенов (до1,048,576токенов), задайтеbackground=Trueи настройтеmax_output_tokensвыше65,536. Подробнее о длительном декодировании…
Подписи мыслей
Подписи мыслей – это зашифрованные представления внутренних рассуждений модели. Они должны сохранять логику рассуждений при многоходовом взаимодействии.
Interactions API упрощает работу с подписями мыслей по сравнению с generateContent API.
Режим с сохранением состояния (рекомендуется)
По умолчанию при использовании API взаимодействий в режиме с сохранением состояния (путем установки значения store: true и передачи previous_interaction_id в последующих запросах) сервер автоматически управляет состоянием разговора, включая все блоки размышлений и подписи. В этом режиме вам не нужно ничего делать с подписями. Они обрабатываются исключительно на стороне сервера.
Режим без отслеживания состояния
Если вы управляете состоянием разговора самостоятельно (режим без сохранения состояния) и передаете полную историю входных и выходных данных в каждом запросе:
- Вы ОБЯЗАНЫ всегда повторно отправлять все блоки
thoughtв том виде, в котором они были получены от модели. - НЕ удаляйте и не изменяйте блоки размышлений в истории, так как они содержат подписи, необходимые модели для продолжения рассуждений.
- При переключении моделей в рамках сеанса вам все равно следует повторно отправить блоки мыслей предыдущей модели. Совместимость обеспечивается на стороне сервера.
Цены
Если мышление включено, цена ответа рассчитывается как сумма токенов вывода и токенов мышления. Общее количество сгенерированных токенов мышления можно узнать из поля total_thought_tokens.
Python
print("Thoughts tokens:", interaction.usage.total_thought_tokens)
print("Output tokens:", interaction.usage.total_output_tokens)
JavaScript
console.log(`Thoughts tokens: ${interaction.usage.total_thought_tokens}`);
console.log(`Output tokens: ${interaction.usage.total_output_tokens}`);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Usage;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Explain the concept of Occam's Razor."))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.usage().isPresent()) {
Usage usage = interaction.usage().get();
System.out.println("Thoughts tokens: " + usage.totalThoughtTokens().orElse(0));
System.out.println("Output tokens: " + usage.totalOutputTokens().orElse(0));
}
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// Turn 1: Execute a reasoning + tool use interaction
turn1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-pro"),
Input: interactions.NewInteractionsInput("Compare the GDP growth of Japan and Germany in 2025."),
Tools: []interactions.Tool{
interactions.NewTool(interactions.GoogleSearch{}),
},
GenerationConfig: &interactions.GenerationConfig{
ThinkingLevel: interactions.ThinkingLevelHigh.ToPointer(),
},
}),
})
if err != nil {
log.Fatal(err)
}
// Turn 2: Pass PreviousInteractionID so thought signatures are automatically preserved
turn2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-pro"),
PreviousInteractionID: turn1.Interaction.ID,
Input: interactions.NewInteractionsInput("Now summarize that comparison in a 3-row markdown table."),
}),
})
if err != nil {
log.Fatal(err)
}
if turn2.Interaction.OutputText != nil {
fmt.Println(*turn2.Interaction.OutputText)
}
}
Думающие модели генерируют полные цепочки рассуждений, чтобы повысить качество итогового ответа, а затем выводят краткие пересказы, чтобы дать представление о ходе мыслей. Цена зависит от количества токенов, которые нужны модели для генерации, несмотря на то, что API возвращает только краткий пересказ.
Подробнее о подсчете токенов…
Рекомендации
Чтобы эффективно использовать модели мышления, следуйте приведенным ниже рекомендациям.
- Просмотр рассуждений. Анализируйте краткие пересказы рассуждений, чтобы понять, почему произошел сбой, и улучшить запросы.
- Управление бюджетом на размышления. Попросите модель меньше думать, чтобы сэкономить токены при создании длинных ответов.
- Простые задачи. Используйте минимальный или низкий уровень рассуждения для поиска фактов или классификации (например, "Где была основана компания DeepMind?").
- Умеренные задачи. Используйте стандартный режим мышления для сравнения концепций или творческого мышления (например, сравните электромобили и гибридные автомобили).
- Сложные задачи. Используйте максимальное время на размышление для написания сложного кода, решения математических задач или многоэтапного планирования (например, для решения задач AIME).
Дальнейшие действия
- Генерирование текста. Простые текстовые ответы.
- Вызов функций. Подключение к инструментам.
- Руководство по Gemini 4: что нового в Gemini 4
- Руководство по Gemini 3: функции, доступные для определенных моделей