为 Android 构建 ADK 智能体

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

Android 版 ADK 库提供专门针对移动环境量身定制的依赖项和运行时支持。您可以使用机器学习套件 GenAI API 构建在设备端使用 Gemini Nano 执行 AI 模型的代理,从而打造注重隐私保护且低延迟的 AI 体验,即使没有网络访问权限也能正常运行。

在 Android 项目中使用 ADK Kotlin

您可以使用 ADK Kotlin 代理 API 构建在 Android 应用内运行的 AI 代理。您编写的代理代码与 ADK Kotlin Get started 指南中的代码相同。不同之处在于 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 快速入门中的代码完全相同。包含 @Tool@Param.generatedTools() 语法的 HelloTimeAgent 代码示例无需修改即可在 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
        }
    }
}

搭载 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 示例。