CopilotKit A2A UI Generator Agent:用 A2A 协议与 A2UI 声明式 JSON 构建通用生成式 UI

原创2026-09-09 13:19:011,655 阅读
文章标签:人工智能AI 应用AI Agent交互助手工具调用前端UI组件Agent 框架移动开发后端WebSocket

CopilotKit A2A UI Generator Agent:用 A2A 协议与 A2UI 声明式 JSON 构建通用生成式 UI

本指南基于 CopilotKit 仓库中的 a2a-agent 示例(位于 generative-ui-playground 演示 下),系统讲解一个用 Python 编写的 A2A(Agent-to-Agent)通用 UI 生成 Agent:它借助 Google ADK 与 LiteLLM 把用户的自然语言请求转化为符合 A2UI 规范的声明式 JSON,由前端动态渲染成表单、列表、卡片、确认弹窗等交互界面。读完本文,你将掌握该 Agent 的启动方式、协议扩展机制、Prompt 工程与校验重试逻辑,并了解如何在 CopilotKit 前端通过 A2UIRenderer 与 HttpAgent 与之对接。

一、背景:A2A 与 A2UI 是什么

该示例同时涉及两个协议,理解二者的分工是读懂代码的前提:

  • A2A(Agent-to-Agent):用于 Agent 之间的消息传递。本示例中的 Agent 通过 A2A 服务器对外提供 agent.json Agent Card 与任务执行接口,客户端(如 CopilotKit 前端的 HttpAgent)经由 A2A 协议把用户请求发送过来。
  • A2UI(Agent-to-UI):Google 提出的声明式生成式 UI 协议,见示例目录中 CLAUDE.md 的说明。Agent 输出描述 UI 组件的 JSON,前端负责渲染,实现"Agent 说了算、前端只管画"的动态界面生成。

在 generative-ui-playground 的 README 中,A2UI 被归类为三种生成式 UI 类型之一:"Agent-composed declarative JSON UI rendered dynamically"(Agent 组合声明式 JSON、动态渲染的 UI),与"预构建 React 组件的静态 GenUI"、"MCP 服务器托管的 HTML 应用"并列。

二、项目结构与模块职责

该 Agent 位于 a2a-agent 目录,核心代码集中在 agent/ 包内。各模块职责如下表(依据目录结构与源码):

文件 职责
agent/main.py A2A 服务器入口:创建 AgentCard、装配 executor、启动 uvicorn、配置 CORS 与静态文件
agent/agent.py UIGeneratorAgent 核心类:基于 Google ADK LlmAgent,含流式响应与 A2UI 校验重试
agent/agent_executor.py UIGeneratorExecutor:处理 A2A 请求、解析 A2UI ClientEvent、把响应拆分为文本与 UI 两部分
agent/prompt_builder.py A2UI JSON Schema、UI 示例模板与系统 Prompt 的构建
agent/a2ui_extension.py A2UI 扩展辅助函数:创建/识别 A2UI DataPart、激活扩展
agent/tools.py 工具预留位(当前为空,UI 完全由用户描述生成)
pyproject.toml 打包与依赖声明(a2a-sdk、google-adk、litellm、jsonschema 等)
Dockerfile、railway.toml 容器化与 Railway 部署配置

从 agent.py 可以看到,Agent 的定位是 "An agent that generates any UI using A2UI declarative JSON",即通用型 UI 生成器,而非绑定某个固定业务场景。

三、快速开始:安装与运行

原文档给出了最精简的启动流程,这里结合实际代码补充细节。

1. 创建虚拟环境并安装

python -m venv .venv
source .venv/bin/activate
pip install -e .

pip install -e . 会依据 pyproject.toml 安装全部依赖,包括:

  • a2a-sdk>=0.3.0:A2A 协议服务端与类型定义;
  • google-adk>=1.8.0:Google Agent Development Kit,用于构建 LlmAgent 与 Runner;
  • google-genai>=1.27.0 与 litellm>=1.0.0:模型调用与多模型路由;
  • jsonschema>=4.0.0:A2UI 输出校验;
  • starlette、uvicorn:ASGI 服务框架;
  • click、python-dotenv、httpx:CLI、环境变量与 HTTP 客户端。

项目要求 Python >=3.11,这也是 Dockerfile 选择 python:3.12-slim 基础镜像的原因。

2. 配置环境变量

启动前需要准备模型相关配置(对应 CLAUDE.md 中的说明):

OPENAI_API_KEY=sk-...            # LiteLLM 调用模型所需
LITELLM_MODEL=openai/gpt-5.2     # 可选,默认即 openai/gpt-5.2

模型名在 agent.py 通过 os.getenv("LITELLM_MODEL", "openai/gpt-5.2") 读取,格式为 provider/model 的 LiteLLM 标准写法,因此也可替换为其他由 LiteLLM 支持的模型。

3. 启动 Agent 服务器

python -m agent

python -m agent 会执行 agent/main.py 中的 main()。该函数通过 Click 定义了两个可配置项(见 main.py#L112-L114):

参数 默认值 说明
--host 0.0.0.0 监听地址
--port 10002 监听端口,且支持环境变量 PORT 覆盖(envvar="PORT")

服务器启动后:

  • 服务端口 10002;
  • Agent Card 位于 http://localhost:10002/.well-known/agent.json,可用 curl 验证:
curl http://localhost:10002/.well-known/agent.json

Agent Card 由 create_agent_card() 构建,包含名称 "UI Generator"、版本 1.0.0、能力(streaming=True)以及四个预声明技能:create_form、create_list、create_card、create_confirmation。在 generative-ui-playground 的 README 中,它与 MCP Server(端口 3001)、Next.js 前端(端口 3000)一同作为三个服务运行。

四、架构与请求流转:从 A2A 请求到 A2UI 输出

1. 整体架构

依据 CLAUDE.md 的架构图,A2A 服务器内部结构如下:

A2A Server (port 10002)
├── AgentCard: Advertises A2UI extension
├── UIGeneratorAgent: Google ADK LlmAgent
├── Tools: None (UI generated from user descriptions)
└── A2UI Output: JSON array of UI components

2. 双 Agent 策略:按扩展激活情况选择

一个值得注意的设计是:executor 同时持有两个 UIGeneratorAgent 实例(agent_executor.py#L46-L47):

self.ui_agent = UIGeneratorAgent(base_url=base_url, use_ui=True)
self.text_agent = UIGeneratorAgent(base_url=base_url, use_ui=False)

请求进入后,先调用 try_activate_a2ui_extension() 检查客户端是否在 context.requested_extensions 中声明了 A2UI 扩展 URI:

  • 若声明了 A2UI 扩展,则激活扩展并选用 ui_agent(输出 A2UI JSON);
  • 否则退化为 text_agent(仅输出文本说明),见 agent_executor.py#L66-L74。

两种模式的 Prompt 分别由 get_ui_prompt() 与 get_text_prompt() 生成,在 agent.py#L114-L118 中根据 use_ui 标志选择。

3. LLM Agent 的构建

UIGeneratorAgent._build_agent() 使用 Google ADK 构建 LLM Agent:

return LlmAgent(
    model=LiteLlm(model=LITELLM_MODEL),
    name="ui_generator_agent",
    description="An agent that generates any UI using A2UI declarative JSON.",
    instruction=instruction,
    tools=[],  # No tools needed - UI is generated from user descriptions
)

值得注意:

  • tools=[]:该 Agent 刻意不挂载任何工具。UI 完全由用户描述驱动生成,这与 tools.py 顶部注释一致——"No tools currently needed - A2UI generates UI from user descriptions"。
  • Runner 在构造函数中创建(agent.py#L88-L94),配以 InMemoryArtifactService、InMemorySessionService、InMemoryMemoryService,即以内存方式维护会话与记忆,服务重启后状态即失。
  • 会话状态:stream() 会把 base_url 存入 session state(agent.py#L141-L157),并以 task.context_id 作为会话 ID 保证多轮对话连续性。

4. 响应格式:文本 + ---a2ui_JSON--- 分隔符

Agent 的最终输出被约束为"两段式"(见 CLAUDE.md 与 get_ui_prompt()):

Here's a contact form for you:
---a2ui_JSON---
[{"beginRendering": {...}}, {"surfaceUpdate": {...}}, {"dataModelUpdate": {...}}]
  • 第一部分是面向用户的对话文本;
  • 分隔符 ---a2ui_JSON--- 恰好出现一次,紧跟其后是一个 JSON 数组(由若干 A2UI message 组成);
  • Prompt 明确要求:分隔符只放在 JSON 之前,不要在 JSON 之后重复出现。

服务端在 agent.py#L228-L254 与 agent_executor.py#L144-L172 两侧都实现了拆分逻辑:先按分隔符切出文本与 JSON 字符串,再去掉可能包裹的 ```json 围栏,最后 json.loads 解析;若是数组则逐条封装为 A2UI Part。

五、A2UI 扩展与协议接入

1. 扩展 URI 与能力声明

A2UI 通过 A2A 的 extension 机制接入,扩展 URI 常量定义在 a2ui_extension.py#L17:

A2UI_EXTENSION_URI = "https://a2ui.org/a2a-extension/a2ui/v0.8"

get_a2ui_agent_extension() 生成扩展描述对象,其中 URI 即上述地址。关键细节:该扩展必须放在 AgentCapabilities.extensions 中,而不是直接挂在 AgentCard 上(main.py#L54-L60 的注释明确强调 "A2UI extension MUST be inside capabilities, not on AgentCard"):

capabilities=AgentCapabilities(
    streaming=True,
    push_notifications=False,
    state_transition_history=False,
    extensions=[get_a2ui_agent_extension()],
)

2. A2UI DataPart 的封装与识别

Agent 产出的 UI 通过 A2A 的 DataPart 传输,携带 metadata.mimeType = "application/json+a2ui"。相关辅助函数:

3. ClientEvent:让 UI 反向驱动 Agent

A2UI 的交互不止"渲染"一个方向,用户在界面上点击按钮、提交表单也会回传事件。executor 在遍历入站 message parts 时(agent_executor.py#L77-L91),会检查 DataPart 中是否含 userAction 字段:

  • 若含 userAction,说明是一条 A2UI ClientEvent(如按钮点击、表单提交);
  • 对 submit_form 动作,把 context 中的全部键值拼成查询:"User submitted a form with the following data: name: ..., email: ..."(agent_executor.py#L98-L101);
  • 其他动作则组装为 "User action: {action} with data: {ctx}"。

由此形成闭环:Agent 生成表单 → 用户填写提交 → ClientEvent 回传 → Agent 基于提交数据继续生成新 UI。表单提交会令任务进入 TaskState.completed,而普通交互进入 TaskState.input_required(agent_executor.py#L134-L138)。

六、Prompt 工程:Schema、模板与动态生成规则

整个 Agent 的"灵魂"在 prompt_builder.py 中,它由三部分组成。

1. A2UI JSON Schema(硬约束)

A2UI_SCHEMA 定义了 A2UI message 的合法结构,核心规则:一条消息必须且只能包含四个 action 之一——beginRendering、surfaceUpdate、dataModelUpdate、deleteSurface。各 action 要点:

Action 作用 关键字段
beginRendering 通知客户端开始渲染一个 surface surfaceId、root(根组件 ID)、styles(font、primaryColor,颜色须符合 ^#[0-9a-fA-F]{6}$)
surfaceUpdate 用一组新组件更新 surface surfaceId、components[](每个组件含 id、component,可选 weight 即 flex-grow)
dataModelUpdate 更新 surface 的数据模型 surfaceId、path、contents[](key 配 valueString/valueNumber/valueBoolean/valueMap)
deleteSurface 删除指定 surface surfaceId

在 agent.py#L96-L104,该 Schema 被加载为 JSON,并包上一层数组校验器({"type": "array", "items": single_message_schema}),因为 LLM 输出的是 A2UI message 列表;若 Schema 解析失败,Agent 会直接报告内部配置错误而不继续生成(agent.py#L165-L174)。

2. 四套示例模板(起点而非规则)

UI_EXAMPLES 内置四个模板,分别对应 Agent Card 中声明的四类技能:

  • FORM_EXAMPLE:联系人表单(标题 + 三个 TextField + 主按钮 submit_form,按钮通过 action.context 声明从数据模型 path 读取 name/email/message),并配 dataModelUpdate 初始化空值;
  • LIST_EXAMPLE:Todo 列表(List 组件用 template + dataBinding: "/items" 实现重复渲染,配合 dataModelUpdate.valueMap 提供三项数据);
  • CARD_EXAMPLE:个人资料卡片(Card 内嵌 Column,含头像 Icon、姓名、职位、Divider 分隔线、邮箱与电话行);
  • CONFIRMATION_EXAMPLE:成功确认弹窗(勾选 Icon + "Success!" 标题 + 消息与参考号)。

模板中的 {{ }} 是 Python f-string 的转义写法,实际渲染时会变成 { }。Prompt 明确要求 Agent 把模板当作起点自由修改:"Templates are examples, not strict rules - modify them freely"(agent.py#L56)。

3. 动态生成规则

get_ui_prompt() 生成的 Prompt 给出具体操作指南:

  • 加字段:新增 TextField/DateTimeInput 组件 → 加入 Column.children.explicitList → 在 dataModelUpdate.contents 补 key → 若是表单,还要把字段 path 追加到按钮 action.context;
  • 改布局:横向用 Row,纵向用 Column,重复项用 List + template;
  • 改文案:直接更新 literalString;
  • 唯一硬约束:JSON 必须通过 A2UI Schema 校验。

七、A2UI 组件清单

依据 Schema(prompt_builder.py#L70-L281)与 CLAUDE.md,Agent 可生成的组件如下:

组件 用途 关键属性/枚举
Text 展示文本 text(literalString 或数据模型 path)、usageHint:h1~h5、caption、body
Icon Material 图标 name 枚举约 30 个:accountCircle、check、close、mail、phone、settings、star 等
Row 横向布局容器 children(explicitList 或 template)、distribution、alignment
Column 纵向布局容器 同上
List 数据绑定重复项 direction: vertical/horizontal、template(componentId + dataBinding)
Card 带阴影/边框的容器 child
Divider 视觉分隔线 axis: horizontal/vertical
Button 交互按钮 child、primary、action(name + context[])
TextField 文本输入 label、text、textFieldType: shortText/longText/number/date/obscured
DateTimeInput 日期/时间选择 value、enableDate、enableTime

八、输出校验与自动重试

为保证生成的 JSON 始终可被前端渲染,UIGeneratorAgent.stream() 实现了"校验—失败—重试"闭环:

  1. 调用 Runner.run_async 流式获取响应,未完成时先产出中间进度消息("Generating your UI...",见 get_processing_message());
  2. 取到最终响应后,检查分隔符 ---a2ui_JSON--- 是否存在、JSON 部分是否为空、能否通过 jsonschema.validate(agent.py#L228-L255);
  3. 若校验失败且重试次数未耗尽(max_retries = 1,即最多两轮),会构造纠错提示重新询问 LLM:"Your previous response was invalid. {error} You MUST generate a valid response following the A2UI JSON SCHEMA."(agent.py#L277-L284);
  4. 重试耗尽仍失败,则降级返回纯文本道歉信息(agent.py#L286-L294)。

此外,agent_executor.py 在最终拆分时对单个 JSON 对象与数组两种情况都做了兼容处理(agent_executor.py#L158-L169),解析失败时会把原始 JSON 字符串降级为纯文本 Part,避免任务整体失败。

九、部署:Docker 与 Railway

Docker

Dockerfile 采用 python:3.12-slim 基础镜像:

FROM python:3.12-slim
WORKDIR /app
RUN apt-get update && apt-get install -y curl gcc && rm -rf /var/lib/apt/lists/*
COPY . .
RUN pip install --no-cache-dir .
EXPOSE 10002
CMD ["python", "-m", "agent"]

其中安装 gcc 用于编译部分依赖;EXPOSE 10002 只是声明端口,实际监听端口由运行环境注入的 PORT 环境变量决定(Click 的 envvar="PORT" 机制)。

Railway

railway.toml 声明使用 Dockerfile 构建,部署策略为 ON_FAILURE 重启、最多重试 5 次。相应地,A2A_BASE_URL 环境变量可用来覆盖 Agent Card 中对外公布的 URL(默认 http://localhost:{port},见 main.py#L118)。

十、在 CopilotKit 前端中的集成方式

该 Agent 是 generative-ui-playground 演示的"第三种生成式 UI"后端。前端集成的要点:

  • 通过 HttpAgent 连接 Python A2A 后端,目标 URL 由环境变量 A2A_AGENT_URL=http://localhost:10002 指定;
  • 前端使用 A2UIRenderer 组件渲染 Agent 返回的 A2UI 声明式 JSON;
  • 演示中与"Static + MCP Apps"选项卡共用一套界面,通过选项卡切换不同协议代理;
  • 三个服务需要同时运行:MCP Server(3001)、A2A Agent(10002)、Next.js 前端(3000)。

示例交互场景包括:"Find Italian restaurants nearby"(餐厅列表 + 预订)、"Book a table for 4"(交互式预订表单)等,完整展示了 Agent 生成列表、接收 ClientEvent、再生成表单的闭环能力。

十一、如何扩展新的 UI 模式

依据 CLAUDE.md 的扩展指南,新增 UI 模式只需两步:

  1. 在 prompt_builder.py 的 UI_EXAMPLES 中追加示例,保持 ---BEGIN 名称--- ... ---END 名称--- 的包裹格式,并保证内容符合"beginRendering → surfaceUpdate → dataModelUpdate"三消息结构:
YOUR_EXAMPLE = """
---BEGIN YOUR_EXAMPLE---
[
  { "beginRendering": { "surfaceId": "...", "root": "...", "styles": {...} } },
  { "surfaceUpdate": { "surfaceId": "...", "components": [...] } },
  { "dataModelUpdate": { "surfaceId": "...", "path": "/", "contents": [...] } }
]
---END YOUR_EXAMPLE---
"""
  1. 在 get_ui_prompt() 中引用新示例,并在 AGENT_INSTRUCTION(agent.py#L33-L68)与 Agent Card 的 skills 中补充对应的提示词与技能声明。

值得注意的是,当前 Schema 刻意"支持纯文本组件(无图片)"(见 prompt_builder.py#L8-L9 的注释),以保持灵活性;若需引入富媒体组件,需同步扩展 Schema 与前端渲染器。

小结

CopilotKit 的 a2a-agent 示例完整演示了一条"通用生成式 UI"的落地方案:以 A2A 协议承载通信、以 A2UI 声明式 JSON 表达界面、以 Google ADK + LiteLLM 驱动模型生成、以 jsonschema 兜底校验并自动重试。它既是理解 A2A/A2UI 双协议协同的极简参考实现,也是 CopilotKit 前端 A2UIRenderer + HttpAgent 对接自定义 Python Agent 的样板工程。需要深入阅读源码的读者,可以从 agent/agent.py、agent/agent_executor.py 与 agent/prompt_builder.py 三个文件入手。

登录后查看全文
CopilotKit