Gemini 思考

Gemini 2.5 系列模型會運用內部「思考過程」,大幅提升推論和多步驟規劃能力,因此非常適合處理複雜工作,例如程式設計、高等數學和資料分析。

本指南說明如何使用 Gemini API,運用 Gemini 的思考能力。

事前準備

請務必使用支援的 2.5 系列模型進行思考。 建議您先在 AI Studio 中探索這些模型,再深入瞭解 API:

生成內容時進行思考

使用思考模型發起要求,與任何其他內容生成要求類似。主要差異在於 model 欄位中指定了支援思考的其中一個模型,如下列文字生成範例所示:

Python

from google import genai

client = genai.Client()
prompt = "Explain the concept of Occam's Razor and provide a simple, everyday example."
response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents=prompt
)

print(response.text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const prompt = "Explain the concept of Occam's Razor and provide a simple, everyday example.";

  const response = await ai.models.generateContent({
    model: "gemini-2.5-pro",
    contents: prompt,
  });

  console.log(response.text);
}

main();

Go

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "google.golang.org/genai"
)

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  prompt := "Explain the concept of Occam's Razor and provide a simple, everyday example."
  model := "gemini-2.5-pro"

  resp, _ := client.Models.GenerateContent(ctx, model, genai.Text(prompt), nil)

  fmt.Println(resp.Text())
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent" \
 -H "x-goog-api-key: $GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -X POST \
 -d '{
   "contents": [
     {
       "parts": [
         {
           "text": "Explain the concept of Occam\'s Razor and provide a simple, everyday example."
         }
       ]
     }
   ]
 }'
 ```

思考預算

thinkingBudget 參數會引導模型在生成回覆時,使用適當數量的思考詞元。詞元數量越多,通常就代表推理更精細,有助於處理更複雜的工作。如果延遲時間較為重要,請使用較低的預算,或將 thinkingBudget 設為 0,停用思考功能。將 thinkingBudget 設為 -1 可啟用動態思考,也就是模型會根據要求的複雜度調整預算。

thinkingBudget支援 Gemini 2.5 Flash、2.5 Pro 和 2.5 Flash-Lite。視提示而定,模型可能會超出或未用完權杖預算。

以下是各模型類型的 thinkingBudget 設定詳細資料。

模型 預設設定
(未設定思考預算)
範圍 停用思考功能 開啟動態思考
2.5 Pro 動態思考:模型會決定思考的時間和程度 12832768 不適用:無法停用思考功能 thinkingBudget = -1
2.5 Flash 動態思考:模型會決定思考的時間和程度 024576 thinkingBudget = 0 thinkingBudget = -1
2.5 Flash Lite 模型不會思考 51224576 thinkingBudget = 0 thinkingBudget = -1

Python

from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents="Provide a list of 3 famous physicists and their key contributions",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_budget=1024)
        # Turn off thinking:
        # thinking_config=types.ThinkingConfig(thinking_budget=0)
        # Turn on dynamic thinking:
        # thinking_config=types.ThinkingConfig(thinking_budget=-1)
    ),
)

print(response.text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-pro",
    contents: "Provide a list of 3 famous physicists and their key contributions",
    config: {
      thinkingConfig: {
        thinkingBudget: 1024,
        // Turn off thinking:
        // thinkingBudget: 0
        // Turn on dynamic thinking:
        // thinkingBudget: -1
      },
    },
  });

  console.log(response.text);
}

main();

Go

package main

import (
  "context"
  "fmt"
  "google.golang.org/genai"
  "os"
)

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  thinkingBudgetVal := int32(1024)

  contents := genai.Text("Provide a list of 3 famous physicists and their key contributions")
  model := "gemini-2.5-pro"
  resp, _ := client.Models.GenerateContent(ctx, model, contents, &genai.GenerateContentConfig{
    ThinkingConfig: &genai.ThinkingConfig{
      ThinkingBudget: &thinkingBudgetVal,
      // Turn off thinking:
      // ThinkingBudget: int32(0),
      // Turn on dynamic thinking:
      // ThinkingBudget: int32(-1),
    },
  })

fmt.Println(resp.Text())
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
  "contents": [
    {
      "parts": [
        {
          "text": "Provide a list of 3 famous physicists and their key contributions"
        }
      ]
    }
  ],
  "generationConfig": {
    "thinkingConfig": {
          "thinkingBudget": 1024
          # Thinking off:
          # "thinkingBudget": 0
          # Turn on dynamic thinking:
          # "thinkingBudget": -1
    }
  }
}'

想法摘要

想法摘要是模型原始想法的綜合版本,可深入瞭解模型的內部推理過程。請注意,思考預算適用於模型的原始想法,而非想法摘要。

如要啟用想法摘要,請在要求設定中將 includeThoughts 設為 true。然後透過疊代 response 參數的 parts,並檢查 thought 布林值,即可存取摘要。

以下範例說明如何啟用及擷取想法摘要 (不含串流),並在回應中傳回單一最終想法摘要:

Python

from google import genai
from google.genai import types

client = genai.Client()
prompt = "What is the sum of the first 50 prime numbers?"
response = client.models.generate_content(
  model="gemini-2.5-pro",
  contents=prompt,
  config=types.GenerateContentConfig(
    thinking_config=types.ThinkingConfig(
      include_thoughts=True
    )
  )
)

for part in response.candidates[0].content.parts:
  if not part.text:
    continue
  if part.thought:
    print("Thought summary:")
    print(part.text)
    print()
  else:
    print("Answer:")
    print(part.text)
    print()

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-pro",
    contents: "What is the sum of the first 50 prime numbers?",
    config: {
      thinkingConfig: {
        includeThoughts: true,
      },
    },
  });

  for (const part of response.candidates[0].content.parts) {
    if (!part.text) {
      continue;
    }
    else if (part.thought) {
      console.log("Thoughts summary:");
      console.log(part.text);
    }
    else {
      console.log("Answer:");
      console.log(part.text);
    }
  }
}

main();

Go

package main

import (
  "context"
  "fmt"
  "google.golang.org/genai"
  "os"
)

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  contents := genai.Text("What is the sum of the first 50 prime numbers?")
  model := "gemini-2.5-pro"
  resp, _ := client.Models.GenerateContent(ctx, model, contents, &genai.GenerateContentConfig{
    ThinkingConfig: &genai.ThinkingConfig{
      IncludeThoughts: true,
    },
  })

  for _, part := range resp.Candidates[0].Content.Parts {
    if part.Text != "" {
      if part.Thought {
        fmt.Println("Thoughts Summary:")
        fmt.Println(part.Text)
      } else {
        fmt.Println("Answer:")
        fmt.Println(part.Text)
      }
    }
  }
}

以下是使用串流思考的範例,會在生成期間傳回滾動式增量摘要:

Python

from google import genai
from google.genai import types

client = genai.Client()

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 chunk in client.models.generate_content_stream(
    model="gemini-2.5-pro",
    contents=prompt,
    config=types.GenerateContentConfig(
      thinking_config=types.ThinkingConfig(
        include_thoughts=True
      )
    )
):
  for part in chunk.candidates[0].content.parts:
    if not part.text:
      continue
    elif part.thought:
      if not thoughts:
        print("Thoughts summary:")
      print(part.text)
      thoughts += part.text
    else:
      if not answer:
        print("Answer:")
      print(part.text)
      answer += part.text

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

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

let thoughts = "";
let answer = "";

async function main() {
  const response = await ai.models.generateContentStream({
    model: "gemini-2.5-pro",
    contents: prompt,
    config: {
      thinkingConfig: {
        includeThoughts: true,
      },
    },
  });

  for await (const chunk of response) {
    for (const part of chunk.candidates[0].content.parts) {
      if (!part.text) {
        continue;
      } else if (part.thought) {
        if (!thoughts) {
          console.log("Thoughts summary:");
        }
        console.log(part.text);
        thoughts = thoughts + part.text;
      } else {
        if (!answer) {
          console.log("Answer:");
        }
        console.log(part.text);
        answer = answer + part.text;
      }
    }
  }
}

await main();

Go

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "google.golang.org/genai"
)

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

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  contents := genai.Text(prompt)
  model := "gemini-2.5-pro"

  resp := client.Models.GenerateContentStream(ctx, model, contents, &genai.GenerateContentConfig{
    ThinkingConfig: &genai.ThinkingConfig{
      IncludeThoughts: true,
    },
  })

  for chunk := range resp {
    for _, part := range chunk.Candidates[0].Content.Parts {
      if len(part.Text) == 0 {
        continue
      }

      if part.Thought {
        fmt.Printf("Thought: %s\n", part.Text)
      } else {
        fmt.Printf("Answer: %s\n", part.Text)
      }
    }
  }
}

思想簽名

由於標準 Gemini API 文字和內容生成呼叫是無狀態的,因此在多輪互動 (例如即時通訊) 中使用思考功能時,模型無法存取先前輪次的思考內容。

您可以使用想法簽章來維護想法脈絡,這是模型內部思考過程的加密表示法。啟用思考和函式呼叫功能後,模型會在回應物件中傳回思考簽章。為確保模型在多輪對話中維持脈絡,您必須在後續要求中將思維簽章提供給模型。

在下列情況下,你會收到想法簽章:

  • 已啟用思考功能並生成想法。
  • 要求內含函式宣告

如需透過函式呼叫思考的範例,請參閱「函式呼叫」頁面。

使用函式呼叫時,請注意以下其他用量限制:

  • 簽章會與其他部分一起傳回,例如函式呼叫或文字部分。在後續回合中,將完整回應 (包括所有部分) 傳回模型。
  • 請勿將簽章與其他部分串連在一起。
  • 請勿將有簽名的部分與沒有簽名的部分合併。

定價

開啟思考功能後,回覆價格為輸出權杖和思考權杖的總和。您可以從 thoughtsTokenCount 欄位取得產生的思考權杖總數。

Python

# ...
print("Thoughts tokens:",response.usage_metadata.thoughts_token_count)
print("Output tokens:",response.usage_metadata.candidates_token_count)

JavaScript

// ...
console.log(`Thoughts tokens: ${response.usageMetadata.thoughtsTokenCount}`);
console.log(`Output tokens: ${response.usageMetadata.candidatesTokenCount}`);

Go

// ...
usageMetadata, err := json.MarshalIndent(response.UsageMetadata, "", "  ")
if err != nil {
  log.Fatal(err)
}
fmt.Println("Thoughts tokens:", string(usageMetadata.thoughts_token_count))
fmt.Println("Output tokens:", string(usageMetadata.candidates_token_count))

思考模型會生成完整想法,提升最終回覆的品質,然後輸出摘要,深入瞭解思考過程。因此,即使 API 只會輸出摘要,但計費依據仍是模型生成摘要時所需的所有思考代幣。

如要進一步瞭解權杖,請參閱權杖計數指南。

支援的模型

所有 2.5 系列機型都支援思考功能。您可以在模型總覽頁面查看所有模型功能。

最佳做法

本節提供一些指引,說明如何有效運用思考模型。一如往常,請遵循提示指南和最佳做法,獲得最佳結果。

偵錯和導向

  • 查看推理過程:如果思考模型未提供預期回覆,請仔細分析 Gemini 的思考摘要。你可以查看 AI 如何分解工作並得出結論,然後根據這些資訊修正結果。

  • 在推理過程中提供指引:如果您希望輸出內容特別長,不妨在提示中提供指引,限制模型思考量。這樣一來,就能為回覆保留更多權杖輸出。

工作複雜度

  • 簡單工作 (可關閉思考):對於不需要複雜推理的簡單要求 (例如事實擷取或分類),不需要思考。例如:
    • 「DeepMind 是在哪裡成立的?」
    • 「這封電子郵件是要安排會議,還是只是提供資訊?」
  • 中等工作 (預設/需要思考):許多常見要求需要逐步處理或深入理解。Gemini 可彈性運用思考能力處理以下工作:
    • 將光合作用和成長過程做類比。
    • 比較電動車和油電混合車的異同。
  • 困難任務 (最高思維能力):如要解決複雜的數學問題或編碼工作等高難度挑戰,建議設定較高的思維預算。這類工作需要模型充分運用推理和規劃能力,通常要經過許多內部步驟,才能提供答案。例如:
    • 解決 2025 年 AIME 的問題 1:找出所有大於 9 的整數底數 b,使 17b 為 97b 的除數,並計算這些底數的總和。
    • 編寫 Python 程式碼,建立可顯示即時股市資料的網路應用程式,包括使用者驗證。盡可能提高效率。

運用工具和功能思考

思考模型可搭配所有 Gemini 工具和功能使用。模型可藉此與外部系統互動、執行程式碼或存取即時資訊,並將結果納入推理和最終回覆。

  • 搜尋工具可讓模型查詢 Google 搜尋,尋找最新資訊或訓練資料以外的資訊。這項功能很適合用來詢問近期事件或非常具體的主題。

  • 程式碼執行工具可讓模型生成及執行 Python 程式碼,進行計算、操控資料,或解決最適合以演算法處理的問題。模型會收到程式碼的輸出內容,並在回覆中使用。

  • 透過結構化輸出,您可以限制 Gemini 以 JSON 格式回覆。這項功能特別適合將模型輸出內容整合至應用程式。

  • 函式呼叫功能可將思考模型連結至外部工具和 API,因此模型可以判斷何時呼叫正確的函式,以及要提供哪些參數。

  • 網址內容會提供網址給模型,做為提示的額外內容。模型接著會從網址擷取內容,並根據這些內容提供回覆。

您可以在思考教戰手冊中,查看使用工具和思考模型的範例。

後續步驟

  • 如要瞭解更多深入範例,例如:

    • 運用工具輔助思考
    • 串流播放並思考
    • 根據不同結果調整思考預算

    歡迎試用思考食譜

  • 您現在可以在 OpenAI 相容性指南中查看思維涵蓋範圍。

  • 如要進一步瞭解 Gemini 2.5 Pro、Gemini Flash 2.5 和 Gemini 2.5 Flash-Lite,請前往模型頁面