UI ツール

adk-ui クレートを使用すると、AI エージェントはツールコールを介してリッチなユーザーインターフェースを動的に生成できます。エージェントは、フォーム、カード、アラート、テーブル、チャートなどをレンダリングできます。これらはすべて、フロントエンドでの利用のために JSON にシリアライズされるタイプセーフな Rust API を介して行われます。

構築するもの

ADK UI エージェント

主要な概念:

  • フォーム - さまざまなフィールドタイプでユーザー入力を収集します
  • カード - アクションボタン付きで情報を表示します
  • テーブル - 構造化されたデータを行と列で表示します
  • チャート - 棒グラフ、折れ線グラフ、面グラフ、円グラフでデータを視覚化します
  • アラート - 通知とステータスメッセージを表示します
  • モーダル - 確認ダイアログとフォーカスされたインタラクション
  • トースト - 短いステータス通知

例: アナリティクスダッシュボード

ADK UI アナリティクス

例: 登録フォーム

ADK UI 登録


動作の仕組み

┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 1: ユーザーが何かを要求する                                            │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   User: 「アカウントを登録したい」                                          │
│                                                                             │
│                              ↓                                              │
│                                                                             │
│   ┌──────────────────────────────────────┐                                  │
│   │         AI AGENT (LLM)              │                                  │
│   │  「登録フォームを表示すべきだ」      │                                  │
│   └──────────────────────────────────────┘                                  │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 2: Agentがrender_formツールを呼び出す                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   📞 Tool Call: render_form({                                               │
│     title: "登録",                                                          │
│     fields: [                                                               │
│       {name: "email", type: "email"},                                       │
│       {name: "password", type: "password"}                                  │
│     ]                                                                       │
│   })                                                                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 3: フロントエンドがフォームをレンダリングする                          │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌─────────────────────────────────────────────────┐                       │
│   │  📋 登録                                       │                       │
│   │  ────────────────────────────────────────────  │                       │
│   │  Email:    [________________________]          │                       │
│   │  パスワード: [________________________]          │                       │
│   │                                                │                       │
│   │  [           登録           ]              │                       │
│   └─────────────────────────────────────────────────┘                       │
│                                                                             │
│   ✅ ユーザーは対話型フォームを見て、入力し、「登録」をクリックする         │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 4: フォームの送信がAgentに送り返される                                 │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   📩 Event: {                                                               │
│     type: "form_submit",                                                    │
│     data: { email: "user@example.com", password: "***" }                    │
│   }                                                                         │
│                                                                             │
│   Agent: 「素晴らしい!登録を処理して、成功アラートを表示します」          │
│                                                                             │
│   📞 Tool Call: render_alert({                                              │
│     title: "登録完了!",                                                    │
│     variant: "success"                                                      │
│   })                                                                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

概要

UI ツールを使用すると、Agent は以下のことが可能になります。

  • テキストエリアをサポートする動的なフォームを通じてユーザー入力を収集する
  • カード、アラート、通知で情報を表示する
  • テーブルやインタラクティブなチャート (Recharts) でデータを提示する
  • 進行状況と読み込み状態 (スピナー、スケルトン) を表示する
  • 複数のコンポーネントでダッシュボードレイアウトを作成する
  • モーダルを介してユーザー確認を要求する
  • ステータス更新のためにトースト通知を表示する

クイックスタート

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"}
  ]
}

ボタンのvariant: primary, secondary, danger, ghost, outline

render_alert

通知とステータスメッセージを表示します。

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

Variant: 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

ステータス更新のために短いトースト通知を表示します。

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

Variant: 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()),
    })),
};

Operations: ReplacePatchAppendRemove

コンポーネントスキーマ

全28のコンポーネントタイプは、ストリーミング更新のためのオプションの id フィールドをサポートしています:

Atoms: Text、Button、Icon、Image、Badge Inputs: TextInput、NumberInput、Select、MultiSelect、Switch、DateInput、Slider、Textarea Layouts: Stack、Grid、Card、Container、Divider、Tabs Data: Table、List、KeyValue、CodeBlock Visualization: Chart (Recharts経由のbar、line、area、pie) Feedback: Alert、Progress、Toast、Modal、Spinner、Skeleton

Reactクライアント

リファレンスのReact実装が提供されています:

cd official_docs_examples/tools/ui_test

# Start the UI server
cargo run --bin ui_server

# In another terminal, start the React client
cd ui_react_client
npm install && npm run dev -- --host

Reactクライアントには以下が含まれます:

  • Rustスキーマに一致するTypeScriptタイプ
  • 全28タイプのコンポーネントレンダラー
  • インタラクティブなチャートのためのRecharts統合
  • Markdownレンダリングサポート
  • ダークモードサポート
  • フォーム送信処理
  • Modalおよびtoastコンポーネント

アーキテクチャ

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

3つの例でUIツールを示します:

説明実行コマンド
ui_agentコンソールデモcargo run --bin ui_agent
ui_serverSSE付きHTTPサーバーcargo run --bin ui_server
ui_react_clientReactフロントエンドcd ui_react_client && npm run dev

official_docs_examples/tools/ui_test/ から実行してください。

サンプルプロンプト

UIツールを以下のプロンプトでテストします。

# Forms
「アカウントを登録したい」
「問い合わせフォームを作成する」
「コメント入力欄付きのフィードバックフォームを作成する」

# Cards
「私のプロフィールを表示する」
「ノートパソコンの商品カードを表示する」

# Alerts
「成功メッセージを表示する」
「セッション期限切れに関する警告を表示する」

# Modals
「アカウントを削除したい」(確認モーダルを表示)
「送信前に確認ダイアログを表示する」

# Toasts
「成功トースト通知を表示する」
「エラーをトースト表示する」

# Tables
「最近の注文を表示する」
「すべてのユーザーを一覧表示する」

# Charts
「月間売上チャートを表示する」
「トラフィック傾向を折れ線グラフで表示する」
「収益の内訳を円グラフで表示する」

# Progress & Loading
「アップロードの進捗を75%で表示する」
「ローディングスピナーを表示する」
「スケルトンローディング状態を表示する」

# Dashboards
「システムステータスダッシュボードを表示する」

前へ: ← Browser Tools | 次へ: MCP Tools →