为 Android 构建 ADK 智能体

借助 智能体开发套件 (ADK) for Android 库,您可以直接在 Android 应用中构建和集成复杂的 AI 智能体。ADK 是一个开源开发者框架,用于构建在本地、托管服务和 Android 移动设备上运行的 AI 赋能的智能体。该框架支持 Kotlin 和 Java 编程语言,可让您快速开始构建智能体,并扩缩为复杂的多智能体应用。

ADK for Android 库提供专为移动环境量身定制的专用依赖项和运行时支持。您可以使用机器学习套件 GenAI API 构建智能体,这些智能体使用 Gemini Nano 在设备端执行 AI 模型,从而让您能够打造注重隐私保护且低延迟的 AI 体验,这些体验无需网络访问即可运行。

在 Android 项目中使用 ADK Kotlin

您可以使用 ADK Kotlin 智能体 API 构建在 Android 应用中运行的 AI 智能体。您编写的智能体代码与 ADK Kotlin 入门指南中的代码相同。区别在于 Gradle 依赖项、项目配置以及在运行时调用代理的方式。

前提条件

ADK for Android 库具有以下开发要求:

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

使用代理生成界面

当您的智能体需要返回结构化、交互式界面(例如卡片、表单或列表)而非纯文本时,请使用智能体到界面 (A2UI) 协议。

您可以使用 Jetpack Compose A2UI 渲染器,在应用的界面层次结构中自动将 A2UI 响应渲染为原生 Jetpack Compose 和 Material 3 组件。如需开始使用,请参阅 Jetpack Compose A2UI 指南。

采用 Gemini Nano 的设备端模型

ADK for Android 工件支持通过机器学习套件生成式 AI 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 示例。