UI 도구

adk-ui crate는 AI 에이전트가 tool calls를 통해 풍부한 사용자 인터페이스를 동적으로 생성할 수 있도록 합니다. 에이전트는 양식, 카드, 알림, 테이블, 차트 등을 렌더링할 수 있으며, 이 모든 것은 프런트엔드에서 소비할 수 있도록 JSON으로 직렬화되는 타입 안전한 Rust API를 통해 이루어집니다.

무엇을 만들게 될까요?

ADK UI 에이전트

주요 개념:

  • Forms - 다양한 필드 유형으로 사용자 입력 수집
  • Cards - 액션 버튼과 함께 정보 표시
  • Tables - 행/열에 구조화된 데이터 표시
  • Charts - 막대, 선, 영역, 원형 차트로 데이터 시각화
  • Alerts - 알림 및 상태 메시지 표시
  • Modals - 확인 대화 상자 및 집중된 상호 작용
  • Toasts - 짧은 상태 알림

예시: 분석 대시보드

ADK UI 분석

예시: 등록 양식

ADK UI 등록


작동 방식

┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 1: 사용자가 무언가를 요청합니다                                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   User: "계정을 등록하고 싶어요"                                          │
│                                                                             │
│                              ↓                                              │
│                                                                             │
│   ┌──────────────────────────────────────┐                                  │
│   │         AI AGENT (LLM)              │                                  │
│   │  "등록 양식을 보여줘야겠어"          │                                  │
│   └──────────────────────────────────────┘                                  │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 2: Agent가 render_form tool을 호출합니다                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   📞 Tool Call: render_form({                                               │
│     title: "등록",                                                          │
│     fields: [                                                               │
│       {name: "email", type: "email"},                                       │
│       {name: "password", type: "password"}                                  │
│     ]                                                                       │
│   })                                                                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 3: Frontend가 양식을 렌더링합니다                                       │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌─────────────────────────────────────────────────┐                       │
│   │  📋 등록                                       │                       │
│   │  ────────────────────────────────────────────  │                       │
│   │  이메일:   [________________________]          │                       │
│   │  비밀번호: [________________________]          │                       │
│   │                                                │                       │
│   │  [           등록           ]                  │                       │
│   └─────────────────────────────────────────────────┘                       │
│                                                                             │
│   ✅ 사용자가 대화형 양식을 보고 작성한 다음, 등록을 클릭합니다             │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────────────────┐
│ STEP 4: 폼 제출이 agent로 다시 전송됨                                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   📩 Event: {                                                               │
│     type: "form_submit",                                                    │
│     data: { email: "user@example.com", password: "***" }                    │
│   }                                                                         │
│                                                                             │
│   Agent: "좋아! 등록을 처리하고 성공 알림을 표시할게"                       │
│                                                                             │
│   📞 Tool Call: render_alert({                                              │
│     title: "등록 완료!",                                                    │
│     variant: "success"                                                      │
│   })                                                                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

개요

UI 도구를 통해 에이전트는 다음을 수행할 수 있습니다:

  • 텍스트 영역을 지원하는 동적 양식을 통해 사용자 입력 수집
  • 카드, 알림 및 통지를 사용하여 정보 표시
  • 테이블 및 대화형 차트(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"}
  ]
}

버튼 변형: 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

상태 업데이트를 위한 간략한 토스트 알림을 표시합니다.

{
  "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()),
    })),
};

작업: 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 클라이언트

참조 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 스키마와 일치하는 TypeScript 타입
  • 모든 28가지 타입에 대한 컴포넌트 렌더러
  • 인터랙티브 차트를 위한 Recharts 통합
  • 마크다운 렌더링 지원
  • 다크 모드 지원
  • 양식 제출 처리
  • 모달 및 토스트 컴포넌트

아키텍처

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

예시

세 가지 예시가 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 도구를 테스트하세요:

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

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

# 알림
"Show a success message"
"Display a warning about expiring session"

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

# 토스트
"Show a success toast notification"
"Display an error toast"

# 테이블
"Show my recent orders"
"List all users"

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

# 진행률 및 로딩
"Show upload progress at 75%"
"Display a loading spinner"
"Show skeleton loading state"

# 대시보드
"Show system status dashboard"

이전: ← Browser Tools | 다음: MCP Tools →