UI 工具
adk-ui crate 让 AI Agent 能够通过工具调用动态生成丰富的用户界面。Agent 可以渲染表单、卡片、提醒、表格、图表等内容,并通过类型安全的 Rust API 序列化为 JSON,供前端使用。
您将构建什么

核心概念:
- 表单 - 使用不同字段类型收集用户输入
- 卡片 - 显示信息和操作按钮
- 表格 - 以行和列呈现结构化数据
- 图表 - 使用柱状图、折线图、面积图和饼图可视化数据
- 提醒 - 显示通知和状态消息
- 模态框 - 提供确认对话框和聚焦式交互
- Toast 通知 - 显示简短的状态通知
- 协议互操作 - 将 UI 输出为 A2UI、AG-UI 或 MCP Apps 负载
示例:分析仪表板

示例:注册表单

工作原理
┌─────────────────────────────────────────────────────────────────────────────┐
│ 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 工具让 Agent 能够:
- 通过支持文本区域的动态表单收集用户输入
- 使用卡片、提醒和通知显示信息
- 使用表格和交互式图表(Recharts)呈现数据
- 显示进度和加载状态(spinner、skeleton)
- 使用多个组件创建仪表板布局
- 通过模态框请求用户确认
- 使用 Toast 通知显示状态更新
快速开始
添加到您的 Cargo.toml:
[dependencies]
adk-ui = { git = "https://github.com/zavora-ai/adk-ui" }
adk-agent = "2.0.0"
adk-model = "2.0.0"
Basic Usage
use adk_rust::prelude::*;
use adk_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.5-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(())
}
A2UI JSONL (render_screen / render_page / render_kit)
这些工具输出 A2UI v0.9 JSONL,以兼容 A2UI 渲染器。
render_screen (single surface)
{
"surface_id": "main",
"components": [
{ "id": "root", "component": "Column", "children": ["title", "cta"] },
{ "id": "title", "component": "Text", "text": "Welcome", "variant": "h1" },
{ "id": "cta_label", "component": "Text", "text": "Continue", "variant": "body" },
{ "id": "cta", "component": "Button", "child": "cta_label", "action": { "event": { "name": "continue" } } }
]
}
render_page (multi-section page)
{
"title": "Release Notes",
"description": "Highlights for the latest launch.",
"sections": [
{
"heading": "What’s new",
"body": "Three big improvements shipped this week.",
"bullets": ["Faster onboarding", "Better search", "New dashboards"],
"actions": [{ "label": "View details", "action": "view_details", "variant": "borderless" }]
}
]
}
render_kit (目录 + 令牌 + 模板)
{
"name": "Fintech Pro",
"version": "0.1.0",
"brand": { "vibe": "trustworthy", "industry": "fintech" },
"colors": { "primary": "#2F6BFF" },
"typography": { "family": "Source Sans 3" },
"templates": ["auth_login", "dashboard"]
}
使用 React 渲染器来消费 A2UI JSONL:
import {
A2uiStore,
A2uiSurfaceRenderer,
applyParsedMessages,
parseJsonl,
} from "@zavora-ai/adk-ui-react";
const store = new A2uiStore();
const parsed = parseJsonl(jsonl);
applyParsedMessages(store, parsed);
export function App() {
return <A2uiSurfaceRenderer store={store} surfaceId="main" />;
}
可用工具
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() // Disable charts
.without_table() // Disable tables
.without_progress() // Disable progress
.without_modal() // Disable modals
.without_toast(); // Disable toasts
// Or use forms only
let forms_only = UiToolset::forms_only();
处理 UI 事件
当用户与渲染的 UI 交互时(提交表单、点击按钮),事件会发送回 agent:
use adk_ui::{UiEvent, UiEventType};
// UiEvent structure
pub struct UiEvent {
pub event_type: UiEventType, // FormSubmit, ButtonClick, InputChange
pub action_id: Option<String>,
pub data: Option<HashMap<String, Value>>,
}
// Convert to message for 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()),
})),
};
操作:Replace, Patch, Append, Remove
组件架构
所有 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 客户端
独立的 adk-ui 仓库中提供了参考的 React 实现:
npm install @zavora-ai/adk-ui-react
React 客户端包括:
- TypeScript 与 Rust 模式匹配的类型
- 支持所有 28 种类型的组件渲染器
- Recharts 集成,用于交互式图表
- Markdown 渲染支持
- 暗模式支持
- 表单提交处理
- 模态框和 Toast 组件
架构
Agent ──[render_* tool]──> UiResponse (JSON)
│
│ SSE
▼
Client (React)
│
└──> UiEvent (user action) ──> Agent
协议互操作
所有 13 种渲染工具都通过 protocol 参数支持协议感知输出:
| 协议 | 描述 |
|---|---|
a2ui | A2UI v0.9 对齐的 JSONL 接口 (render_screen、render_page 的默认值) |
ag_ui | 混合 AG-UI 支持:默认兼容性封装,加上附加的协议原生运行时传输,适用于 adk-server 客户端 |
mcp_apps | 兼容性 MCP 应用负载与 ui:// 资源、附加桥接助手、通知流、运行时请求字段,以及 HTML/资源适配器 |
当 protocol 被省略时,工具使用其默认输出格式(大多数工具使用旧版 UiResponse JSON,A2UI 用于 render_screen/render_page/render_kit)。
协议选择示例:
{
"protocol": "mcp_apps",
"mcp_apps": {
"resource_uri": "ui://demo/surface"
}
}
互操作适配器
adk-ui 包含用于协议转换的适配器原语:
A2uiAdapter— 将规范表面转换为 A2UI JSONLAgUiAdapter— 转换为 AG-UI 事件负载McpAppsAdapter— 转换为 MCP Apps 资源负载
它们实现了一个共享的 UiProtocolAdapter trait,以实现在所有工具之间的一致转换。
弃用时间表
旧版 adk_ui runtime profile 包含弃用元数据:
| 日期 | 里程碑 |
|---|---|
| 2026-02-07 | 弃用公告 |
| 2026-12-31 | 停用目标 |
替代方案:a2ui、ag_ui、mcp_apps
这些元数据通过 UI_PROTOCOL_CAPABILITIES 常量公开,并由 adk-server 在 /api/ui/capabilities 提供。
能力响应还会报告 implementationTier、specTrack、summary 和 limitations,帮助客户端区分混合或兼容性子集与完全原生的协议支持。
当 adk-server 作为面向主机的边界时,它还会在 /api/ui/initialize、/api/ui/message、/api/ui/update-model-context、/api/ui/notifications/poll、/api/ui/notifications/resources-list-changed 和 /api/ui/notifications/tools-list-changed 提供额外的 MCP Apps 桥接辅助端点。这些端点保留现有 ADK 运行时契约,并接受直接请求正文或使用 ui/... 方法的类 JSON-RPC 信封。
对于运行时消费者,adk-server 还支持:
x-adk-ui-transport: protocol_native或uiTransport: "protocol_native"用于 AG-UI 原生 SSE 序列化- 通过
input/agUiInput实现 AG-UI 双路径请求输入,与现有newMessage并存 - 通过
mcpAppsInitialize、mcpAppsRequest和mcpAppsInitialized在/api/run_sse内部实现 MCP Apps 桥接信封
这些新增功能是可选的。现有的 /api/run 和 /api/run_sse 消费者将继续接收通用 ADK 包装器,除非他们明确请求原生 AG-UI 传输模式。
对于框架拥有的 MCP Apps 工具响应,adk-server::ui_types 现在公开了:
McpUiBridgeSnapshot用于类型化的主机/应用桥接状态McpUiToolResult用于附加响应信封McpUiToolResultBridge用于桥接元数据 (protocolVersion,structuredContent,hostInfo,hostCapabilities,hostContext,appInfo,appCapabilities,initialized)
优先使用 McpUiBridgeSnapshot::build_tool_result(...) 将 bridge/session state 提升为 tool response。这标准化了 tool-result shape,同时保留了 resourceUri 和 inline html 回退,以适应兼容性优先的主机。
对于嵌入式或浏览器主机映射,additive HTTP bridge 对应于 host/app flows 如下:
ui/initialize->/api/ui/initializeui/message->/api/ui/messageui/update-model-context->/api/ui/update-model-contextnotifications/resources/list_changed->/api/ui/notifications/resources-list-changednotifications/tools/list_changed->/api/ui/notifications/tools-list-changed- 排队的主机通知 ->
/api/ui/notifications/poll
Direct /api/ui/* bridge endpoints 是 MCP Apps hosts 的首选生命周期路径。Runtime-side MCP Apps request fields 仍然可用作混合或传统客户端的 additive 兼容性路径。
示例
独立的 adk-ui repo 包含可运行的 UI 示例:
| 示例 | 描述 | Run Command |
|---|---|---|
ui_agent | 控制台演示 | cargo run --bin ui_agent |
ui_server | HTTP 服务器与 SSE | cargo run --bin ui_server |
ui_react_client | React 前端 | cd ui_react_client && npm run dev |
运行这些示例,来自 adk-ui 仓库,以便 Rust 和 React 包保持在同一发布线上。
示例提示
使用这些提示测试 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"