使用 ADK 和 A2UI 打造前端體驗

1. 總覽

大多數 AI 代理程式都會以文字回覆。在本程式碼研究室中,您將使用 A2UI,讓代理程式改為透過使用者介面回覆。代理程式會使用標準元件目錄,以 JSON 格式描述資訊卡、清單、按鈕和表單,而用戶端會使用自己的原生小工具算繪這些元素,因此新版面配置不需要新的前端程式碼。

您將使用 Agent Development Kit (ADK) 建構代理。

建構項目

模擬雲端基礎架構資訊主頁,分為三個階段:

  1. 傳回純文字格式資源資料的標準代理程式
  2. A2UI 代理程式,傳回的資料與結構化 A2UI JSON 相同
  3. 已算繪的代理,會在 ADK 開發 UI 中將 A2UI JSON 顯示為互動式 UI 元件

ADK A2UI 代理

課程內容

  • A2UI 的運作方式:18 個基本元素、建構 UI 的訊息,以及平面元件模型
  • 如何使用 A2UI SDK 提示 ADK 代理產生 A2UI JSON
  • 如何在 adk web 中轉譯 A2UI 元件

軟硬體需求

  • 已啟用計費功能的 Google Cloud 雲端專案
  • 網路瀏覽器,例如 Chrome
  • 如果您是在自己的電腦上執行程式碼,而非 Cloud Shell,則需要 Python 3.12 以上版本和 uv

本程式碼實驗室適合對 Python 和 Google Cloud 有基本認識的中級開發人員。

完成這個程式碼研究室大約需要 20 分鐘。

本程式碼研究室建立的資源費用應低於 $5 美元。

2. 設定環境

建立 Google Cloud 專案

  1. 在 Google Cloud 控制台的專案選擇器頁面中,選取或建立 Google Cloud 專案。
  2. 確認 Cloud 專案已啟用計費功能。瞭解如何檢查專案是否已啟用計費功能。

啟動 Cloud Shell 編輯器

如要從 Google Cloud 控制台啟動 Cloud Shell 工作階段,請點選 Google Cloud 控制台中的「啟用 Cloud Shell」。

系統會在 Google Cloud 控制台的底部窗格啟動工作階段。

如要啟動編輯器,請點選 Cloud Shell 視窗工具列中的「開啟編輯器」。

啟用 API

在 Cloud Shell 編輯器工具列中,依序點選「終端機」和「新增終端機」,然後執行下列指令來啟用必要 API:

gcloud services enable aiplatform.googleapis.com

安裝依附元件

在終端機執行下列指令,為本程式碼實驗室建立資料夾,並在其中建立 a2ui_agent 資料夾來存放代理程式碼,然後安裝 Agent Development Kit (ADK) 和 A2UI SDK:

mkdir -p ~/adk-a2ui/a2ui_agent
cd ~/adk-a2ui
uv init --bare
uv add google-adk a2ui-agent-sdk

uv 會為這個程式碼研究室建立獨立的 Python 環境,因此您不需要啟用任何項目。在 Python 指令前加上 uv run。

3. 建構代理

首先,請使用會傳回純文字的標準 ADK 代理。這就是目前大多數服務專員應用程式的樣貌。

設定專案設定

在終端機中執行下列指令,使用專案和位置建立 a2ui_agent/.env,並讓 ADK 透過 Google Cloud 專案呼叫 Gemini。ADK 會自動載入這個檔案,因此設定也會在新終端機中生效。

cat > ~/adk-a2ui/a2ui_agent/.env <<EOF
GOOGLE_CLOUD_PROJECT=$(gcloud config get project)
GOOGLE_CLOUD_LOCATION=global
GOOGLE_GENAI_USE_ENTERPRISE=True
EOF

定義工具和模擬資料

建立 a2ui_agent/resources.py,並加入以下內容。這項工具會傳回雲端資源清單及其狀態。

RESOURCES = [
    {
        "name": "auth-service",
        "type": "Cloud Run",
        "region": "us-west1",
        "status": "healthy",
        "cpu": "2 vCPU",
        "memory": "1 GiB",
        "instances": 3,
        "url": "https://auth-service-abc123.run.app",
        "last_deployed": "2026-04-18T14:22:00Z",
    },
    {
        "name": "events-db",
        "type": "Cloud SQL",
        "region": "us-east1",
        "status": "warning",
        "tier": "db-custom-8-32768",
        "storage": "500 GB SSD",
        "connections": 195,
        "version": "PostgreSQL 16",
        "issue": "Storage usage at 92%",
    },
    {
        "name": "analytics-pipeline",
        "type": "Cloud Run",
        "region": "us-west1",
        "status": "error",
        "cpu": "2 vCPU",
        "memory": "4 GiB",
        "instances": 0,
        "url": "https://analytics-pipeline-ghi789.run.app",
        "last_deployed": "2026-04-10T16:45:00Z",
        "issue": "CrashLoopBackOff: OOM killed",
    },
]

def get_resources() -> list[dict]:
    """Get all cloud resources in the current project.
    Returns a list of cloud infrastructure resources including their
    name, type, region, status, and type-specific details.
    Status is one of: healthy, warning, error. Resources with
    warning or error status include an 'issue' field describing
    the problem.
    """
    return RESOURCES

定義代理

建立 a2ui_agent/agent.py,並加入以下內容:

from google.adk.agents import Agent
from google.adk.models import Gemini
from google.genai import types
from .resources import get_resources

root_agent = Agent(
    model=Gemini(
        model="gemini-3.8-flash",
        retry_options=types.HttpRetryOptions(attempts=5),
    ),
    name="cloud_dashboard",
    description="A cloud infrastructure assistant that reports on project resources.",
    instruction=(
        "You are a cloud infrastructure assistant. When users ask about their "
        "cloud resources, use the get_resources tool to fetch the current state. "
        "Summarize the results clearly in plain text."
    ),
    tools=[get_resources],
)

4. 測試代理

ADK 包含開發 UI,您可以在瀏覽器中與代理互動並傳送提示,以進行測試。

啟動 ADK 開發 UI

在 Cloud Shell 編輯器終端機中,執行下列指令來啟動 ADK 開發人員 UI:

uv run adk web --port 8080 --allow_origins "*" --reload_agents

畫面會顯示類似下列的訊息:

+-----------------------------------------------------------------------------+
| ADK Web Server started                                                      |
|                                                                             |
| For local testing, access at http://127.0.0.1:8080.                         |
+-----------------------------------------------------------------------------+

開啟 ADK 開發 UI

如要在瀏覽器中開啟 ADK 開發人員 UI,請按 Ctrl 或 Cmd 點選本機測試網址,或按一下「Web Preview」(網頁預覽) 按鈕,然後選取「Preview on Port 8080」(透過以下通訊埠預覽:8080)。

查看 ADK 開發 UI 時,請從下拉式選單中選取 a2ui_agent。

傳送範例提示

向代理傳送範例提示:

What's running in my project?

現在請試試其他提示,你會發現輸出文字變多了:

Does anything need my attention?

對話內容應如下所示:

ADK 文字代理

答案正確,但內容密密麻麻。

5. 生成 A2UI JSON

接著,將代理從純文字切換為 A2UI。

A2UI Python SDK 內含提示生成器,可為您撰寫系統提示。這會教導 LLM 完整的 A2UI 元件目錄、正確的屬性名稱和類型,以及 JSON 結構。

更新代理程式

將 a2ui_agent/agent.py 改成以下內容:

from google.adk.agents import Agent
from google.adk.agents.callback_context import CallbackContext
from google.adk.models import Gemini
from google.adk.models.llm_response import LlmResponse
from google.genai import types
from a2ui.inference_formats.direct_json import DirectJsonFormat
from a2ui.basic_catalog.provider import BasicCatalog
from .resources import get_resources

a2ui_format = DirectJsonFormat(
    version="0.8",
    catalogs=[BasicCatalog.get_config("0.8")],
)

instruction = a2ui_format.prompt_generator.generate(
    role_description=(
        "You are a cloud infrastructure assistant. When users ask about "
        "their cloud resources, use the get_resources tool to fetch the "
        "current state."
    ),
    workflow_description=(
        "Analyze the user's request and return structured UI when appropriate."
    ),
    ui_description=(
        "Use cards for resource summaries, rows and columns for comparisons, "
        "icons for status indicators, and buttons for drill-down actions. "
        "Do NOT use markdown formatting in text values. Use the usageHint "
        "property for heading levels instead. "
        "Respond ONLY with the A2UI JSON array. Do NOT include any text "
        "outside the JSON. Put all explanations into Text components."
    ),
    include_schema=True,
    include_examples=True,
)


def show_raw_json(
    callback_context: CallbackContext,
    llm_response: LlmResponse,
) -> LlmResponse | None:
    """Show the A2UI JSON as text so you can read it, instead of rendering it."""
    if not llm_response.content or not llm_response.content.parts:
        return None
    for part in llm_response.content.parts:
        if part.text:
            part.text = (
                part.text
                .replace("<a2ui-json>", "```json\n")
                .replace("</a2ui-json>", "\n```")
            )
    return llm_response


root_agent = Agent(
    model=Gemini(
        model="gemini-3.8-flash",
        retry_options=types.HttpRetryOptions(attempts=5),
    ),
    name="cloud_dashboard",
    description="A cloud infrastructure assistant that renders rich A2UI interfaces.",
    instruction=instruction,
    tools=[get_resources],
    after_model_callback=show_raw_json,
)

show_raw_json 會以文字形式顯示 A2UI JSON,方便您閱讀。稍後會移除這個項目,查看 UI 算繪結果。

prompt_generator.generate() 方法會將角色說明與完整的 A2UI JSON 結構定義和少量樣本結合,讓 LLM 確切瞭解輸出內容的格式。您不需要手動編寫元件目錄。

本程式碼研究室使用 A2UI 0.8 版 (version="0.8"),這是 adk web A2UI 算繪器支援的版本。

6. 測試 JSON 輸出內容

如果您先前已執行 ADK 開發人員 UI,系統應會自動重新載入您對代理程式所做的變更。

選取 a2ui_agent,點選 ADK 開發 UI 右上方的「+ New Session」,開始新的工作階段,然後傳送與先前相同的提示:

What's running in my project?

這次代理會傳回 A2UI JSON,而不是純文字。在 JSON 程式碼區塊中,您會在對話輸出內容中看到 beginRendering 和 surfaceUpdate 等結構化訊息 (有時也會看到 dataModelUpdate)。

ADK A2UI JSON

JSON 描述的是含有資訊卡、圖示和按鈕的豐富 UI,但 show_raw_json 會將其保留為文字,方便您閱讀。接著,您會查看這個 JSON 的結構,然後移除 show_raw_json,將其算繪為實際的 UI 元件。

7. 瞭解 A2UI

查看代理剛生成的 JSON。A2UI 提供三種訊息類型,可供建構 UI。代理的輸出內容不一定每次都會使用這三種格式:

1. beginRendering

建立算繪介面並命名根元件:

{"beginRendering": {"surfaceId": "default", "root": "main-column"}}

2. surfaceUpdate

以 ID 參照 (非巢狀結構) 形式,將元件樹狀結構做為扁平清單傳送:

{"surfaceUpdate": {"surfaceId": "default", "components": [
  {"id": "main-column", "component": {"Column": {"children": {"explicitList": ["title", "card1"]}}}},
  {"id": "title", "component": {"Text": {"text": {"literalString": "My Resources"}, "usageHint": "h1"}}},
  {"id": "card1", "component": {"Card": {"child": "card1-content"}}},
  {"id": "card1-content", "component": {"Text": {"text": {"path": "service_name"}}}}
]}}

3. dataModelUpdate

將資料與結構分開傳送:

{"dataModelUpdate": {"surfaceId": "default", "contents": [
  {"key": "service_name", "valueString": "auth-service"},
  {"key": "status", "valueString": "healthy"}
]}}

元件會使用 {"path": "key"} 繫結至資料。您可以更新資料,不必重新傳送元件樹狀結構。

18 個基本型別

類別

元件

版面配置

資訊卡、欄、列、清單、分頁、分隔線、模式

螢幕

文字、圖片、圖示、影片、AudioPlayer

輸入功率

TextField、DateTimeInput、MultipleChoice、CheckBox、Slider

動作

按鈕

代理程式會使用這些相同元件建構不同的版面配置,例如瀏覽檢視畫面、優先順序資訊主頁或設定表單。如要瞭解各項元件的詳細資料,請參閱元件參考資料。

8. 算繪 A2UI 元件

SDK 會將 A2UI 包裝在標準 標記中。adk web 會辨識這些元件,並使用內建的 A2UI 算繪器算繪元件。如要查看,請移除 show_raw_json。

更新代理程式

將 a2ui_agent/agent.py 改成以下內容。與上一個步驟相比,唯一變更之處是 show_raw_json 函式、其 after_model_callback 參數,以及使用的兩個匯入項目都已移除:

from google.adk.agents import Agent
from google.adk.models import Gemini
from google.genai import types
from a2ui.inference_formats.direct_json import DirectJsonFormat
from a2ui.basic_catalog.provider import BasicCatalog
from .resources import get_resources

a2ui_format = DirectJsonFormat(
    version="0.8",
    catalogs=[BasicCatalog.get_config("0.8")],
)

instruction = a2ui_format.prompt_generator.generate(
    role_description=(
        "You are a cloud infrastructure assistant. When users ask about "
        "their cloud resources, use the get_resources tool to fetch the "
        "current state."
    ),
    workflow_description=(
        "Analyze the user's request and return structured UI when appropriate."
    ),
    ui_description=(
        "Use cards for resource summaries, rows and columns for comparisons, "
        "icons for status indicators, and buttons for drill-down actions. "
        "Do NOT use markdown formatting in text values. Use the usageHint "
        "property for heading levels instead. "
        "Respond ONLY with the A2UI JSON array. Do NOT include any text "
        "outside the JSON. Put all explanations into Text components."
    ),
    include_schema=True,
    include_examples=True,
)

root_agent = Agent(
    model=Gemini(
        model="gemini-3.8-flash",
        retry_options=types.HttpRetryOptions(attempts=5),
    ),
    name="cloud_dashboard",
    description="A cloud infrastructure assistant that renders rich A2UI interfaces.",
    instruction=instruction,
    tools=[get_resources],
)

9. 測試算繪的 UI

如果您先前已執行 ADK 開發人員 UI,系統應會自動重新載入您對代理程式所做的變更。

重新整理瀏覽器分頁,選取 a2ui_agent,然後點選 ADK 開發 UI 右上方的「+New Session」,啟動新的工作階段,並傳送與先前相同的提示:

What's running in my project?

這次 adk web 會將 A2UI 元件轉譯為實際 UI:含有狀態指標、資源詳細資料和動作按鈕的資訊卡。

ADK A2UI 代理

請嘗試其他提示詞,看看代理如何從同一組基本元素組成不同的 UI:

Does anything need my attention?

最後,請嘗試使用其他提示詞生成不同的 UI,部署新服務:

I need to deploy a new service

這三項提示都使用相同的代理程式、工具和元件,但每個提示都會產生符合您要求的不同 UI。

10. 清除

為避免本機伺服器持續運作,請清理資源:

  • 在執行 adk web 的終端機中,按下 Ctrl+C 鍵停止代理程式伺服器。

如果您是特地為了這個程式碼研究室建立專案,可以刪除整個專案:

gcloud projects delete <YOUR_PROJECT_ID>

11. 恭喜

您已建構 ADK 代理,可使用 A2UI 生成豐富的互動式 UI。

您學到的內容

  • A2UI 是一種通訊協定,包含 18 個宣告式基本元素和幾個簡單的訊息,可建構 UI
  • A2UI SDK 會生成系統提示,教導 LLM 元件目錄
  • 相同代理程式、工具和基本型別會根據不同意圖組成不同的 UI
  • 開發期間,A2UI 元件可直接在 adk web 中算繪

建構正式版前端

在本程式碼研究室中,您在 adk web 內算繪 A2UI,以進行開發和測試。

如要用於正式環境,請使用其中一個官方 A2UI 算繪器建構前端:

平台

轉譯器

安裝

網頁 (React)

@a2ui/react

npm install @a2ui/react

網頁 (Lit)

@a2ui/lit

npm install @a2ui/lit

網頁 (Angular)

@a2ui/angular

npm install @a2ui/angular

行動裝置/電腦

Flutter GenUI SDK

開始使用

參考文件

後續步驟

透過 Gemini Enterprise Agent Ready (GEAR) 學習資源,建構及部署企業級代理。