跳转到内容

A2UI — 用于 ADK 的“代理到用户界面”(Agent-to-UI)组件

在 ADK 中得到支持。Python

A2UI 允许您的代理自动生成相关内容。 Real UI — 包括卡片、表格、图表等元素,而不仅仅是文本。您的代理会生成结构化的 JSON 数据,客户端上的渲染器会将这些数据转换为交互式组件。

该技术不依赖于特定的传输协议:A2UI 的数据 payload 可通过 A2A、MCP、REST、WebSockets 或任何其他协议进行传输。代理程序(agent)会负责处理这些数据 payload 的传输过程。 什么 是否展示这些内容由客户决定。 如何;怎样 为了将其呈现出来(即为了让用户看到或理解该内容)。

了解更多关于 A2UI 的信息。

a2ui.org 该组件提供了完整的规格说明、相关文档、图片库(gallery)、产品目录(catalog)信息,以及渲染器(renderer)的详细使用说明。

快速入门指南

安装 SDK

pip install a2ui-agent-sdk

1. 设置 Schema Manager(模式管理器)。

The A2uiSchemaManager 加载组件目录并生成系统提示;这些提示用于指导大型语言模型(LLM)如何生成符合规范的 A2UI JSON 格式的数据。

from a2ui.core.schema.manager import A2uiSchemaManager
from a2ui.basic_catalog.provider import BasicCatalog

schema_manager = A2uiSchemaManager(
    catalogs=[
        BasicCatalog.get_config(
            examples_path="examples",
        ),
    ],
)

注意:

模式管理器会自动从传入的客户端请求中检测 A2UI 的版本。您也可以通过手动传递参数来明确指定 A2UI 的版本。 version=VERSION_0_9 如果需要的话。

提示(Tip)

如果您省略了…… catalogs 在处理参数时,模式管理器会使用相应的机制来进行处理。 基础目录(Basic Catalog) 该组件由 A2UI 团队维护,团队提供了许多常用的组件,如文本(Text)、卡片(Card)、按钮(Button)和图片(Image)等。你也可以自己创建新的组件。 自定义目录 可以使用特定于领域的组件,或者将基本目录与您自己的组件混合使用。 — 详见…… 高级模式(Advanced Patterns) 如下所示。

2. 生成系统提示信息。

The generate_system_prompt 该方法将您的代理角色描述与 A2UI JSON 架构以及少量示例数据相结合,从而使大型语言模型(LLM)能够准确了解如何格式化其输出结果。

instruction = schema_manager.generate_system_prompt(
    role_description="You are a helpful assistant that presents information with rich UI.",
    workflow_description="Analyze the user's request and return structured UI when appropriate.",
    ui_description="Use cards for summaries, tables for comparisons, and forms for user input.",
    include_schema=True,
    include_examples=True,
    allowed_components=["Heading", "Text", "Card", "Button", "Table"],
)

3. 创建您的 ADK 代理(ADK Agent)。

使用生成的指令作为代理系统的提示信息:

from google.adk.agents.llm_agent import LlmAgent

agent = LlmAgent(
    model="gemini-flash-latest",
    name="ui_agent",
    description="An agent that generates rich UI responses.",
    instruction=instruction,
)

4. 验证 A2UI 的输出结果,并将其以流的形式传输出去。

在将大型语言模型(LLM)生成的 JSON 数据发送给客户端之前,务必对其进行验证。SDK 提供了用于解析、修复数据以及验证数据有效性的工具。

from a2ui.core.parser.parser import parse_response
from a2ui.a2a import parse_response_to_parts

# Get the active catalog's validator
selected_catalog = schema_manager.get_selected_catalog()

# Option A: Manual parse + validate
response_parts = parse_response(llm_output_text)
for part in response_parts:
    if part.a2ui_json:
        selected_catalog.validator.validate(part.a2ui_json)

# Option B: One-liner that returns A2A Parts
parts = parse_response_to_parts(
    llm_output_text,
    validator=selected_catalog.validator,
    fallback_text="Here's what I found.",
)

A2UI 的数据负载(payloads)被封装在 A2A(点对点)通信框架中。 DataPart 使用相应的 MIME 类型 application/json+a2ui 这样,渲染器就可以识别它们了:

from a2ui.a2a import create_a2ui_part

part = create_a2ui_part({"type": "Card", "props": {"title": "Hello"}})
# → DataPart(data={...}, metadata={"mimeType": "application/json+a2ui"})

高级模式(Advanced Patterns)

动态目录

对于那些需要根据上下文使用不同用户界面组件(例如:用于数据查询的图表、用于配置的表单)的代理来说,应在运行时解析相关组件信息,并将其存储在会话状态(session state)中。

async def _prepare_session(self, context, run_request, runner):
    session = await super()._prepare_session(context, run_request, runner)

    # Determine client capabilities from request metadata
    capabilities = context.message.metadata.get("a2ui_client_capabilities")

    # Select the right catalog
    a2ui_catalog = self.schema_manager.get_selected_catalog(
        client_ui_capabilities=capabilities
    )
    examples = self.schema_manager.load_examples(a2ui_catalog, validate=True)

    # Store in session state for tool access
    await runner.session_service.append_event(
        session,
        Event(
            actions=EventActions(
                state_delta={
                    "system:a2ui_enabled": True,
                    "system:a2ui_catalog": a2ui_catalog,
                    "system:a2ui_examples": examples,
                }
            ),
        ),
    )
    return session

自定义目录

您可以为特定领域的用户界面(UI)定义自己的组件目录:

from a2ui.core.schema.manager import CatalogConfig

schema_manager = A2uiSchemaManager(
    catalogs=[
        BasicCatalog.get_config(),
        CatalogConfig.from_path(
            name="my_dashboard_catalog",
            catalog_path="catalogs/dashboard.json",
            examples_path="catalogs/dashboard_examples",
        ),
    ],
)

多智能体协同调度(Multi-agent orchestration)

Orchestrator 的代理程序可以从子代理程序中收集 A2UI(Application-to-User Interface)相关的功能,并将这些功能显示在代理程序的卡片上。

from a2ui.a2a import get_a2ui_agent_extension

# Collect catalog IDs from sub-agents
supported_catalog_ids = set()
for subagent in subagents:
    for extension in subagent_card.capabilities.extensions:
        if extension.uri == "https://a2ui.org/a2a-extension/a2ui/v0.9":
            supported_catalog_ids.update(
                extension.params.get("supportedCatalogIds") or []
            )

# Advertise in the orchestrator's AgentCard
agent_card = AgentCard(
    capabilities=AgentCapabilities(
        extensions=[
            get_a2ui_agent_extension(
                supported_catalog_ids=list(supported_catalog_ids),
            )
        ]
    )
)

示例(Samples)

A2UI 仓库中包含了 ADK 示例代理程序,您可以立即运行它们。

Sample 描述
restaurant_finder 用于搜索和显示餐厅信息的静态架构代理(Static Schema Agent)
rizzcharts 动态目录代理:根据上下文选择图表组件
**orchestrator**(协调器/编排器) 这种多代理(Multi-agent)架构会将任务分配给子代理(sub-agents),同时整合各个子代理提供的用户界面(UI)功能。

资源