Android 向け ADK エージェントをビルドする

Android 用 Agent Development Kit(ADK)ライブラリを使用すると、 高度な AI エージェントを構築して Android アプリに直接統合できます。ADK は、ローカル、ホスト型サービス、Android モバイル デバイスで実行される AI 搭載エージェントを構築するためのオープンソース デベロッパー フレームワークです。このフレームワークは Kotlin と Java プログラミング言語をサポートしているため、エージェントの構築を迅速に開始し、複雑なマルチエージェント アプリケーションにスケールアップできます。

Android 用 ADK ライブラリは、モバイル環境に合わせて調整された特別な依存関係とランタイム サポートを提供します。ML Kit GenAI API を使用して Gemini Nano でデバイス上の AI モデルを実行するエージェントを構築できるため、ネットワーク アクセスなしで機能するプライバシー重視の低レイテンシ AI エクスペリエンスを作成できます。

Android プロジェクトで ADK Kotlin を使用する

ADK Kotlin Agent 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 クイックスタートと同じです。@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 を使用したオンデバイス推論のサポートが含まれています。このアプローチにより、エージェントはネットワーク アクセスなしで実行でき、デバイス上にデータを保持できます。

オンデバイス モデルを使用するには、次のコード例に示すように、Gemini ではなく GenaiPrompt モデルを作成します。

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 モデルを使用します。

完全に動作するアクティビティとその他の例については、GitHub の ADK Kotlin の例 をご覧ください