建構適用於 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
    }

    packaging {
        resources {
            excludes += "/META-INF/{INDEX.LIST,DEPENDENCIES}"
        }
    }
}

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 快速入門導覽課程相同。HelloTimeAgent 程式碼範例包含 @Tool、@Param 和 .generatedTools() 語法,不需修改即可在 Android 上運作:

// 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
        }
    }
}

使用代理生成 UI

如果代理需要傳回結構化、互動式的使用者介面 (例如資訊卡、表單或清單),而非純文字,請使用代理到 UI (A2UI) 通訊協定。

您可以使用 Jetpack Compose A2UI 轉譯器,在應用程式的 UI 階層中,自動將 A2UI 回應轉譯為原生 Jetpack Compose 和 Material 3 元件。如要開始使用,請參閱 Jetpack Compose A2UI 指南。

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.Generation
// import com.google.mlkit.genai.prompt.GenerativeModel
// Create an ML Kit GenerativeModel for on-device inference
val generativeModel: GenerativeModel = Generation.getClient()
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 模型做為子代理,處理涉及隱私權的任務。如要進一步瞭解這個模式,請參閱 Kotlin 和 Android 適用的 ADK 網誌文章。

如需完整的 Activity 運作方式和其他範例,請參閱 GitHub 上的 ADK Kotlin 範例。