Gemini 2.5 シリーズのモデルは、内部の「思考プロセス」を使用して、推論能力とマルチステップの計画能力を大幅に向上させ、コーディング、高度な数学、データ分析などの複雑なタスクに非常に効果的です。
このガイドでは、Gemini API を使用して Gemini の思考機能を操作する方法について説明します。
始める前に
思考に使用するモデルが 2.5 シリーズでサポートされていることを確認します。API を詳しく調べる前に、AI Studio でこれらのモデルを調べることをおすすめします。
- AI Studio で Gemini 2.5 Flash を試す
- AI Studio で Gemini 2.5 Pro を試す
- AI Studio で Gemini 2.5 Flash-Lite プレビューを試す
思考によるコンテンツの生成
思考モデルでリクエストを開始する方法は、他のコンテンツ生成リクエストと同様です。主な違いは、次のテキスト生成の例に示すように、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 | 動的思考: モデルが思考するタイミングと思考量を決定します | 128 から 32768 |
なし: 思考を無効にできない | thinkingBudget = -1 |
2.5 Flash | 動的思考: モデルが思考するタイミングと思考量を決定します | 0 から 24576 |
thinkingBudget = 0 |
thinkingBudget = -1 |
2.5 Flash Lite | モデルは考えない | 512 から 24576 |
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
ブール値を確認することで、概要にアクセスできます。
ストリーミングなしで思考の要約を有効にして取得する方法の例を次に示します。レスポンスとともに、最終的な思考の要約が 1 つ返されます。
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("Thoughts summary:")
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)
}
}
}
}
料金
思考が有効になっている場合、レスポンスの料金は出力トークンと思考トークンの合計です。生成された思考トークンの合計数は、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 の思考の概要を慎重に分析すると役に立ちます。タスクを分解して結論に至った方法を確認して、その情報に基づいて正しい結果に修正できます。
推論にガイダンスを提供する: 特に長い出力を希望する場合は、プロンプトでガイダンスを提供して、モデルが使用する思考量を制限することをおすすめします。これにより、レスポンス用にトークン出力をより多く予約できます。
タスクの複雑さ
- 簡単なタスク(思考をオフにできる): 事実の取得や分類など、複雑な推論が不要な単純なリクエストの場合、思考は必要ありません。次に例を示します。
- 「DeepMind はどこで設立されましたか?」
- 「このメールは会議を依頼するものですか?それとも情報提供のみですか?」
- 中程度のタスク(デフォルト/ある程度の思考): 多くの一般的なリクエストでは、ある程度のステップごとの処理や深い理解が役立ちます。Gemini は、次のようなタスクで思考能力を柔軟に使用できます。
- 光合成と成長を類推する。
- 電気自動車とハイブリッド車を比較対照する。
- 難しいタスク(最大の思考能力): 複雑な数学の問題の解答やコーディング タスクなど、本当に複雑な課題の場合は、思考時間を長く設定することをおすすめします。このようなタイプのタスクでは、モデルが推論と計画の機能をすべて使用する必要があります。多くの場合、回答を提供する前に多くの内部ステップが含まれます。次に例を示します。
- AIME 2025 の問題 1 を解く: 17b が 97b の約数であるすべての整数基数 b > 9 の合計を求めます。
- ユーザー認証など、リアルタイムの株式市場データを可視化するウェブ アプリケーションの Python コードを記述します。できるだけ効率的にします。
ツールと機能を使って考える
思考モデルは、Gemini のすべてのツールと機能で動作します。これにより、モデルは外部システムとやり取りしたり、コードを実行したり、リアルタイム情報にアクセスしたりして、結果を推論と最終的なレスポンスに組み込むことができます。
検索ツールを使用すると、モデルは Google 検索をクエリして、最新情報やトレーニング データ以外の情報を検索できます。これは、最近の出来事や非常に具体的なトピックに関する質問に役立ちます。
コード実行ツールを使用すると、モデルは Python コードを生成して実行し、計算の実行、データの操作、アルゴリズムで処理するのが最適な問題の解決を行うことができます。モデルはコードの出力を受け取り、レスポンスで使用できます。
構造化出力を使用すると、Gemini が JSON で応答するように制約できます。これは、モデルの出力をアプリケーションに統合する場合に特に便利です。
関数呼び出しは、思考モデルを外部ツールや API に接続するため、適切な関数を呼び出すタイミングと提供するパラメータを推論できます。
URL コンテキストは、プロンプトの追加コンテキストとして URL をモデルに提供します。モデルは URL からコンテンツを取得し、そのコンテンツを使用してレスポンスを通知して形成できます。
思考モデルでツールを使用する例については、思考に関するクックブックをご覧ください。
次のステップ
次のような詳細な例を試すには:
- ツールを思考とともに使用する
- ストリーミングと思考
- さまざまな結果に合わせて思考予算を調整する
などについては、Thinking の Cookbook をご覧ください。
思考の範囲が、OpenAI の互換性ガイドで利用可能になりました。
Gemini 2.5 Pro、Gemini Flash 2.5、Gemini 2.5 Flash-Lite の詳細については、モデルページをご覧ください。