Modele Gemini korzystają z „procesu myślenia”, który znacznie poprawia ich zdolność do rozumowania i planowania wieloetapowego. Dzięki temu są one bardzo skuteczne w przypadku złożonych zadań, takich jak kodowanie, zaawansowana matematyka i analiza danych.
Gdy używasz modelu myślenia, Gemini analizuje dane wewnętrznie przed udzieleniem odpowiedzi. Interfejs Interactions API udostępnia to rozumowanie za pomocą kroków thought, czyli specjalnych kroków, które pojawiają się chronologicznie obok wywołań funkcji, danych wejściowych użytkownika lub danych wyjściowych modelu w tablicy steps.
Każdy krok myślenia zawiera 2 pola:
| Pole | Wymagane | Opis |
|---|---|---|
signature |
✅ Tak | Zaszyfrowana reprezentacja wewnętrznego stanu rozumowania modelu. Zawsze obecna, nawet gdy model wykonuje minimalne rozumowanie. |
summary |
❌ Nie | Tablica treści (tekstu lub obrazów) podsumowująca rozumowanie. Może być pusta w zależności od konfiguracji thinking_summaries, tego, czy model przeprowadził wystarczające rozumowanie, lub typu treści (np. obrazy mogą nie mieć podsumowań tekstowych). |
Interakcje z myśleniem
Inicjowanie interakcji z modelem myślenia jest podobne do każdego innego żądania interakcji. W polu model określ jeden z modeli obsługujących myślenie:
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(""));
Go
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."
}'
Podsumowania myśli
Podsumowania myśli zawierają informacje o wewnętrznym procesie rozumowania modelu.
Domyślnie zwracane są tylko dane wyjściowe. Podsumowania myśli możesz włączyć za pomocą 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();
}
}
}
}
Go
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"
}
}'
W tych przypadkach blok myśli może zawierać tylko podpis bez podsumowania:
- Proste żądania, w których model nie przeprowadził wystarczającego rozumowania, aby wygenerować podsumowanie.
thinking_summaries: "none", gdzie podsumowania są wyraźnie wyłączone.- Niektóre typy treści myśli, takie jak obrazy, mogą nie mieć podsumowań tekstowych.
Twój kod powinien zawsze obsługiwać bloki myśli, w których pole summary jest puste lub nieobecne.
Strumieniowanie z myśleniem
Użyj strumieniowania, aby otrzymywać przyrostowe podsumowania myśli podczas generowania. Bloki myśli są dostarczane za pomocą zdarzeń wysyłanych przez serwer (SSE) z 2 różnymi typami delta:
| Typ delta | Zawiera | Kiedy wysłano |
|---|---|---|
thought_summary |
Treść podsumowania tekstowego lub obrazu | Co najmniej 1 delta z przyrostowym podsumowaniem |
thought_signature |
Podpis kryptograficzny | Ostatnia delta przed 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);
}
}
}
}
}
Go
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
}'
Odpowiedź strumieniowa korzysta ze zdarzeń wysyłanych przez serwer (SSE) i składa się z kroków i zdarzeń, np.:
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]
Kontrolowanie myślenia
Modele Gemini domyślnie korzystają z myślenia dynamicznego, automatycznie dostosowując ilość rozumowania do złożoności żądania. To zachowanie możesz kontrolować za pomocą parametru thinking_level.
| Model | Domyślne myślenie | Obsługiwane poziomy |
|---|---|---|
| gemini-4-argon | Włączone (średnie) | niski, średni, wysoki |
| gemini-3.8-flash | Włączone (średnie) | niski, średni, wysoki |
| gemini-3.6-flash | Włączone (średnie) | minimalny, niski, średni, wysoki |
| gemini-3.5-flash-lite | Włączone (minimalne) | minimalny, niski, średni, wysoki |
| gemini-3.1-pro-preview | Włączone (wysokie) | niski, średni, wysoki |
| gemini-3.1-flash-lite-image | Włączone (minimalne) | minimalny, wysoki |
| gemini-3-flash-preview | Włączone (wysokie) | minimalny, niski, średni, wysoki |
| gemini-3-pro-preview | Włączone (wysokie) | niski, wysoki |
| gemini-2.5-pro | Włączone | niski, średni, wysoki |
| gemini-2.5-flash | Włączone | niski, średni, wysoki |
| gemini-2.5-flash-lite | Wyłączone | niski, średni, wysoki |
| gemini-robotics-er-2-preview | Włączone (wysokie) | minimalny, niski, średni, wysoki |
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(""));
Go
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"
}
}'
Limity tokenów i max_output_tokens
Parametr generowania max_output_tokens określa maksymalną liczbę tokenów, które może wygenerować odpowiedź, w tym
tokeny myśli.
Gdy ten parametr jest ustawiony, działa jako twardy limit egzekwowany przez infrastrukturę bez zmiany sposobu, w jaki model przydziela budżet na myślenie (thinking_level).
Jeśli model osiągnie ten limit podczas rozumowania, przestanie generować dane ze stanem
"incomplete" i zwróci obcięte lub puste dane wyjściowe (przy jednoczesnym naliczaniu opłat za
wygenerowane tokeny myśli). Aby zmniejszyć koszty lub opóźnienia bez obcinania odpowiedzi, zmniejsz wartość thinking_level (low lub medium) zamiast ustawiać małą wartość max_output_tokens.
W przypadku modeli Gemini 4 (gemini-4-argon) pamiętaj o tych limitach kontekstu i danych wyjściowych:
- Wspólne okno kontekstu o wielkości 1 mln tokenów: tokeny wejściowe, myśli i wyjściowe współdzielą jedno okno kontekstu o wielkości 1 mln tokenów (
1,048,576tokenów). Jeśli tokeny wejściowe plusmax_output_tokensprzekroczą 1 048 576 tokenów, interfejs API automatycznie ograniczy limit danych wyjściowych do pozostałego miejsca w oknie kontekstu (1,048,576minus tokeny wejściowe). - Domyślny limit synchronicznych danych wyjściowych (64 tys.): gdy
background=False(w przypadku żądań strumieniowych i niestrumieniowych), domyślny i maksymalny limitmax_output_tokenswynosi65,536tokenów. Ustawieniemax_output_tokens > 65536zbackground=Falsezwraca błąd400. - Długie dekodowanie (do 1 mln tokenów): aby umożliwić Gemini 4 rozumowanie i generowanie danych powyżej
65,536tokenów (do1,048,576tokenów), ustawbackground=Truei skonfigurujmax_output_tokensna wartość większą niż65,536. Więcej informacji znajdziesz w sekcji Długie dekodowanie.
Podpisy myśli
Podpisy myśli to zaszyfrowane reprezentacje wewnętrznego rozumowania modelu. Są one wymagane do zachowania ciągłości rozumowania w interakcjach wieloetapowych.
Interfejs Interactions API znacznie upraszcza obsługę podpisów myśli w porównaniu z interfejsem generateContent API.
Tryb stanowy (zalecany)
Domyślnie, gdy używasz interfejsu Interactions API w trybie stanowym (ustawiając store: true i przekazując previous_interaction_id w kolejnych turach), serwer automatycznie zarządza stanem rozmowy, w tym wszystkimi blokami myśli i podpisami. W tym trybie nie musisz nic robić w związku z podpisami. Są one obsługiwane w całości po stronie serwera.
Tryb bezstanowy
Jeśli samodzielnie zarządzasz stanem rozmowy (tryb bezstanowy) i przekazujesz pełną historię danych wejściowych i wyjściowych w każdym żądaniu:
- MUSISZ zawsze ponownie wysyłać wszystkie bloki
thoughtdokładnie tak, jak zostały odebrane z modelu. - NIE POWINIENEŚ usuwać ani modyfikować bloków myśli z historii, ponieważ zawierają one podpisy wymagane do kontynuowania rozumowania przez model.
- Podczas przełączania modeli w ramach sesji nadal należy ponownie wysyłać bloki myśli poprzedniego modelu. Backend zarządza zgodnością.
Ceny
Gdy myślenie jest włączone, cena odpowiedzi jest sumą tokenów wyjściowych i tokenów myśli. Łączną liczbę wygenerowanych tokenów myśli możesz uzyskać z pola 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));
}
Go
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)
}
}
Modele myślenia generują pełne myśli, aby poprawić jakość ostatecznej odpowiedzi, a następnie podsumowania, aby zapewnić wgląd w proces myślenia. Ceny są oparte na pełnych tokenach myśli, które model musi wygenerować, mimo że interfejs API zwraca tylko podsumowanie.
Więcej informacji o tokenach znajdziesz w przewodniku po zliczaniu tokenów.
Sprawdzone metody
Aby efektywnie korzystać z modeli myślenia, postępuj zgodnie z tymi wskazówkami.
- Sprawdzanie rozumowania: analizuj podsumowania myśli, aby zrozumieć przyczyny niepowodzeń i ulepszyć prompty.
- Kontrolowanie budżetu na myślenie: poproś model, aby mniej myślał w przypadku długich danych wyjściowych, aby zaoszczędzić tokeny.
- Proste zadania: używaj minimalnego lub niskiego myślenia do wyszukiwania faktów lub klasyfikacji (np. „Gdzie została założona firma DeepMind?”).
- Umiarkowane zadania: używaj domyślnego myślenia do porównywania koncepcji lub kreatywnego rozumowania (np. porównaj samochody elektryczne i samochody hybrydowe).
- Złożone zadania: używaj maksymalnego myślenia do zaawansowanego kodowania, matematyki lub planowania wieloetapowego (np. rozwiązywania problemów matematycznych AIME).
Co dalej?
- Generowanie tekstu: podstawowe odpowiedzi tekstowe
- Wywoływanie funkcji: łączenie z narzędziami
- Przewodnik po Gemini 4: co nowego w Gemini 4
- Przewodnik po Gemini 3: funkcje specyficzne dla modelu