本頁說明如何設定 Android 專案、genai-agent 程式庫,以及建立第一個裝置端代理。
必要條件
使用 Gemini Nano 建構 Agentic Workflows 前,請確認環境符合下列需求:
- Android 版本:Android 14 (API 級別 34) 以上版本,且已註冊 AICore 開發人員預覽版計畫。
- 支援的裝置:如需支援的裝置清單和 Gemini Nano 模型版本,請參閱「自訂生成和代理裝置支援」。
- Minimum SDK:
minSdk 26以上版本。 - Kotlin:Kotlin 2.3 以上版本。
設定專案
將 genai-agent 依附元件新增至模組的 build.gradle.kts 檔案:
dependencies {
// Gemini Nano agentic workflows
implementation("com.google.mlkit:genai-agent:1.0.0-alpha1")
// Optional: Only required when defining tools using Android AppFunctions
implementation("androidx.appfunctions:appfunctions:1.0.0-alpha13")
ksp("androidx.appfunctions:appfunctions-compiler:1.0.0-alpha13")
}
建構第一個代理
代理主要由兩個部分組成:
- 代理定義:設定代理行為的指令和護欄。
- 代理執行工具:與 AICore 通訊並管理對話的執行引擎。
1. 設定代理和執行工具
下列程式碼範例說明如何使用系統指令定義代理,並初始化 AgentRunner 類別:
import com.google.mlkit.genai.agent.Agent
import com.google.mlkit.genai.agent.AgentRunner
// 1. Build the agent configuration
val agent = Agent.builder()
.setName("Assistant")
.setInstructions("You are a helpful on-device assistant.")
.build()
// 2. Initialize the runner
val runner = AgentRunner(agent)
2. 執行對話
多輪對話會使用 AgentSession 執行個體,保留各輪對話的記錄。將提示文字包裝在 Content 物件中,並收集串流回覆:
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.google.mlkit.genai.agent.textTokens
import com.google.mlkit.genai.prompt.Content
import kotlinx.coroutines.launch
// Create or retrieve a conversation session
val session = runner.getOrCreateSession("chat_session")
val prompt = Content.builder()
.text("Hello! Can you help me organize my day?")
.build()
// Collect streamed tokens in a coroutine
lifecycleScope.launch {
session.runAsync(prompt)
.textTokens()
.collect { token ->
Log.d("Agent", token)
}
}
如果是一次性查詢,不需要保留對話記錄,可以直接呼叫 runner.runSingleTurnAsync(prompt) 方法:
lifecycleScope.launch {
runner.runSingleTurnAsync(prompt)
.textTokens()
.collect { token ->
Log.d("Agent", token)
}
}
3. 清除所用資源
AgentRunner 類別會實作 AutoCloseable 介面。當 ViewModel 或 Activity 元件遭到刪除時,請關閉執行工具,釋出有效活動時段並取消背景協同程式:
runner.close()
後續步驟
- 運用工具新增功能:讓代理能使用 Android AppFunctions 執行動作或查詢應用程式資料。請參閱「定義工具」。
- 在旋轉時保留工作階段:請參閱「管理工作階段和生命週期」,瞭解如何在設定變更時,保留
ViewModel類別中的AgentSession執行個體。 - 連結至 Compose:在串流事件和 UI 整合中,串流事件並算繪互動式聊天泡泡。