使用 Gemini 思考模式

Gemini 2.5 Pro Experimental 和 Gemini 2.0 Flash Thinking Experimental 是採用內部「思考過程」產生回覆的模型。這個過程有助於提升推理能力,讓他們能夠解決複雜的工作。本指南說明如何使用具備思考功能的 Gemini 模型。

使用思考模型

具備思考能力的模型可在 Google AI Studio 和 Gemini API 中使用。請注意,思考過程會顯示在 Google AI Studio 中,但不會提供為 API 輸出內容的一部分。

傳送基本要求

from google import genai

client = genai.Client(api_key="GEMINI_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-pro-exp-03-25",  # or gemini-2.0-flash-thinking-exp
    contents=prompt
)

print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_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-pro-exp-03-25",  // or gemini-2.0-flash-thinking-exp
    contents: prompt,
  });

  console.log(response.text);
}

main();
// import packages here

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
  if err != nil {
    log.Fatal(err)
  }
  defer client.Close()

  model := client.GenerativeModel("gemini-2.5-pro-exp-03-25")  // or gemini-2.0-flash-thinking-exp
  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-pro-exp-03-25:generateContent?key=$YOUR_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."
         }
       ]
     }
   ]
 }'
 ```

多輪思考對話

如要考量先前的即時通訊記錄,可以使用多輪對話。

您可以使用 SDK 建立聊天工作階段,以便管理對話狀態。

PythonJavaScript
from google import genai

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

chat = client.aio.chats.create(
    model='gemini-2.5-pro-exp-03-25',  # or gemini-2.0-flash-thinking-exp
)
response = await chat.send_message('What is your name?')
print(response.text)
response = await chat.send_message('What did you just say before this?')
print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
    const chat = ai.chats.create({
        model: 'gemini-2.5-pro-exp-03-25'  // or gemini-2.0-flash-thinking-exp
    });

    const response = await chat.sendMessage({
        message: 'What is your name?'
    });
    console.log(response.text);

    response = await chat.sendMessage({
        message: 'What did you just say before this?'
    });
    console.log(response.text);
}

main();

後續步驟