开始思考:Jupyter Notebook 入门指南

本教程面向有编程基础的开发者,深入讲解 Gemini 模型的思考模式(Thinking Mode)。通过 Jupyter Notebook 实践,你将学会使用 Interactions API 控制思考级别(minimal 到 high),理解思考 token 的计量,并掌握如何结合代码执行、Google 搜索等工具解决复杂问题。教程涵盖环境配置、API 密钥设置、多模态推理示例,以及从旧版 thinking_budget 迁移到 thinking_level 的指南,帮助你在实际项目中平衡推理深度与响应速度。

技术背景

传统语言模型直接生成答案,在复杂任务(如多步推理、数学计算)中容易出错。Gemini 模型引入了显式的思考过程,在生成最终答案前进行内部推理,显著提升复杂任务的准确性。思考级别(Thinking Level)允许开发者控制推理深度,在响应速度、成本和推理质量之间取得平衡。本教程基于最新的 Interactions API,取代了旧的 generateContent API,提供更简洁的交互方式。

核心原理

Gemini 模型在生成最终答案前,会先产生一系列思考 token(thought tokens),这些 token 不直接输出给用户,但会消耗计算资源。思考级别(minimal、low、medium、high)控制模型允许的思考量:high 允许模型根据任务复杂度动态调整,low 则限制思考量,可能导致复杂任务表现不佳。通过 usage_metadata 可以查看思考 token 数量,从而监控推理成本。Interactions API 将请求和响应封装为 interaction 对象,支持流式输出和工具调用。

架构分析

本教程的架构围绕 Interactions API 展开:客户端初始化(genai.Client)→ 创建交互(client.interactions.create)→ 配置思考级别(ThinkingConfig)→ 处理响应(interaction.steps)。关键组件包括:模型 ID(如 gemini-3.7-flash)、思考配置(ThinkingConfig)、工具(如代码执行、Google 搜索)。设计上,Interactions API 统一了文本、图像、工具调用等输入,并通过 steps 数组返回模型输出和工具执行结果,便于开发者解析。

完整实战教程

##### 版权所有 2026 Google LLC.

#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

使用 Gemini 思考

注意: 本笔记本使用 Interactions API,这是与 Gemini 模型交互的最新方式。正在寻找 generateContent 版本?请查看归档分支。

所有 Gemini 模型都经过训练,在得出最终答案之前会进行思考过程(或推理)。因此,这些模型在需要多个处理步骤的较难任务上通常能取得更好的结果:复杂数学、编码、多步骤指令推理和多模态理解。

虽然思考始终开启,但您可以通过使用思考级别(minimal、low、medium、high)来配置模型进行思考的量。这使您可以根据用例在响应速度/成本与推理深度之间取得平衡。

理解思考模型

思考模型针对需要多轮策略制定和迭代求解的复杂任务进行了优化。

您可以使用思考级别来控制思考力度:

| 思考级别 | 使用场景 |

|---|---|

| 高(默认) | 复杂推理、数学、编码、多步骤问题 |

| 中 | 在速度和推理之间取得良好平衡 |

| 低 | 响应更快,但有一定推理 |

| 最低 | 响应最快,推理最少(大致相当于“关闭”) |

您可以使用 types.ThinkingConfig(thinking_level=types.ThinkingLevel.HIGH) 设置思考级别。

设置

本节将安装 SDK,使用你的 API 密钥 进行设置,导入相关库,下载示例视频并将其上传到 Gemini。

如果你想直接跳到示例,只需折叠(点击标题左侧的小箭头)并运行本节(但别忘了运行它,否则什么都不会工作)。

安装 SDK

Google Gen AI SDK 提供了对 Gemini 模型的编程访问,支持 Google AI for Developers 和 Vertex AI API。除少数例外,在一个平台上运行的代码也可以在另一个平台上运行。这意味着您可以使用开发者 API 快速构建原型,然后无需重写代码即可将应用迁移到 Vertex AI。

有关此新 SDK 的更多详细信息,请参阅文档或入门指南。

image](../quickstarts/Get_started.ipynb) 笔记本。

%pip install -U -q "google-genai>=2.9.0" # 2.0 is needed to use the interactions API

设置你的 API 密钥

要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab 密钥中。如果你还没有 API 密钥,或者不确定如何创建 Colab 密钥,请参阅 [身份验证]

image](../quickstarts/Authentication.ipynb) 查看演练。

from google.colab import userdata

GEMINI_API_KEY=userdata.get('GEMINI_API_KEY')

初始化 SDK 客户端

使用新版 SDK,你现在只需使用 API 密钥(或如果使用 Vertex AI 则使用 OAuth)初始化一个客户端即可。模型现在在每次调用中设置。

from google import genai
from google.genai import types

client = genai.Client(api_key=GEMINI_API_KEY)
MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}

导入

import json
from PIL import Image
from IPython.display import display, Markdown

使用思考模型

以下是一些复杂的示例,展示了 Gemini 思考模型可以解决的问题。

在每个示例中,您可以选择不同的模型来比较它们的表现。

在某些情况下,即使使用较低的思考级别,您仍然可以获得不错的答案。在这种情况下,请使用 minimal 思考级别重新运行示例,以了解模型从更深层次的推理中获益多少。

使用思考级别

你可以先让模型解释一个概念,看看它在回答之前是如何进行推理的。

默认情况下,模型使用 high 思考级别,这使其能够根据请求的复杂性动态调整推理深度。

prompt = """
    You are playing the 20 question game. You know that what you are looking for
    is a aquatic mammal that doesn't live in the sea, is venomous and that's
    smaller than a cat. What could that be and how could you make sure?
"""

interaction = client.interactions.create(
    model=MODEL_ID,
    input=prompt
)

Markdown(interaction.steps[-1].content[0].text)

查看响应元数据,你不仅可以看到输入中的 token 数量和用于响应的 token 数量,还可以看到用于思考步骤的 token 数量——正如你在这里看到的,模型在思考步骤中使用了大约 1400 个 token。

print("Prompt tokens:",response.usage_metadata.prompt_token_count)
print("Thoughts tokens:",response.usage_metadata.thoughts_token_count)
print("Output tokens:",response.usage_metadata.candidates_token_count)
print("Total tokens:",response.usage_metadata.total_token_count)

最小思考

你可以将思考设置为 minimal,以获得几乎不需要推理的更快响应。你会看到,在这种情况下,模型不会像之前那样深入地思考问题。

if "-pro" not in MODEL_ID:
  prompt = """
      You are playing the 20 question game. You know that what you are looking for
      is a aquatic mammal that doesn't live in the sea, is venomous and that's
      smaller than a cat. What could that be and how could you make sure?
  """

  interaction = client.interactions.create(
    model=MODEL_ID,
    input=prompt,
    config=types.GenerateContentConfig(
      thinking_config=types.ThinkingConfig(
        thinking_level="none"
      )
    )
  )

  Markdown(interaction.steps[-1].content[0].text)

else:
  print("You can't disable thinking for pro models.")

现在你可以看到,由于模型没有执行任何思考步骤,响应速度更快了。同时你也会发现,思考步骤没有消耗任何 token。

print("Prompt tokens:",response.usage_metadata.prompt_token_count)
print("Thoughts tokens:",response.usage_metadata.thoughts_token_count)
print("Output tokens:",response.usage_metadata.candidates_token_count)
print("Total tokens:",response.usage_metadata.total_token_count)

<a name="physics"></a>

解决一个物理问题

现在,尝试一个复杂的物理问题。首先使用 minimal 思考模式,看看模型的表现如何:

if "-pro" not in MODEL_ID:
    prompt = """
            A cantilever beam of length L=3m has a rectangular cross-section (width b=0.1m, height h=0.2m) and is made of steel (E=200 GPa).
            It is subjected to a uniformly distributed load w=5 kN/m along its entire length and a point load P=10 kN at its free end.
            Calculate the maximum bending stress (σ_max).
    """

    interaction = client.interactions.create(
            model=MODEL_ID,
            input=prompt,
            config=types.GenerateContentConfig(
                    thinking_config=types.ThinkingConfig(
                            thinking_level="none"
                    )
            )
    )

    Markdown(interaction.steps[-1].content[0].text)

else:
    print("You can't disable thinking for pro models.")

你可以看到,在极少的思考下,模型用于推理的令牌非常少。

print("Prompt tokens:",response.usage_metadata.prompt_token_count)
print("Thoughts tokens:",response.usage_metadata.thoughts_token_count)
print("Output tokens:",response.usage_metadata.candidates_token_count)
print("Total tokens:",response.usage_metadata.total_token_count)

然后你可以使用 high 思考模式来观察模型在完整推理下的表现。

你可以看到,即使对于相同的提示,当模型被允许进行更深入的思考时,回答的深度和一致性也会显著提高。

注意: 你始终可以在 usage_metadata 中查看思考步骤使用了多少 token。

prompt = """
    A cantilever beam of length L=3m has a rectangular cross-section (width b=0.1m, height h=0.2m) and is made of steel (E=200 GPa).
    It is subjected to a uniformly distributed load w=5 kN/m along its entire length and a point load P=10 kN at its free end.
    Calculate the maximum bending stress (σ_max).
"""

interaction = client.interactions.create(
    model=MODEL_ID,
    input=prompt,
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level=types.ThinkingLevel.HIGH
        )
    )
)

Markdown(interaction.steps[-1].content[0].text)

现在你可以看到,模型在推理上使用了明显更多的令牌:

print("Prompt tokens:",response.usage_metadata.prompt_token_count)
print("Thoughts tokens:",response.usage_metadata.thoughts_token_count)
print("Output tokens:",response.usage_metadata.candidates_token_count)
print("Total tokens:",response.usage_metadata.total_token_count)

请记住,更高的思考级别意味着模型会花费更多时间进行推理,这意味着更长的计算时间和更昂贵的请求。

<a name="geometry"></a>

处理多模态问题

这个几何问题需要复杂的推理,并且还利用了 Gemini 的多模态能力来读取图像。

!wget https://storage.googleapis.com/generativeai-downloads/images/geometry.png -O geometry.png -q

geometry_image = Image.open("geometry.png").resize((256,256))
geometry_image
prompt = "What's the area of the overlapping region?"

interaction = client.interactions.create(
    model=MODEL_ID,
    input=[geometry_image, prompt],
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level=types.ThinkingLevel.HIGH
        )
    )
)

Markdown(interaction.steps[-1].content[0].text)

解决脑筋急转弯

这里还有一个基于图像的脑筋急转弯,这次看起来像是一个数学问题,但实际上无法用数学方法解决。如果你查看模型的思考过程,你会发现它意识到了这一点,并想出了一个跳出常规的解决方案。

!wget https://storage.googleapis.com/generativeai-downloads/images/pool.png -O pool.png -q

pool_image = Image.open("pool.png").resize((256,256))
pool_image

首先,你可以检查模型在minimal思考模式下的表现:

interaction = client.interactions.create(
    model=MODEL_ID,
    input=[
        pool_image,
        "How do I use those three pool balls to sum up to 30?"
    ],
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level=types.ThinkingLevel.MINIMAL
        )
    )
)

Markdown(interaction.steps[-1].content[0].text)

如你所见,模型在寻找解题路径时遇到了困难——最终建议使用不同的台球。

现在你可以使用 high 思考模式来解决这个谜题:

prompt = "How do I use those three pool balls to sum up to 30?"

interaction = client.interactions.create(
    model=MODEL_ID,
    input=[
        pool_image,
        prompt,
    ],
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level=types.ThinkingLevel.HIGH
        )
    )
)

Markdown(interaction.steps[-1].content[0].text)

<a name="math"></a>

用高思考模式解决数学谜题

这通常是你想要使用 high 思考模式的情况,因为模型在找到正确答案之前需要探索许多方向。

prompt = """
   How can you obtain 565 with 10 8 3 7 1 and 5 and the common operations?
   You can only use a number once.
"""

interaction = client.interactions.create(
    model=MODEL_ID,
    input=prompt,
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level=types.ThinkingLevel.HIGH
        )
    )
)

display(Markdown(interaction.steps[-1].content[0].text))

<a name="thoughts_summaries"></a>

工作思路摘要

模型思考的摘要揭示了其内部解决问题的路径。用户可以利用此功能来检查模型的策略,并在处理复杂任务时保持知情。

有关 Gemini 思考能力的更多详细信息,请参阅 Gemini 模型思考指南。

prompt = """
  Alice, Bob, and Carol each live in a different house on the same street: red, green, and blue.
  The person who lives in the red house owns a cat.
  Bob does not live in the green house.
  Carol owns a dog.
  The green house is to the left of the red house.
  Alice does not own a cat.
  Who lives in each house, and what pet do they own?
"""

interaction = client.interactions.create(
  model=MODEL_ID,
  input=prompt,
  config=types.GenerateContentConfig(
    thinking_config=types.ThinkingConfig(
      include_thoughts=True
    )
  )
)

你可以同时查看思考摘要和模型的最终回答。

for step in interaction.steps:
    if step.type == "model_output":
        for content in step.content:
            if hasattr(content, 'thought') and content.thought:
                display(Markdown("## **Thoughts summary:**"))
                display(Markdown(content.text))
                print()
            elif content.text:
                display(Markdown("## **Answer:**"))
                display(Markdown(content.text))

你还可以在流式体验中查看思考摘要:

prompt = """
    Alice, Bob, and Carol each live in a different house on the same street: red,
    green, and blue.
    The person who lives in the red house owns a cat.
    Bob does not live in the green house.
    Carol owns a dog.
    The green house is to the left of the red house.
    Alice does not own a cat.
    Who lives in each house, and what pet do they own?
"""

thoughts = ""
answer = ""

for event in client.interactions.create(
    model=MODEL_ID,
    input=prompt,
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level=types.ThinkingLevel.HIGH
        )
    ),
    stream=True,
):
    if hasattr(event, 'delta'):
        if hasattr(event.delta, 'thought') and event.delta.thought:
            thoughts += event.delta.text or ""
        elif hasattr(event.delta, 'text') and event.delta.text:
            answer += event.delta.text

display(Markdown("## **Thoughts summary:**"))
display(Markdown(thoughts))
print()
display(Markdown("## **Answer:**"))
display(Markdown(answer))

使用 Gemini 思考模型与工具

Gemini 思考模型与 Gemini 生态系统固有的工具和功能兼容。这种兼容性使它们能够与外部环境交互、执行计算代码或检索实时数据,随后将此类信息纳入其分析框架和结论陈述中。

<a name="code_execution"></a>

使用代码执行工具解决问题

此示例展示了如何使用代码执行工具来解决问题。模型将生成代码,然后执行代码以获得最终答案。

prompt = """
    What are the best ways to sort a list of n numbers from 0 to m?
    Generate and run Python code for three different sort algorithms.
    Provide the final comparison between algorithm clearly.
    Is one of them linear?
"""

code_execution_tool = types.Tool(
    code_execution=types.ToolCodeExecution()
)

interaction = client.interactions.create(
    model=MODEL_ID,
    input=prompt,
    config=types.GenerateContentConfig(
        tools=[code_execution_tool],
        thinking_config=types.ThinkingConfig(
            thinking_level=thinking_level,
        )
    ),
)

检查模型的响应,包括生成的代码和执行结果:

from IPython.display import display, HTML, Markdown

for step in interaction.steps:
    if step.type == "model_output":
        for content in step.content:
            if content.text is not None:
                display(Markdown(content.text))
    elif step.type == "code_execution":
        display(HTML(f'<pre style="background-color: #1a1a2e; color: #16c60c; padding: 10px;">{step.code}</pre>'))
        if hasattr(step, 'result') and step.result:
            display(HTML(f'<pre style="background-color: #2d2d44; color: white; padding: 10px;">{step.result}</pre>'))

<a name="google_search"></a>

使用搜索工具进行思考

搜索接地是一种通过赋予模型使用 Google 搜索查找最新信息的能力来提升响应质量的好方法。有关该功能的更多详细信息,请参阅专门指南。

from google.genai.types import Tool, GenerateContentConfig, GoogleSearch

google_search_tool = Tool(google_search=GoogleSearch())

prompt = """
    What were the major scientific breakthroughs announced last month? Use your
    critical thinking and only list what's really incredible and not just an
    overinfluated title.
"""

interaction = client.interactions.create(
    model=MODEL_ID,
    input=prompt,
    config=GenerateContentConfig(
        tools=[google_search_tool],
        thinking_config=types.ThinkingConfig(
            thinking_level=thinking_level,
            include_thoughts=True
        )
    )
)

然后你可以查看所有信息:

for step in interaction.steps:
    if step.type == "model_output":
        for content in step.content:
            if hasattr(content, 'thought') and content.thought:
                display(Markdown("## **Thoughts summary:**"))
                display(Markdown(content.text))
                print()
            elif content.text:
                display(Markdown("## **Answer:**"))
                display(Markdown(content.text))

<a name="thinking_level"></a>

思考级别参考

思考级别提供了一种简单的方法来控制推理量:

# Set thinking level
config = types.GenerateContentConfig(
    thinking_config=types.ThinkingConfig(
        thinking_level=types.ThinkingLevel.HIGH  # MINIMAL, LOW, MEDIUM, HIGH
    )
)
# @title Run this cell to set everything up if you jump directly to this section
from google.colab import userdata
from google import genai
from google.genai import types
from IPython.display import display, Markdown, HTML

client = genai.Client(api_key=userdata.get('GEMINI_API_KEY'))

# Select the Gemini 3 model

GEMINI_3_MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite"] {"allow-input":true, isTemplate: true}

你可以将思考级别设置为 minimal、low、medium 或 high(默认)。这将向模型指示它被允许进行多少思考。由于思考过程保持动态,high 并不一定意味着模型会思考很多——只是意味着它被允许根据需要尽可能多地思考。

同样,将级别设置为 low 并不意味着模型会思考很少,而是意味着它将被限制,对于更复杂的任务,它可能无法像应该的那样思考很多。

prompt = """
  Find what I'm thinking of:
    It moves, but doesn't walk, run, or swim.
    It has no fixed shape and if cut into pieces, those pieces will keep living and moving.
    It has no brain but can solve complex mazes.
"""

# Thinking levels can be either "Minimal/Low/Medium/High" or types.ThinkingLevel.MINIMAL/types.ThinkingLevel.LOW/types.ThinkingLevel.MEDIUM/types.ThinkingLevel.HIGH
thinking_level = "High" # @param ["Minimal", "Low", "Medium","High"]

interaction = client.interactions.create(
  model=GEMINI_3_MODEL_ID,
  input=prompt,
  config=types.GenerateContentConfig(
    thinking_config=types.ThinkingConfig(
      thinking_level=thinking_level,
      include_thoughts=True
    )
  )
)

for part in response.parts:
  if not part.text:
    continue
  if part.thought:
    display(Markdown("### Thought summary:"))
    display(Markdown(part.text))
    print()
  else:
    display(Markdown("### Answer:"))
    display(Markdown(part.text))
    print()

print(f"We used {response.usage_metadata.thoughts_token_count} tokens for the thinking phase and {response.usage_metadata.prompt_token_count} for the output.")

<a name="gemini3migration"></a>

旧版:从 thinking_budget 迁移到 thinking_level

如果您之前使用过 thinking_budget(generateContent 中的一个功能),以下是迁移方法:

* 如果您使用的是 thinking_budget=0 → 使用 ThinkingLevel.MINIMAL

* 如果您使用的是较低的 thinking_budget(例如 1024) → 使用 ThinkingLevel.LOW

* 如果您使用的是中等的 thinking_budget(例如 4096-8192) → 使用 ThinkingLevel.MEDIUM

* 如果您使用的是最大的 thinking_budget 或自适应(默认) → 使用 ThinkingLevel.HIGH

* 如果您使用的是动态思考 → 使用 ThinkingLevel.HIGH(模型仍会动态调整)

注意: thinking_budget 是 generateContent API 中的旧功能,仍可用于微调思考行为。有关详细信息,请参阅 generateContent notebook。

后续步骤

在 Google AI Studio 中试用 Gemini 3 和其他 Gemini 模型,并了解更多关于为思考模型编写提示词的信息。

有关 Gemini 功能的更多示例,请查看其他 Cookbook 示例。您将学习如何使用 Live API。

image./Get_started.ipynb),并灵活运用[多种工具

image](../examples/LiveAPI_plotting_and_mapping.ipynb) 或使用 Gemini 的 [空间理解能力](

image](./Spatial_understanding.ipynb) 能力。

常见问题

常见错误:1) API 密钥未设置,导致认证失败——确保在 Colab 中设置 GEMINI_API_KEY 密钥。2) 使用旧版 generateContent 代码,导致 API 不兼容——迁移到 Interactions API。3) 思考级别设置不当,如对 pro 模型禁用思考(会报错)——pro 模型不支持 minimal 或 none。4) 忽略 usage_metadata,导致成本失控——监控 thoughts_token_count。排查方法:检查 API 响应中的错误信息,确认模型 ID 正确,使用官方文档对比代码。

企业应用扩展

生产环境优化:1) 根据任务复杂度动态选择思考级别,简单任务用 minimal 降低成本,复杂任务用 high 保证质量。2) 利用流式输出(stream=True)提升用户体验,同时实时监控思考 token。3) 结合代码执行工具,让模型生成并运行代码,减少幻觉。4) 使用 Google 搜索工具获取实时信息,增强回答的时效性。5) 迁移到 Vertex AI 时,只需更改客户端初始化方式,代码无需重写。

总结

本教程面向有编程基础的开发者,深入讲解 Gemini 模型的思考模式(Thinking Mode)。通过 Jupyter Notebook 实践,你将学会使用 Interactions API 控制思考级别(minimal 到 high),理解思考 token 的计量,并掌握如何结合代码执行、Google 搜索等工具解决复杂问题。教程涵盖环境配置、API 密钥设置、多模态推理示例,以及从旧版 thinking_budget 迁移到 thinking_level 的指南,帮助你在实际项目中平衡推理深度与响应速度。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部API 与工程实践教程