AI Agent 时代下的智能表单交互:深入解析 A2UI 协议与 Formily 融合实践

前言

在 AI Agent 快速发展的今天,如何让大语言模型(LLM)生成丰富、交互性强的用户界面,已成为前端领域的重要课题。Google 近期开源的 A2UI(Agent-to-User Interface)协议为这一难题提供了全新的解决思路。与此同时,阿里开源的 Formily 作为业界领先的动态表单解决方案,在企业级表单场景中积累了丰富的实践经验。

本文将带您深入理解 A2UI 协议的设计理念,并探讨如何结合 Formily 构建智能化的表单交互体验。

什么是 A2UI 协议?

A2UI 是 Google 开源的 Agent-to-User Interface 协议,旨在解决 AI Agent 如何"说话"并生成丰富的用户界面这一核心问题。

核心定位

传统 AI Agent 主要通过文本与用户交互,而 A2UI 让 Agent 能够发送声明式的 JSON 格式描述 UI,客户端通过渲染器将抽象的组件描述映射为原生界面组件。这种方式确保了Agent 生成的 UI 如同数据一样安全,但表达力如代码般丰富

核心理念

A2UI 协议的设计遵循三大核心原则:

特性 描述
安全优先 A2UI 是声明式数据格式,而非可执行代码。客户端维护一个"组件目录",Agent 只能请求渲染目录中的组件
LLM 友好 UI 表示为扁平化的组件列表,带有 ID 引用,LLM 易于增量生成,支持渐进式渲染
框架无关 同一套 A2UI JSON 可以在 Web(Lit、React)、Flutter、SwiftUI 等多种平台上渲染

架构概览

┌─────────────┐    A2UI JSON     ┌─────────────┐
│   Agent     │ ───────────────▶ │   Client    │
│ (Gemini/    │                  │  Renderer   │
│  LLM)       │                  │             │
└─────────────┘                  └─────────────┘
                                         │
                                         ▼
                              ┌─────────────────────┐
                              │  Native Components  │
                              │ (Web/Flutter/Swift) │
                              └─────────────────────┘

Formily:企业级动态表单解决方案

Formily 是阿里巴巴开源的动态表单解决方案,专为复杂业务场景设计,支撑了阿里内部大量中后台系统的表单需求。

核心优势

能力 说明
声明式 Schema 支持 JSON Schema 和 Markup Schema 两种方式定义表单
跨端支持 React、Vue 2、Vue 3、React Native
高性能 响应式系统只更新变化的组件,支持虚拟滚动
可视化设计器 支持拖拽式表单构建

典型使用示例

import { createForm, onFieldValueChange } from '@formily/core';
import { FormProvider, createSchemaField } from '@formily/react';
import { FormItem, Input, Select } from '@formily/antd';

// 1. 创建表单实例
const form = createForm({
  effects: () => {
    // 2. 声明式联动逻辑
    onFieldValueChange('country', (field) => {
      field.query('city').take((cityField) => {
        cityField.loading = true;
        // 动态加载城市列表
        setTimeout(() => {
          cityField.dataSource = getCitiesByCountry(field.value);
          cityField.loading = false;
        }, 500);
      });
    });
  },
});

// 3. 定义 Schema
const schema = {
  type: 'object',
  properties: {
    country: {
      type: 'string',
      title: '国家',
      enum: [
        { label: '中国', value: 'cn' },
        { label: '美国', value: 'us' },
      ],
      'x-decorator': 'FormItem',
      'x-component': 'Select',
    },
    city: {
      type: 'string',
      title: '城市',
      'x-decorator': 'FormItem',
      'x-component': 'Select',
    },
  },
};

const SchemaField = createSchemaField({
  components: { FormItem, Input, Select },
});

export default () => (
  <FormProvider form={form}>
    <SchemaField schema={schema} />
  </FormProvider>
);

A2UI + Formily:智能表单的融合实践

方案设计思路

将 A2UI 协议与 Formily 结合,可以实现以下场景:

  1. Agent 驱动的动态表单生成:LLM 根据用户意图生成 Formily Schema
  2. 渐进式表单渲染:A2UI 的增量更新特性 + Formily 的响应式更新
  3. 智能化表单交互:结合 AI 能力实现智能推荐、自动填充

核心实现方案

第一步:定义 A2UI 到 Formily 的映射规则
// a2ui-to-formily-mapper.js

const componentMapping = {
  'text-field': {
    component: 'Input',
    decorator: 'FormItem',
  },
  'number-field': {
    component: 'InputNumber',
    decorator: 'FormItem',
  },
  'select-field': {
    component: 'Select',
    decorator: 'FormItem',
  },
  'date-picker': {
    component: 'DatePicker',
    decorator: 'FormItem',
  },
  'checkbox': {
    component: 'Checkbox',
    decorator: 'FormItem',
  },
  'radio-group': {
    component: 'Radio.Group',
    decorator: 'FormItem',
  },
};

export function mapA2UIToFormily(a2uiComponents) {
  const properties = {};
  
  a2uiComponents.forEach((comp) => {
    const mapping = componentMapping[comp.type] || {
      component: 'Input',
      decorator: 'FormItem',
    };
    
    properties[comp.id] = {
      type: comp.type === 'number-field' ? 'number' : 'string',
      title: comp.label,
      description: comp.helpText,
      'x-decorator': mapping.decorator,
      'x-component': mapping.component,
      'x-component-props': {
        placeholder: comp.placeholder,
        ...comp.props,
      },
      required: comp.required,
      ...(comp.validation && {
        validate: comp.validation,
      }),
    };
  });
  
  return {
    type: 'object',
    properties,
  };
}
第二步:构建 Agent 服务端
# agent_service.py
from google import generativeai
import json

class FormAgent:
    def __init__(self, api_key: str):
        generativeai.configure(api_key=api_key)
        self.model = generativeai.GenerativeModel('gemini-2.0-flash')
    
    def generate_form_schema(self, user_intent: str, context: dict) -> dict:
        """根据用户意图生成 Formily Schema"""
        
        prompt = f"""
        用户需求:{user_intent}
        上下文信息:{context}
        
        请生成一个 Formily JSON Schema,遵循以下规范:
        1. 使用标准的 Formily Schema 格式
        2. 包含合适的表单项:Input, Select, DatePicker, InputNumber 等
        3. 包含必要的联动逻辑
        4. 添加合适的校验规则
        
        只返回 JSON,不要其他内容。
        """
        
        response = self.model.generate_content(prompt)
        
        try:
            return json.loads(response.text)
        except:
            return self._get_fallback_schema()
    
    def generate_a2ui_response(self, user_intent: str, context: dict) -> dict:
        """生成 A2UI 格式的响应"""
        
        prompt = f"""
        用户需求:{user_intent}
        
        请生成 A2UI 格式的 UI 描述,遵循 A2UI 规范:
        - 使用 type 字段指定组件类型
        - 使用 id 字段作为唯一标识
        - 使用 label 字段指定显示标签
        - 使用 placeholder 字段指定占位符
        - 必要时添加 required 和 validation 规则
        
        A2UI 支持的组件类型:
        - text-field: 文本输入
        - number-field: 数字输入
        - select-field: 下拉选择
        - date-picker: 日期选择
        - checkbox: 复选框
        - radio-group: 单选组
        
        只返回 JSON 数组格式,不要其他内容。
        """
        
        response = self.model.generate_content(prompt)
        
        try:
            return json.loads(response.text)
        except:
            return []
第三步:前端集成实现
// SmartFormRenderer.jsx
import React, { useState, useEffect } from 'react';
import { createForm } from '@formily/core';
import { FormProvider, createSchemaField } from '@formily/react';
import { FormItem, Input, Select, DatePicker, InputNumber, Checkbox } from '@formily/antd';
import { mapA2UIToFormily } from './a2ui-to-formily-mapper';

const SchemaField = createSchemaField({
  components: {
    FormItem,
    Input,
    Select,
    DatePicker,
    InputNumber,
    Checkbox,
  },
});

export const SmartFormRenderer = ({ a2uiComponents, onSubmit, initialValues }) => {
  const [formSchema, setFormSchema] = useState(null);
  const [form, setForm] = useState(null);

  // 将 A2UI 组件转换为 Formily Schema
  useEffect(() => {
    if (a2uiComponents && a2uiComponents.length > 0) {
      const schema = mapA2UIToFormily(a2uiComponents);
      setFormSchema(schema);
      
      // 创建表单实例
      const formInstance = createForm({
        initialValues,
        onSubmit: (values) => {
          onSubmit?.(values);
        },
      });
      setForm(formInstance);
    }
  }, [a2uiComponents, initialValues]);

  if (!formSchema || !form) {
    return <div>加载表单中...</div>;
  }

  return (
    <FormProvider form={form}>
      <SchemaField schema={formSchema} />
    </FormProvider>
  );
};

典型应用场景

场景一:智能旅游预订表单
// Agent 生成的 A2UI 描述
const travelBookingA2UI = [
  {
    id: 'destination',
    type: 'select-field',
    label: '目的地',
    required: true,
    options: [
      { label: '日本', value: 'japan' },
      { label: '泰国', value: 'thailand' },
      { label: '新加坡', value: 'singapore' },
    ],
  },
  {
    id: 'departure-date',
    type: 'date-picker',
    label: '出发日期',
    required: true,
  },
  {
    id: 'return-date',
    type: 'date-picker',
    label: '返回日期',
    required: true,
  },
  {
    id: 'travelers',
    type: 'number-field',
    label: '出行人数',
    required: true,
    min: 1,
    max: 10,
  },
  {
    id: 'budget',
    type: 'select-field',
    label: '预算范围',
    options: [
      { label: '5000元以下', value: 'low' },
      { label: '5000-10000元', value: 'medium' },
      { label: '10000-20000元', value: 'high' },
      { label: '20000元以上', value: 'luxury' },
    ],
  },
  {
    id: 'special-requirements',
    type: 'text-field',
    label: '特殊要求',
    placeholder: '请输入您的特殊需求,如无障碍设施、亲子游等',
  },
];
场景二:企业级审批流程表单
const approvalFormA2UI = [
  {
    id: 'applicant-name',
    type: 'text-field',
    label: '申请人姓名',
    required: true,
  },
  {
    id: 'department',
    type: 'select-field',
    label: '所属部门',
    required: true,
  },
  {
    id: 'expense-type',
    type: 'select-field',
    label: '费用类型',
    required: true,
    options: [
      { label: '差旅费', value: 'travel' },
      { label: '办公用品', value: 'supplies' },
      { label: '业务招待', value: 'entertainment' },
      { label: '培训费', value: 'training' },
    ],
  },
  {
    id: 'amount',
    type: 'number-field',
    label: '金额(元)',
    required: true,
    min: 0,
  },
  {
    id: 'description',
    type: 'text-field',
    label: '费用说明',
    required: true,
    multiline: true,
  },
  {
    id: 'attachments',
    type: 'file-upload',
    label: '附件',
  },
];

方案优势总结

维度 传统方案 A2UI + Formily 方案
表单生成 开发者手动编写 Agent 根据意图自动生成
动态性 需预定义所有字段 支持运行时动态调整
智能化 无 AI 能力 支持智能推荐、自动填充
跨平台 需针对各平台适配 统一协议,一次生成多端渲染
安全性 存在 XSS 等风险 声明式数据格式,组件白名单

常见问题

Q1: A2UI 和 A2A 协议是什么关系?

A2A(Agent-to-Agent)是 Agent 之间的通信协议,而 A2UI 是 Agent 到用户界面的协议。两者可以结合使用:A2A 用于 Agent 之间的任务分发,A2UI 用于呈现结果。

Q2: Formily 的性能如何保证?

Formily 采用响应式设计,核心基于细粒度依赖追踪,只更新变化的字段。同时支持虚拟滚动,可轻松处理上千字段的大型表单。

Q3: 如何保证 Agent 生成表单的安全性?

A2UI 的设计本身即考虑安全性:只传输声明式数据,组件必须在客户端白名单中,不支持执行任意代码。结合 Formily 的组件映射,可完全掌控可渲染的表单元素。

总结

A2UI 协议为 AI Agent 时代的 UI 交互提供了标准化的解决方案,而 Formily 作为企业级表单的成熟实践,提供了完整的表单能力。结合两者,我们可以构建出既智能又安全的动态表单系统:

  • 对开发者:减少重复劳动,让 Agent 参与表单生成
  • 对用户:获得更智能、更个性化的表单交互体验
  • 对企业:平衡创新与安全,快速响应业务需求

随着 AI Agent 技术的持续发展,表单交互将进入一个新的智能化时代。掌握 A2UI 与 Formily 的融合方案,将帮助我们在这一变革中占据先机。

参考资源

  • A2UI 官方文档:https://a2ui.org/
  • A2UI GitHub 仓库:https://github.com/google/A2UI
  • Formily 官方文档:https://formilyjs.org/
  • Formily GitHub 仓库:https://github.com/alibaba/formily

相关文章推荐:

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐