UI 工具

adk-ui crate 允许 AI 智能体通过工具调用动态生成丰富的用户界面。智能体可以渲染表单、卡片、警告、表格、图表等——所有这些都通过类型安全的 Rust API 实现,该 API 序列化为 JSON 以供前端使用。

您将构建什么

ADK UI 智能体

关键概念:

  • 表单 - 使用各种字段类型收集用户输入
  • 卡片 - 显示带操作按钮的信息
  • 表格 - 以行/列形式展示结构化数据
  • 图表 - 通过柱状图、折线图、面积图、饼图可视化数据
  • 警告 - 显示通知和状态消息
  • 模态框 - 确认对话框和聚焦式交互
  • 提示 - 简短的状态通知

示例:分析仪表盘

ADK UI 分析

示例:注册表单

ADK UI 注册


工作原理

┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 1: User requests something                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   User: "I want to register for an account"                                 │
│                                                                             │
│                              ↓                                              │
│                                                                             │
│   ┌──────────────────────────────────────┐                                  │
│   │         AI AGENT (LLM)              │                                  │
│   │  "I should show a registration form" │                                  │
│   └──────────────────────────────────────┘                                  │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 2: Agent calls render_form tool                                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   📞 Tool Call: render_form({                                               │
│     title: "Registration",                                                  │
│     fields: [                                                               │
│       {name: "email", type: "email"},                                       │
│       {name: "password", type: "password"}                                  │
│     ]                                                                       │
│   })                                                                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 3: Frontend renders the form                                           │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌─────────────────────────────────────────────────┐                       │
│   │  📋 Registration                               │                       │
│   │  ────────────────────────────────────────────  │                       │
│   │  Email:    [________________________]          │                       │
│   │  Password: [________________________]          │                       │
│   │                                                │                       │
│   │  [           Register           ]              │                       │
│   └─────────────────────────────────────────────────┘                       │
│                                                                             │
│   ✅ User sees an interactive form, fills it out, clicks Register           │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 4: Form submission sent back to agent                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   📩 Event: {                                                               │
│     type: "form_submit",                                                    │
│     data: { email: "user@example.com", password: "***" }                    │
│   }                                                                         │
│                                                                             │
│   Agent: "Great! I'll process your registration and show a success alert"  │
│                                                                             │
│   📞 Tool Call: render_alert({                                              │
│     title: "Registration Complete!",                                        │
│     variant: "success"                                                      │
│   })                                                                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

概述

UI 工具允许 agents 进行以下操作:

  • 通过支持 textarea 的动态表单收集用户输入
  • 使用 cards、alerts 和 notifications 显示信息
  • 以 tables 和交互式 charts (Recharts) 形式呈现数据
  • 显示进度和加载状态 (spinner, skeleton)
  • 创建包含多个 components 的 dashboard 布局
  • 通过 modals 请求用户确认
  • 显示 toast notifications 以获取状态更新

快速开始

添加到您的 Cargo.toml

[dependencies]
adk-rust = { version = "0.2.0", features = ["ui"] }
# Or use individual crates:
adk-ui = "0.2.0"
adk-agent = "0.2.0"
adk-model = "0.2.0"

基本用法

use adk_rust::prelude::*;
use adk_rust::ui::UiToolset;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = Arc::new(GeminiModel::from_env("gemini-2.0-flash")?);

    // Get all 10 UI tools
    let ui_tools = UiToolset::all_tools();

    // Create AI agent with UI tools
    let mut builder = LlmAgentBuilder::new("ui_agent")
        .model(model)
        .instruction(r#"
            You are a helpful assistant that uses UI components to interact with users.
            Use render_form for collecting information.
            Use render_card for displaying results.
            Use render_alert for notifications.
            Use render_modal for confirmation dialogs.
            Use render_toast for brief status messages.
        "#);

    for tool in ui_tools {
        builder = builder.tool(tool);
    }

    let agent = builder.build()?;
    Ok(())
}

可用工具

render_form

渲染交互式表单以收集用户输入。

{
  "title": "Registration Form",
  "description": "Create your account",
  "fields": [
    {"name": "username", "label": "Username", "type": "text", "required": true},
    {"name": "email", "label": "Email", "type": "email", "required": true},
    {"name": "password", "label": "Password", "type": "password", "required": true},
    {"name": "newsletter", "label": "Subscribe to newsletter", "type": "switch"}
  ],
  "submit_label": "Register"
}

渲染结果:

┌─────────────────────────────────────────────────┐
│  📋 Registration Form                          │
│  Create your account                           │
│  ─────────────────────────────────────────────  │
│                                                │
│  Username *                                    │
│  ┌─────────────────────────────────────────┐   │
│  │                                         │   │
│  └─────────────────────────────────────────┘   │
│                                                │
│  Email *                                       │
│  ┌─────────────────────────────────────────┐   │
│  │                                         │   │
│  └─────────────────────────────────────────┘   │
│                                                │
│  Password *                                    │
│  ┌─────────────────────────────────────────┐   │
│  │ ••••••••                                │   │
│  └─────────────────────────────────────────┘   │
│                                                │
│  Subscribe to newsletter  [○]                  │
│                                                │
│  ┌─────────────────────────────────────────┐   │
│  │             Register                    │   │
│  └─────────────────────────────────────────┘   │
│                                                │
└─────────────────────────────────────────────────┘

字段类型: text, email, password, number, date, select, multiselect, switch, slider, textarea

render_card

显示带有可选操作按钮的信息卡片。

{
  "title": "Order Confirmed",
  "description": "Order #12345",
  "content": "Your order has been placed successfully. Expected delivery: Dec 15, 2025.",
  "actions": [
    {"label": "Track Order", "action_id": "track", "variant": "primary"},
    {"label": "Cancel", "action_id": "cancel", "variant": "danger"}
  ]
}

按钮变体: primary, secondary, danger, ghost, outline

render_alert

显示通知和状态消息。

{
  "title": "Payment Successful",
  "description": "Your payment of $99.00 has been processed.",
  "variant": "success"
}

变体: info, success, warning, error

render_confirm

在操作前请求用户确认。

{
  "title": "Delete Account",
  "message": "Are you sure you want to delete your account? This action cannot be undone.",
  "confirm_label": "Delete",
  "cancel_label": "Keep Account",
  "variant": "danger"
}

render_table

显示表格数据。

{
  "title": "Recent Orders",
  "columns": [
    {"header": "Order ID", "accessor_key": "id"},
    {"header": "Date", "accessor_key": "date"},
    {"header": "Amount", "accessor_key": "amount"},
    {"header": "Status", "accessor_key": "status"}
  ],
  "data": [
    {"id": "#12345", "date": "2025-12-10", "amount": "$99.00", "status": "Delivered"},
    {"id": "#12346", "date": "2025-12-11", "amount": "$149.00", "status": "Shipped"}
  ]
}

render_chart

创建数据可视化。

{
  "title": "Monthly Sales",
  "chart_type": "bar",
  "x_key": "month",
  "y_keys": ["revenue", "profit"],
  "data": [
    {"month": "Jan", "revenue": 4000, "profit": 2400},
    {"month": "Feb", "revenue": 3000, "profit": 1398},
    {"month": "Mar", "revenue": 5000, "profit": 3800}
  ]
}

图表类型: bar, line, area, pie

render_progress

显示带可选步骤的任务进度。

{
  "title": "Installing Dependencies",
  "value": 65,
  "description": "Installing package 13 of 20...",
  "steps": [
    {"label": "Download", "completed": true},
    {"label": "Extract", "completed": true},
    {"label": "Install", "current": true},
    {"label": "Configure", "completed": false}
  ]
}

render_layout

创建具有多个部分的仪表盘布局。

{
  "title": "System Status",
  "description": "Current system health overview",
  "sections": [
    {
      "title": "Services",
      "type": "stats",
      "stats": [
        {"label": "API Server", "value": "Healthy", "status": "operational"},
        {"label": "Database", "value": "Degraded", "status": "warning"},
        {"label": "Cache", "value": "Down", "status": "error"}
      ]
    },
    {
      "title": "Recent Errors",
      "type": "table",
      "columns": [{"header": "Time", "key": "time"}, {"header": "Error", "key": "error"}],
      "rows": [{"time": "10:30", "error": "Connection timeout"}]
    }
  ]
}

部分类型: stats, table, chart, alert, text

render_modal

显示模态对话框以进行确认或聚焦交互。

{
  "title": "Confirm Deletion",
  "message": "Are you sure you want to delete this item? This action cannot be undone.",
  "size": "medium",
  "closable": true,
  "confirm_label": "Delete",
  "cancel_label": "Cancel",
  "confirm_action": "delete_confirmed"
}

尺寸: small, medium, large, full

render_toast

显示简短的 Toast 通知以更新状态。

{
  "message": "Settings saved successfully",
  "variant": "success",
  "duration": 5000,
  "dismissible": true
}

变体: info, success, warning, error

筛选工具

只选择你的 agent 所需的工具:

let toolset = UiToolset::new()
    .without_chart()      // 禁用图表
    .without_table()      // 禁用表格
    .without_progress()   // 禁用进度条
    .without_modal()      // 禁用模态框
    .without_toast();     // 禁用提示框

// 或者只使用表单
let forms_only = UiToolset::forms_only();

处理 UI 事件

当用户与渲染的 UI 交互(提交表单、点击按钮)时,事件会发送回 agent:

use adk_ui::{UiEvent, UiEventType};

// UiEvent 结构
pub struct UiEvent {
    pub event_type: UiEventType,  // FormSubmit, ButtonClick, InputChange
    pub action_id: Option<String>,
    pub data: Option<HashMap<String, Value>>,
}

// 转换为 agent 的消息
let message = ui_event.to_message();

流式 UI 更新

对于实时 UI 更新,使用 UiUpdate 按 ID 修补组件:

use adk_ui::{UiUpdate, UiOperation};

let update = UiUpdate {
    target_id: "progress-bar".to_string(),
    operation: UiOperation::Patch,
    payload: Some(Component::Progress(Progress {
        id: Some("progress-bar".to_string()),
        value: 75,
        label: Some("75%".to_string()),
    })),
};

操作ReplacePatchAppendRemove

组件 Schema

所有 28 种组件类型都支持用于流式更新的可选 id 字段:

原子组件:Text, Button, Icon, Image, Badge 输入组件:TextInput, NumberInput, Select, MultiSelect, Switch, DateInput, Slider, Textarea 布局组件:Stack, Grid, Card, Container, Divider, Tabs 数据组件:Table, List, KeyValue, CodeBlock 可视化组件:Chart (通过 Recharts 实现的柱状图、折线图、面积图、饼图) 反馈组件:Alert, Progress, Toast, Modal, Spinner, Skeleton

React 客户端

提供了参考 React 实现:

cd official_docs_examples/tools/ui_test

# 启动 UI 服务器
cargo run --bin ui_server

# 在另一个终端中,启动 React 客户端
cd ui_react_client
npm install && npm run dev -- --host

React 客户端包括:

  • 与 Rust schema 匹配的 TypeScript 类型
  • 所有 28 种组件类型的渲染器
  • 用于交互式图表的 Recharts 集成
  • Markdown 渲染支持
  • 暗模式支持
  • 表单提交处理
  • 模态框和提示框组件

架构

┌─────────────┐                    ┌─────────────┐
│   Agent     │ ──[render_* tool]──│ UiResponse  │
│  (LLM)      │                    │   (JSON)    │
└─────────────┘                    └──────┬──────┘
       ▲                                  │
       │                                  │ SSE
       │                                  ▼
       │                           ┌─────────────┐
       └────── UiEvent ◄───────────│   Client    │
              (用户操作)             │  (React)    │
                                   └─────────────┘

示例

三个示例演示了 UI 工具:

示例描述运行命令
ui_agent控制台演示cargo run --bin ui_agent
ui_server带 SSE 的 HTTP 服务器cargo run --bin ui_server
ui_react_clientReact 前端cd ui_react_client && npm run dev

official_docs_examples/tools/ui_test/ 运行。

示例提示

使用这些提示测试 UI 工具:

# Forms
"I want to register for an account"
"Create a contact form"
"Create a feedback form with a comments textarea"

# Cards
"Show me my profile"
"Display a product card for a laptop"

# Alerts
"Show a success message"
"Display a warning about expiring session"

# Modals
"I want to delete my account" (shows confirmation modal)
"Show a confirmation dialog before submitting"

# Toasts
"Show a success toast notification"
"Display an error toast"

# Tables
"Show my recent orders"
"List all users"

# Charts
"Show monthly sales chart"
"Display traffic trends as a line chart"
"Show revenue breakdown as a pie chart"

# Progress & Loading
"Show upload progress at 75%"
"Display a loading spinner"
"Show skeleton loading state"

# Dashboards
"Show system status dashboard"

上一页: ← 浏览器工具 | 下一页: MCP 工具 →