Gemini 2.5 シリーズのモデルは、内部の「思考プロセス」を使用して、推論能力とマルチステップの計画能力を大幅に向上させ、コーディング、高度な数学、データ分析などの複雑なタスクに非常に効果的です。
このガイドでは、Gemini API を使用して Gemini の思考機能を操作する方法について説明します。
始める前に
思考に使用するモデルが 2.5 シリーズでサポートされていることを確認します。API を詳しく調べる前に、AI Studio でこれらのモデルを調べることをおすすめします。
思考によるコンテンツの生成
思考モデルでリクエストを開始する方法は、他のコンテンツ生成リクエストと同様です。主な違いは、次のテキスト生成の例に示すように、model
フィールドに思考サポート付きモデルのいずれかを指定することです。
from google import genai
client = genai.Client(api_key="GOOGLE_API_KEY")
prompt = "Explain the concept of Occam's Razor and provide a simple, everyday example."
response = client.models.generate_content(
model="gemini-2.5-flash-preview-05-20",
contents=prompt
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
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-flash-preview-05-20",
contents: prompt,
});
console.log(response.text);
}
main();
// import packages here
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GOOGLE_API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-2.5-flash-preview-05-20")
resp, err := model.GenerateContent(ctx, genai.Text("Explain the concept of Occam's Razor and provide a simple, everyday example."))
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Text())
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=$GOOGLE_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."
}
]
}
]
}'
```
思考の要約(試験運用版)
思考の要約は、モデルの内部推論プロセスに関する分析情報を提供します。この機能は、モデルのアプローチを検証し、長時間のタスク中にユーザーに情報を提供する場合(特にストリーミングと組み合わせる場合)に役立ちます。
思考の要約を有効にするには、リクエスト構成で includeThoughts
を true
に設定します。次に、response
パラメータの parts
を反復処理し、thought
ブール値を確認することで、概要にアクセスできます。
ストリーミングなしで思考の要約を有効にして取得する方法の例を次に示します。レスポンスとともに、最終的な思考の要約が 1 つ返されます。
from google import genai
from google.genai import types
client = genai.Client(api_key="GOOGLE_API_KEY")
prompt = "What is the sum of the first 50 prime numbers?"
response = client.models.generate_content(
model="gemini-2.5-flash-preview-05-20",
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()
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-preview-05-20",
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();
package main
import (
"context"
"fmt"
"google.golang.org/genai"
"os"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GOOGLE_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
contents := genai.Text("What is the sum of the first 50 prime numbers?")
model := "gemini-2.5-flash-preview-05-20"
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)
}
}
}
}
次に、ストリーミングで考える方法の例を示します。この方法では、生成中にローリングの増分サマリーが返されます。
from google import genai
from google.genai import types
client = genai.Client(api_key="GOOGLE_API_KEY")
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-flash-preview-05-20",
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
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
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-flash-preview-05-20",
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();
思考予算
thinkingBudget
パラメータを使用すると、回答の生成時に使用できる思考トークンの数についてモデルにガイダンスを提供できます。一般に、トークン数が多いほど、より詳細な推論が可能になり、より複雑なタスクに取り組む際に役立ちます。thinkingBudget
を設定しないと、モデルはリクエストの複雑さに基づいて予算を動的に調整します。
thinkingBudget
は、0
~24576
の範囲の整数にする必要があります。- 思考予算を
0
に設定すると、思考が無効になります。 - プロンプトによっては、モデルがトークン予算をオーバーフローまたはアンダーフローすることがあります。
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash-preview-05-20",
contents="Provide a list of 3 famous physicists and their key contributions",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_budget=1024)
),
)
print(response.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-preview-05-20",
contents: "Provide a list of 3 famous physicists and their key contributions",
config: {
thinkingConfig: {
thinkingBudget: 1024,
},
},
});
console.log(response.text);
}
main();
package main
import (
"context"
"fmt"
"google.golang.org/genai"
"os"
)
func main() {
ctx := context.Background()
client, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GOOGLE_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
thinkingBudgetVal := int32(1024)
contents := genai.Text("Provide a list of 3 famous physicists and their key contributions")
model := "gemini-2.5-flash-preview-05-20"
resp, _ := client.Models.GenerateContent(ctx, model, contents, &genai.GenerateContentConfig{
ThinkingConfig: &genai.ThinkingConfig{
ThinkingBudget: &thinkingBudgetVal,
},
})
fmt.Println(resp.Text())
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=$GOOGLE_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
}
}
}'
料金
思考が有効になっている場合、レスポンスの料金は出力トークンと思考トークンの合計です。生成された思考トークンの合計数は、thoughtsTokenCount
フィールドから取得できます。
# ...
print("Thoughts tokens:",response.usage_metadata.thoughts_token_count)
print("Output tokens:",response.usage_metadata.candidates_token_count)
// ...
console.log(`Thoughts tokens: ${response.usageMetadata.thoughtsTokenCount}`);
console.log(`Output tokens: ${response.usageMetadata.candidatesTokenCount}`);
// ...
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 から出力されるのは要約のみですが、料金は、要約を作成するためにモデルが生成する必要のある完全な思考トークンに基づいています。
トークンの詳細については、トークンのカウント ガイドをご覧ください。
サポートされているモデル
すべてのモデル機能については、モデルの概要ページをご覧ください。
モデル | 思考の要約 | 思考予算 |
---|---|---|
Gemini 2.5 Flash | ✔️ | ✔️ |
Gemini 2.5 Pro | ✔️ | X |
ベスト プラクティス
このセクションでは、思考モデルを効率的に使用するためのガイダンスを紹介します。いつもどおり、プロンプトのガイダンスとベスト プラクティスに沿って作成することで、最良の結果が得られます。
デバッグとステアリング
推論を確認する: 思考モデルから期待どおりの回答が得られない場合、Gemini の推論プロセスを慎重に分析すると役に立ちます。タスクを分解して結論に至った方法を確認して、その情報に基づいて正しい結果に修正できます。
推論にガイダンスを提供する: 特に長い出力を希望する場合は、プロンプトでガイダンスを提供して、モデルが使用する思考量を制限することをおすすめします。これにより、レスポンス用にトークン出力をより多く予約できます。
タスクの複雑さ
- 簡単なタスク(思考をオフにできる): 事実の取得や分類など、複雑な推論が不要な単純なリクエストの場合、思考は必要ありません。次に例を示します。
- 「DeepMind はどこで設立されましたか?」
- 「このメールは、会議を希望しているのか、単に情報を提供しているのか?」
- 中程度のタスク(デフォルト/ある程度の思考): 多くの一般的なリクエストでは、ある程度のステップごとの処理や深い理解が役立ちます。Gemini は、次のようなタスクで思考機能を柔軟に使用できます。
- 光合成と成長を類推する。
- 電気自動車とハイブリッド車を比較対照する。
- 難しいタスク(最大の思考能力): 本当に複雑な課題の場合、モデルは推論と計画の機能をすべて活用する必要があります。多くの場合、回答を出す前に多くの内部ステップが関与します。次に例を示します。
- AIME 2025 の問題 1 を解く: 17b が 97b の約数であるすべての整数基数 b > 9 の合計を求めます。
- ユーザー認証など、リアルタイムの株式市場データを可視化するウェブ アプリケーションの Python コードを記述します。できるだけ効率的にします。
ツールと機能を使って考える
思考モデルは、Gemini のすべてのツールと機能で動作します。これにより、モデルは外部システムとやり取りしたり、コードを実行したり、リアルタイム情報にアクセスしたりして、結果を推論と最終的なレスポンスに組み込むことができます。
検索ツールを使用すると、モデルは Google 検索にクエリを実行して、最新情報やトレーニング データ以外の情報を検索できます。これは、最近の出来事や非常に具体的なトピックに関する質問に役立ちます。
コード実行ツールを使用すると、モデルは Python コードを生成して実行し、計算の実行、データの操作、アルゴリズムで処理するのが最適な問題の解決を行うことができます。モデルはコードの出力を受け取り、レスポンスで使用できます。
構造化出力を使用すると、Gemini が JSON で応答するように制約できます。これは、モデルの出力をアプリケーションに統合する場合に特に便利です。
関数呼び出しは、思考モデルを外部ツールや API に接続するため、適切な関数を呼び出すタイミングと、提供するパラメータを推論できます。
思考モデルでツールを使用する例については、思考に関するクックブックをご覧ください。
次のステップ
次のような詳細な例を試すには:
- ツールを思考とともに使用する
- ストリーミングと思考
- さまざまな結果に合わせて思考予算を調整する
などについては、Thinking の Cookbook をご覧ください。
思考の範囲が、OpenAI の互換性ガイドで利用可能になりました。
Gemini 2.5 Pro プレビューと Gemini Flash 2.5 Thinking の詳細については、モデルページをご覧ください。