开始使用 Agentic Workflows

本页面介绍了如何设置 Android 项目、配置 genai-agent 库以及创建首个设备端智能体。

前提条件

在使用 Gemini Nano 构建 Agentic Workflows 之前,请确保您的环境满足以下要求:

配置您的项目

将 genai-agent 依赖项添加到模块的 build.gradle.kts 文件中:

dependencies {
    // Gemini Nano agentic workflows
    implementation("com.google.mlkit:genai-agent:1.0.0-alpha1")

    // Optional: Only required when defining tools using Android AppFunctions
    implementation("androidx.appfunctions:appfunctions:1.0.0-alpha13")
    ksp("androidx.appfunctions:appfunctions-compiler:1.0.0-alpha13")
}

构建您的首个智能体

智能体有两个主要组成部分:

  • 智能体定义:用于配置智能体行为的指令和护栏。
  • 智能体运行程序:与 AICore 通信并管理对话的执行引擎。

1. 配置智能体和运行程序

以下代码示例展示了如何使用系统指令定义代理并初始化 AgentRunner 类:

import com.google.mlkit.genai.agent.Agent
import com.google.mlkit.genai.agent.AgentRunner

// 1. Build the agent configuration
val agent = Agent.builder()
    .setName("Assistant")
    .setInstructions("You are a helpful on-device assistant.")
    .build()

// 2. Initialize the runner
val runner = AgentRunner(agent)

2. 运行对话

多轮对话使用 AgentSession 实例在多轮对话中保留对话记录。将提示文本封装在 Content 对象中,并收集流式传输的回答:

import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.google.mlkit.genai.agent.textTokens
import com.google.mlkit.genai.prompt.Content
import kotlinx.coroutines.launch

// Create or retrieve a conversation session
val session = runner.getOrCreateSession("chat_session")

val prompt = Content.builder()
    .text("Hello! Can you help me organize my day?")
    .build()

// Collect streamed tokens in a coroutine
lifecycleScope.launch {
    session.runAsync(prompt)
        .textTokens()
        .collect { token ->
            Log.d("Agent", token)
        }
}

对于不需要保留对话记录的一次性查询,您可以直接调用 runner.runSingleTurnAsync(prompt) 方法:

lifecycleScope.launch {
    runner.runSingleTurnAsync(prompt)
        .textTokens()
        .collect { token ->
            Log.d("Agent", token)
        }
}

3. 清理资源

AgentRunner 类实现了 AutoCloseable 接口。当 ViewModel 或 Activity 组件被销毁时,请关闭运行程序以释放活跃会话并取消后台协程:

runner.close()

后续步骤

  • 利用工具添加功能:让智能体能够使用 Android AppFunctions 执行操作或查询应用数据。请参阅定义工具。
  • 在旋转屏幕时保留会话:在管理会话和生命周期中,了解如何在配置发生更改时保留 ViewModel 类中的 AgentSession 实例。
  • 连接到 Compose:在流式传输事件和界面集成中流式传输事件并呈现互动式聊天气泡。