1. 概览
大多数 AI 智能体都会以文本形式回答。在此 Codelab 中,您将使用 A2UI 让代理通过界面进行回复。智能体使用标准组件目录以 JSON 格式描述卡片、列表、按钮和表单,而客户端使用自己的原生 widget 渲染这些元素,因此新布局不需要新的前端代码。
您将使用智能体开发套件 (ADK) 构建智能体。
构建内容
一个模拟云基础设施信息中心,分为三个阶段:
- 以纯文本形式返回资源数据的标准代理
- 一种 A2UI 代理,可返回与结构化 A2UI JSON 相同的数据
- 一种已渲染的代理,可在 ADK 开发者界面中将 A2UI JSON 显示为互动式界面组件

学习内容
- A2UI 的工作原理:18 个基元、用于构建界面的消息和平坦的组件模型
- 如何使用 A2UI SDK 提示 ADK 智能体生成 A2UI JSON
- 如何在
adk web中渲染 A2UI 组件
所需条件
本 Codelab 适用于对 Python 和 Google Cloud 有一定了解的中级开发者。
完成此 Codelab 大约需要 20 分钟。
本 Codelab 中创建的资源费用应低于 5 美元。
2. 设置您的环境
创建 Google Cloud 项目
- 在 Google Cloud 控制台的项目选择器页面上,选择或创建一个 Google Cloud 项目。
- 确保您的 Cloud 项目已启用结算功能。了解如何检查项目是否已启用结算功能。
启动 Cloud Shell Editor
如需从 Google Cloud 控制台启动 Cloud Shell 会话,请点击 Google Cloud 控制台中的激活 Cloud Shell。
此操作会在 Google Cloud 控制台的底部窗格中启动会话。
如需启动编辑器,请点击 Cloud Shell 窗口工具栏上的打开编辑器。
启用 API
在 Cloud Shell 编辑器工具栏中,依次点击终端和新终端,然后运行以下命令以启用所需的 API:
gcloud services enable aiplatform.googleapis.com
安装依赖项
在终端中,运行以下命令来创建此 Codelab 的文件夹,并在其中创建一个用于存放智能体代码的 a2ui_agent 文件夹,然后安装智能体开发套件 (ADK) 和 A2UI SDK:
mkdir -p ~/adk-a2ui/a2ui_agent cd ~/adk-a2ui uv init --bare uv add google-adk a2ui-agent-sdk
uv 会为此 Codelab 创建一个隔离的 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 包含一个开发者界面,您可以在浏览器中使用该界面与智能体互动并向其发送提示以进行测试。
启动 ADK 开发者界面
在 Cloud Shell 编辑器终端中,运行以下命令以启动 ADK 开发界面:
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 开发者界面
您可以在浏览器中打开 ADK 开发界面,方法是按 Ctrl 或 Cmd 点击本地测试网址,或者点击网页预览按钮并选择在端口 8080 上预览。
查看 ADK 开发者界面后,从下拉菜单中选择 a2ui_agent。
发送示例提示
向代理发送示例提示:
What's running in my project?
现在,尝试另一个示例提示,您将获得更多文本输出:
Does anything need my attention?
您的对话应如下所示:

回答准确,但内容过于冗长。
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,以便您阅读。您稍后会移除它,以查看界面渲染效果。
prompt_generator.generate() 方法会将您的角色描述与完整的 A2UI JSON 架构和少样本示例相结合,以便 LLM 确切地知道如何设置输出格式。您无需手动编写组件目录。
此 Codelab 使用 A2UI 版本 0.8 (version="0.8"),这是 adk web A2UI 渲染器支持的版本。
6. 测试 JSON 输出
如果您之前运行的 ADK 开发者界面仍在运行,则该界面应会自动重新加载您对代理所做的更改。
选择 a2ui_agent,点击 ADK 开发者界面右上角的 + 新建会话,开始新会话,然后发送与之前相同的提示:
What's running in my project?
这次,智能体以 A2UI JSON 而不是纯文本进行响应。您会在聊天输出中看到结构化消息,例如 beginRendering 和 surfaceUpdate(有时还会看到 dataModelUpdate),这些消息位于 JSON 代码块中。

该 JSON 描述了一个包含卡片、图标和按钮的丰富界面,但 show_raw_json 会将其保留为文本,以便您阅读。接下来,您将了解此 JSON 的结构,然后移除 show_raw_json 以将其渲染为实际的界面组件。
7. 了解 A2UI
查看您的代理刚刚生成的 JSON。A2UI 有三种类型的消息用于构建界面。智能体的输出可能并非每次都使用这三个工具:
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. 测试渲染的界面
如果您之前运行的 ADK 开发者界面仍在运行,则该界面应会自动重新加载您对代理所做的更改。
刷新浏览器标签页,选择 a2ui_agent,然后点击 ADK 开发者界面右上角的 + 新建会话,开始新会话,并发送与之前相同的提示:
What's running in my project?
这一次,adk web 会将 A2UI 组件渲染为实际界面:包含状态指示器、资源详细信息和操作按钮的卡片。

尝试使用其他提示,看看智能体如何使用同一组原语来组成不同的界面:
Does anything need my attention?
最后,尝试使用另一个提示来生成用于部署新服务的不同界面:
I need to deploy a new service
这三个提示使用相同的代理、工具和组件,但每个提示都会生成不同的界面,以满足您的要求。
10. 清理
为避免本地服务器持续运行,请清理资源:
- 在运行
adk web的终端中,按 Ctrl+C 停止代理服务器。
如果您专门为此 Codelab 创建了一个项目,可以删除整个项目:
gcloud projects delete <YOUR_PROJECT_ID>
11. 恭喜
您构建了一个 ADK 智能体,该智能体使用 A2UI 生成丰富的交互式界面。
要点回顾
- A2UI 是一种协议,包含 18 个声明式原语和一些用于构建界面的简单消息
- A2UI SDK 会生成系统提示,让 LLM 了解组件目录
- 同一智能体、工具和基元可针对不同意图组成不同的界面
- 在开发期间,A2UI 组件可以直接在
adk web中呈现
构建生产环境前端
在此 Codelab 中,您在 adk web 内渲染了 A2UI,以进行开发和测试。
对于生产环境,您可以使用以下官方 A2UI 渲染器之一构建前端:
平台 | 渲染程序 | 安装 |
Web (React) |
|
|
Web(Lit) |
|
|
Web(Angular) |
|
|
移动设备/桌面设备 | Flutter GenUI SDK |
参考文档
后续步骤
探索学习资源,了解如何使用 Gemini Enterprise Agent Ready (GEAR) 构建和部署企业级智能体。