# Gemini 思考能力

[Gemini型号](/docs/models) 使用“思维过程”可以显着提高他们的推理和多步骤规划能力，使他们能够高效地完成编码、高等数学和数据分析等复杂任务。

当您使用思维模型时，Gemini 在做出响应之前会在内部进行推理。 Interactions API 通过以下方式表达了这一推理 `thought` 步骤，按时间顺序与函数调用、用户输入或模型输出一起出现的专用步骤 `steps` 数组。

每个思考步骤都包含两个字段：

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
领域
{% /doc-cell %}

{% doc-cell %}
必填
{% /doc-cell %}

{% doc-cell %}
说明
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
`signature`
{% /doc-cell %}

{% doc-cell %}
✅ 是的
{% /doc-cell %}

{% doc-cell %}
模型内部推理状态的加密表示。即使模型执行最少的推理，也始终存在。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
`summary`
{% /doc-cell %}

{% doc-cell %}
❌ 没有
{% /doc-cell %}

{% doc-cell %}
总结推理的内容数组（文本和/或图像）。可能为空，具体取决于 [`thinking_summaries`](/api-reference/interactions-api) 配置，模型是否执行了足够的推理，或者内容类型（例如，图像潜在可能没有文本摘要）。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% callout type="note" %}
Interactions API 处理想法和签名的方式与 `generateContent` API：

- 在 `generateContent` API，没有专用的思维块。正因为如此，签名是可以附加到任何部分的元数据，例如生活在里面 `functionCall` 部分或响应的最后部分。
- 在Interactions API中，思想是专注的一流表现 `thought` 步骤。由于此签名仅限于两个已知位置， `thought` 步骤或内置工具步骤（例如 `google_search_call`/ `google_search_result`）。它们永远不会出现在用户输入、模型输出或标准函数调用中。
{% /callout %}

## 与思维的互动  {% #interactions-with-thinking %}

启动与思维模型的交互与任何其他交互请求类似。指定其中一项 [有思维支撑的模型](/docs/thinking#thinking-levels) 在 `model` 字段：

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Explain the concept of Occam's Razor and provide a simple, everyday example."
)
print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: "gemini-4-hydrogen",
    input: "Explain the concept of Occam's Razor and provide a simple, everyday example."
});
console.log(interaction.output_text);
```
{% /tab %}

{% tab label="Java" %}
```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-4-hydrogen"))
        .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(""));
```
{% /tab %}

{% tab label="Go" %}
```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-4-hydrogen"),
            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)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "Explain the concept of Occam'\''s Razor and provide a simple example."
  }'
```
{% /tab %}
{% /tabs %}

## 思想总结  {% #summaries %}

思想摘要提供了对模型内部推理过程的见解。默认情况下，仅返回最终输出。您可以使用以下方式启用思想摘要 `thinking_summaries`:

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    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()
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: "gemini-4-hydrogen",
    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);
            }
        }
    }
}
```
{% /tab %}

{% tab label="Java" %}
```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-4-hydrogen"))
        .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();
      }
    }
  }
}
```
{% /tab %}

{% tab label="Go" %}
```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-4-hydrogen"),
            Input: interactions.NewInteractionsInput("What is the sum of the first 50 prime numbers?"),
            GenerationConfig: &interactions.GenerationConfig{
                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)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "What is the sum of the first 50 prime numbers?",
    "generation_config": {
      "thinking_summaries": "auto"
    }
  }'
```
{% /tab %}
{% /tabs %}

思想块可能包含 **只有签名，没有摘要** 在这些情况下：

* 简单的请求，模型没有足够的理由来生成摘要
* `thinking_summaries: "none"`，其中明确禁用摘要
* 某些思想内容类型（例如图像）可能没有文本摘要

你的代码应该始终处理思想块 `summary` 为空或不存在。

## 流淌着思考  {% #streaming-with-thinking %}

使用流式传输在生成过程中接收增量思想摘要。思想块是使用服务器发送事件 (SSE) 传递的，具有两种不同的增量类型：

| 三角型                 | 包含        | 发送时                   |
| ------------------- | --------- | --------------------- |
| `thought_summary`   | 文字或图片摘要内容 | 具有增量摘要的一个或多个增量        |
| `thought_signature` | 加密签名      | 之前的最后一个增量 `step.stop` |

{% tabs %}
{% tab label="Python" %}
```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-4-hydrogen",
    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
```
{% /tab %}

{% tab label="JavaScript" %}
```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-4-hydrogen",
    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...");
            if (event.delta.content?.type === "text") {
                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;
        }
    }
}
```
{% /tab %}

{% tab label="Java" %}
```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-4-hydrogen"))
        .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);
        }
      }
    }
  }
}
```
{% /tab %}

{% tab label="Go" %}
```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"
)

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

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-4-hydrogen"),
            Input: interactions.NewInteractionsInput(prompt),
            GenerationConfig: &interactions.GenerationConfig{
                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] %s", textContent.Text)
                }
            }
            if textDelta := stepDelta.GetDeltaText(); textDelta != nil {
                fmt.Print(textDelta.GetText())
            }
        }
    }
    if err := stream.Err(); err != nil {
        log.Fatal(err)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
  -H 'Content-Type: application/json' \
  --no-buffer \
  -d '{
    "model": "gemini-4-hydrogen",
    "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
  }'
```
{% /tab %}
{% /tabs %}

流响应使用服务器发送事件 (SSE)，由步骤和事件组成，例如：

```none
event: interaction.created
data: {"interaction":{"id":"v1_xxx","status":"in_progress","object":"interaction","model":"gemini-4-hydrogen"},"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]
```

## 控制思维  {% #thinking-levels %}

Gemini 模型默认采用动态思维，根据请求的复杂性自动调整推理工作量。您可以使用以下命令控制此行为 `thinking_level` 参数。

| 模型                           | 默认思维  | 支持的级别    |
| ---------------------------- | ----- | -------- |
| gemini-4-carbon              | 开（中）  | 低、中、高    |
| gemini-4-argon               | 开（中）  | 低、中、高    |
| gemini-4-hydrogen            | 开（高）  | 低、中、高、x高 |
| gemini-3.8-flash             | 开（中）  | 低、中、高    |
| gemini-3.6-flash             | 开（中）  | 最小、低、中、高 |
| gemini-3.5-flash-lite        | 开（最小） | 最小、低、中、高 |
| gemini-3.1-pro-preview       | 开（高）  | 低、中、高    |
| gemini-3.1-flash-lite        | 开（最小） | 最小、低、中、高 |
| 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 | 开（高）  | 最小、低、中、高 |

### 了解思维层次  {% #understanding-thinking-levels %}

该 `thinking_level` 是您对质量、延迟和 token 使用的主要控制 [Gemini 4 Hydrogen](/docs/whats-new-gemini-4-hydrogen)。该模型默认为 `high` 并介绍 `xhigh`:

| 思维层面                              | 代币使用               | 何时使用                                                                                                                                                                                        |
| --------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `low`                             | 最少的token，最低的延迟     | 对成本和延迟敏感的工作负载，例如快速聊天和高吞吐量处理。仍然有能力执行智能体任务。                                                                                                                                                   |
| `medium`                          | token 使用率更低，响应速度更快 | 交互式编码、实时 UI 原型、响应式聊天和延迟敏感的工具调用。 （默认开启 `gemini-4-carbon`, `gemini-4-argon`, `gemini-3.8-flash`, 和 `gemini-3.6-flash`.)                                                                       |
| `high` （默认开启 `gemini-4-hydrogen`) | 平衡智力和速度            | 建议默认开启 `gemini-4-hydrogen` 适用于大多数任务，包括复杂编码、智能体执行、工具调用和多模态知识工作。最大推理深度 `gemini-4-carbon`, `gemini-4-argon`和 Gemini 3 型号。                                                                      |
| `xhigh`                           | 最token，最深刻的推理      | 为困难的、多步骤的编码和智能体问题保留，其中 `high` 当您可以交易更高的延迟和 token 使用（支持 `gemini-4-hydrogen`).                                                                                                                |
| `minimal`                         | 近距离思考，最低延迟         | 与大多数查询的接近关闭设置相匹配 `gemini-3.6-flash`, `gemini-3.5-flash-lite` （默认）， `gemini-3.1-flash-lite`, `gemini-3-flash-preview`, 和 `gemini-robotics-er-2-preview`。 Gemini 4 型号不支持或 `gemini-3.8-flash`. |

开始于 `high` 对于最复杂的任务，并保留 `xhigh` 对于困难的、多步骤的问题，其中 `high` 达不到要求。使用 `xhigh` 增加延迟和 token 使用，并可能导致过度思考或耗尽 `max_output_tokens` 更简单的提示，例如文本或 JSON 提取。在所有四个级别上进行高评价 `max_output_tokens` 所以限制不会缩短答案，然后选择最低的 `thinking_level` 符合您的质量标准。

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Audit this payment retry queue for race conditions and rewrite the lock acquisition logic.",
    generation_config={
        "thinking_level": "xhigh"
    }
)

print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
  model: "gemini-4-hydrogen",
  input: "Audit this payment retry queue for race conditions and rewrite the lock acquisition logic.",
  generation_config: {
    thinking_level: "xhigh",
  },
});

console.log(interaction.output_text);
```
{% /tab %}

{% tab label="REST" %}
```bash
curl "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "Audit this payment retry queue for race conditions and rewrite the lock acquisition logic.",
    "generation_config": {
      "thinking_level": "xhigh"
    }
  }'
```
{% /tab %}
{% /tabs %}

下面的例子设置 `thinking_level` 到 `low`:

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Provide a list of 3 famous physicists and their key contributions",
    generation_config={
        "thinking_level": "low"
    }
)
print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: "gemini-4-hydrogen",
    input: "Provide a list of 3 famous physicists and their key contributions",
    generation_config: {
        thinking_level: "low"
    }
});
console.log(interaction.output_text);
```
{% /tab %}

{% tab label="Java" %}
```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-4-hydrogen"))
        .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(""));
```
{% /tab %}

{% tab label="Go" %}
```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-4-hydrogen"),
            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)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "Provide a list of 3 famous physicists and their key contributions",
    "generation_config": {
      "thinking_level": "low"
    }
  }'
```
{% /tab %}
{% /tabs %}

### 代币限制和 `max_output_tokens` {% #token-limits %}

该 [`max_output_tokens`](/api-reference/interactions-api/create-interaction#request-body)
Generation 参数设置响应可以生成的 token 的最大数量，包括 token。

设置后，此参数充当基础设施强制执行的硬截止，而不改变模型分配其思考预算的方式（`thinking_level`).

如果模型在推理时达到此限制，它将停止生成状态 `"incomplete"` 并返回截断或空的输出（同时仍然对生成的任何思考 token 进行计费）。要在不截断响应的情况下降低成本或延迟，请降低 `thinking_level` (`low` 或 `medium`）而不是设置一个小的 `max_output_tokens`.

对于 Gemini 4 型号（`gemini-4-carbon`, `gemini-4-argon`, 和 `gemini-4-hydrogen`），请记住以下上下文和输出限制：

* **共享 1M 上下文窗口：** 输入、思考和输出token共用一个1M-token 上下文窗口（`1,048,576` token）。如果你输入token加上 `max_output_tokens` 超过 1,048,576 token 时，API 自动将输出限制限制为上下文窗口中的剩余空间（`1,048,576` 减去您的输入 token）。
* **默认同步输出上限（64K）：** 当 `background=False`，默认 `max_output_tokens` 上限为 65,536 token。单个前台跃点最多可生成 65,536 token 用于流式调用和 `gemini-4-hydrogen` 非流式呼叫，或高达 32,768 token（对于非流式呼叫） `gemini-4-carbon` 和 `gemini-4-argon`.
* **长解码（最多 1M token）：** 让Gemini 4能够推理并生成超越 `65,536` token（最多 `1,048,576` token），配置 `max_output_tokens` 大于 `65,536` 使用 `background=True` 或客户端延续。参见 [长输出](/docs/long-decode) 了解详情。

## 思考签名  {% #signatures %}

思想签名是模型内部推理的加密表示。他们需要在多轮交互中保持推理连续性。

Interactions API 使处理思想签名比 `generateContent` API。

### 有状态模式（推荐）  {% #stateful-mode-recommended %}

默认情况下，当您在有状态模式下使用 Interactions API 时（通过设置 `store: true` 并通过 `previous_interaction_id` 在后续回合中），服务器自动管理对话状态，包括所有思想块和签名。在此模式下，您不需要对签名进行任何操作。它们完全在服务器端处理。

### 无状态模式  {% #stateless-mode %}

如果您自己管理对话状态（无状态模式）并在每个请求中传递输入和输出的完整历史记录：

* 你 **MUST** 总是重新发送全部 `thought` 块与从模型接收到的块完全相同。
* 你应该 **NOT** 从历史记录中删除或修改思想块，因为它们包含模型继续推理所需的签名。
* 在会话中切换模型时，您仍然应该重新发送先前模型的思维块。后端管理兼容性。

{% callout type="note" %}
注意：Google 搜索等内置工具可以在调用/结果块上携带自己独特的签名。在无状态模式下，您还必须在后续回合中重新发送这些工具结果签名。
{% /callout %}

## 价格  {% #pricing %}

当思维打开时，响应定价是输出 token 和思维 token 之和。您可以从生成思维的总数token `total_thought_tokens` 场。

{% tabs %}
{% tab label="Python" %}
```python
print("Thoughts tokens:", interaction.usage.total_thought_tokens)
print("Output tokens:", interaction.usage.total_output_tokens)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
console.log(`Thoughts tokens: ${interaction.usage.total_thought_tokens}`);
console.log(`Output tokens: ${interaction.usage.total_output_tokens}`);
```
{% /tab %}

{% tab label="Java" %}
```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-4-hydrogen"))
        .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));
}
```
{% /tab %}

{% tab label="Go" %}
```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-4-hydrogen"),
            Input: interactions.NewInteractionsInput("Explain the concept of Occam's Razor."),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if usage := res.Interaction.Usage; usage != nil {
        if usage.TotalThoughtTokens != nil {
            fmt.Println("Thoughts tokens:", *usage.TotalThoughtTokens)
        }
        if usage.TotalOutputTokens != nil {
            fmt.Println("Output tokens:", *usage.TotalOutputTokens)
        }
    }
}
```
{% /tab %}
{% /tabs %}

思维模型产生完整的想法，提高最终响应的质量，然后输出 [摘要](/docs/thinking#summaries) 提供对思维过程的洞察。定价基于模型需要生成的 token 的完整想法，尽管 API 仅输出摘要。

{% callout type="note" %}
因为 `max_output_tokens` 适用于思维 token 和输出 token 的组合总计，设置下限可以截断响应。参见 [代币限制和 `max_output_tokens`](/docs/thinking#token-limits) 了解详情。
{% /callout %}

您可以在以下位置了解有关 token 的更多信息 [token 计数](/docs/tokens) 指导。

## 最佳实践  {% #best-practices %}

遵循这些准则可以有效地使用思维模型。

- **复习推理**：分析思想总结以了解失败并改进提示。
- **控制思维预算**：提示模型少考虑冗长的输出以保存 token。
- **简单的任务**：使用最少的思维进行事实检索或分类（例如，“DeepMind 是在哪里成立的？”）。
- **中等任务**：使用默认思维来比较概念或创造性推理（例如，比较电动汽车和混合动力汽车）。
- **复杂的任务**：最大限度地思考高级编码、数学或多步骤规划（例如，解决 AIME 数学问题）。

## 后续步骤  {% #whats-next %}

- [文本生成](/docs/text-generation)：基本文本回复
- [函数调用](/docs/function-calling)：连接到工具
- [最新 Gemini 模型](/docs/latest-model)：比较型号并阅读新增功能指南
