建構適用於 Android 的 ADK 代理

Android 專用的 Agent Development Kit (ADK) 程式庫可讓您直接在 Android 應用程式中建構及整合精密的 AI 代理。ADK 是開放原始碼開發人員框架,可用於建構 AI 輔助代理,並在本地、代管服務和 Android 行動裝置上執行。這個框架支援 Kotlin 和 Java 程式設計語言,可讓您快速開始建構代理程式,並擴展為複雜的多代理應用程式。

Android 適用的 ADK 程式庫提供專屬依附元件和執行階段支援,專為行動環境量身打造。您可以使用 ML Kit GenAI API,建構在裝置端執行 Gemini Nano AI 模型的代理程式,打造注重隱私權且低延遲的 AI 體驗,即使沒有網路連線也能運作。

在 Android 專案中使用 ADK Kotlin

您可以使用 ADK Kotlin 代理程式 API,建構在 Android 應用程式中執行的 AI 代理程式。您編寫的代理程式碼與 ADK Kotlin「開始使用」指南中的程式碼相同。差異在於 Gradle 依附元件、專案設定,以及您在執行階段叫用代理程式的方式。

必要條件

Android 適用的 ADK 程式庫須符合下列開發需求:

  • Android Studio
  • Android SDK (compileSdk 34 以上版本,minSdk 24 以上版本)

設定 Android 專案

在 Android 專案的 build.gradle.kts 中,新增 ADK Android 依附元件和 KSP 註解處理工具:

plugins {
    id("com.android.application")
    kotlin("android")
    id("com.google.devtools.ksp") version "2.1.20-2.0.1"
}

android {
    namespace = "com.example.agent"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.example.agent"
        minSdk = 24
        targetSdk = 34
    }
}

dependencies {
    implementation("com.google.adk:google-adk-kotlin-core-android:0.1.0")
    ksp("com.google.adk:google-adk-kotlin-processor:0.1.0")
}

kotlin {
    jvmToolchain(17)
}

定義代理

代理程式碼與 ADK Kotlin 快速入門導覽課程相同。在 Android 上,使用 @Tool@Param.generatedTools() 語法的 HelloTimeAgent 程式碼範例可直接運作,不需修改:

package com.example.agent
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.models.Gemini
class TimeService {
    /** Mock tool implementation */
    @Tool
    fun getCurrentTime(
        @Param("Name of the city to get the time for") city: String
    ): Map<String, String> {
        return mapOf("city" to city, "time" to "The time is 10:30am.")
    }
}
object HelloTimeAgent {
    @JvmField
    val rootAgent = LlmAgent(
        name = "hello_time_agent",
        description = "Tells the current time in a specified city.",
        model = Gemini(
            name = "gemini-flash-latest",
            apiKey = System.getenv("GOOGLE_API_KEY")
                ?: error("GOOGLE_API_KEY environment variable not set."),
        ),
        instruction = Instruction(
            "You are a helpful assistant that tells the current time in a city. "
                + "Use the 'getCurrentTime' tool for this purpose."
        ),
        tools = TimeService().generatedTools(),
    )
}

從 Android 應用程式執行代理程式

在 Android 裝置上,使用 InMemoryRunner 叫用代理程式,並從協同程式收集回應,如以下程式碼範例所示:

import com.google.adk.kt.runners.InMemoryRunner
import com.google.adk.kt.sessions.InMemorySessionService
import com.google.adk.kt.types.Content
import com.google.adk.kt.types.Part
import com.google.adk.kt.types.Role
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
// Create a runner and session service
val sessionService = InMemorySessionService()
val runner = InMemoryRunner(
    agent = HelloTimeAgent.rootAgent,
    sessionService = sessionService,
)
// Call the agent from a coroutine (e.g. in a ViewModel or Activity)
scope.launch {
    runner.runAsync(
        userId = "user-123",
        sessionId = "session-123",
        newMessage = Content(
            role = Role.USER,
            parts = listOf(Part(text = "What time is it in New York?")),
        ),
    ).collect { event ->
        val text = event.content?.parts?.firstOrNull()?.text
        if (!text.isNullOrBlank()) {
            // Update your UI with the agent's response
        }
    }
}

搭載 Gemini Nano 的裝置端模型

Android 適用的 ADK 構件支援使用 ML Kit GenAI API,透過 Gemini Nano 執行裝置端推論。這個方法可讓代理程式在沒有網路連線的情況下執行,並將資料保留在裝置上。

如要使用裝置端模型,請建立 GenaiPrompt 模型,而非 Gemini,如以下程式碼範例所示:

import com.google.adk.kt.models.mlkit.GenaiPrompt
import com.google.mlkit.genai.prompt.GenerativeModel
// Create an ML Kit GenerativeModel for on-device inference
val generativeModel: GenerativeModel = // ... initialize using ML Kit
val onDeviceModel = GenaiPrompt.create(
    generativeModel = generativeModel,
    name = "gemini-nano",
)
val agent = LlmAgent(
    name = "on_device_agent",
    model = onDeviceModel,
    instruction = Instruction("You are a helpful assistant."),
)

您也可以在多代理程式系統中結合雲端和裝置端模型:將雲端 Gemini 用於根自動化調度管理工具,並將裝置端 GenaiPrompt 模型用於處理隱私權敏感工作的子代理程式。

如需完整的運作中 Activity 和更多範例,請參閱 GitHub 上的 ADK Kotlin 範例。