思考模式會提示模型輸出推論過程,再生成最終回覆。思考模式可提升模型函式呼叫的準確度,並有效處理數學、解決問題和其他複雜的推論工作。
啟用思考模式後,模型輸出內容會分為兩部分:
- 思考過程:模型採取的內部推理或規劃步驟。
- 回覆:為使用者生成的最終答案。
必要條件
思考模式適用於搭載 Gemini Nano V4 以上版本的裝置。您可以在任何啟用 AICore 的裝置上,透過開發人員預覽版計畫測試思考模式。
啟用思考模式
如要使用思考模式,請在 generateContentRequest 建構工具函式中,將 enableThinking 標記設為 true,選擇啟用這項功能:
val request = generateContentRequest {
text("Solve this complex riddle: ...")
enableThinking = true // Enable thinking mode for Gemini Nano V4
}
存取權注意事項
視您使用的是非串流或串流實作方式而定,ML Kit SDK 提供不同的方式,可存取模型回覆前的想法。
非串流模式
在標準非串流呼叫中,推論程序會做為完整回應的一部分傳回。您可以使用 GenerateContentResponse 物件中的 thoughtProcess 屬性存取這個程序,該屬性包含 Candidate 物件清單。
try {
val response = generativeModel.generateContent(request)
// 1. Access the main response
val answer = response.candidates.firstOrNull()?.text
println("Final Answer: $answer")
// 2. Access the separated thought process
println("Thought Process:")
response.thoughtProcess.forEach { thoughtCandidate ->
print(thoughtCandidate.text)
}
} catch (e: GenAiException) {
// Handle SDK-specific exceptions
}
串流模式
為支援即時意見回饋,StreamingCallback 介面已更新,包含 onNewThought 方法。這樣一來,應用程式就能在模型生成串流思緒區塊時處理這些區塊。
val callback = object : StreamingCallback {
override fun onNewText(additionalText: String) {
// Called for regular response chunks
print(additionalText)
}
override fun onNewThought(additionalThought: String) {
// Called for thought chunks before final text arrives
// Update a separate reasoning UI or status indicator
print("[Thinking: $additionalThought]")
}
}
try {
generativeModel.generateContent(request, callback)
} catch (e: GenAiException) {
// Handle exception
}
最佳做法
使用思考模式時,建議採用以下最佳做法:
- 使用者介面指標:產生推論步驟可能需要時間,因此在串流模式中顯示想法或「思考」指標,可向使用者表明模型正在運作,大幅提升感知效能。
- 選擇性實作:如果不想向使用者公開原始推論結果,可以忽略
thoughtProcess欄位或省略onNewThought實作。onNewThought方法具有預設的空白實作,有助於確保回溯相容性。
如需更多提示,請參閱「Gemma 的思考模式」。請注意,AICore 目前不支援多輪對話。