跳到正文
分析 / HiA2UI Team

使用 A2UI 构建数据仪表盘 Agent

创建能够生成交互式仪表盘的 AI Agent 分步教程。学习组合图表组件、数据绑定和流式更新。

使用 A2UI 构建数据仪表盘 Agent

目标:构建一个能够分析数据并通过动态、交互式图表呈现发现的 AI Agent。

[!NOTE] [!NOTE] **2026 年 8 月更新:**A2UI 基础 Catalog 不保证提供完整图表组件。本文中的图表应实现为宿主自有的自定义 Catalog,并按实际 Schema 校验。

我们要构建什么

一个”分析师 Agent”,能够:

  1. 接受自然语言查询,如”显示 Q4 收入趋势”。
  2. 处理数据并选择适当的可视化类型。
  3. 使用 A2UI 组件渲染交互式图表。

前提条件

  • React 18+ 配合 TypeScript
  • 已安装 A2UI SDK (npm install @a2ui/react)
  • 一个图表库(我们使用 Chart.js)

[!TIP] 正在使用 Vercel AI SDK? 您无需放弃现有的技术栈。阅读我们的指南:如何在 Vercel AI SDK 中使用 A2UI,实现两全其美。

第一步:定义图表组件

首先,创建一个 Agent 可以调用的可复用图表组件。

// components/DashboardChart.tsx
import { Bar, Line, Pie } from 'react-chartjs-2';

interface ChartProps {
  title: string;
  chartType: 'bar' | 'line' | 'pie';
  data: {
    labels: string[];
    datasets: {
      label: string;
      data: number[];
      color: string;
    }[];
  };
}

export function DashboardChart({ title, chartType, data }: ChartProps) {
  const chartData = {
    labels: data.labels,
    datasets: data.datasets.map(ds => ({
      label: ds.label,
      data: ds.data,
      backgroundColor: ds.color,
      borderColor: ds.color,
    })),
  };

  const ChartComponent = { bar: Bar, line: Line, pie: Pie }[chartType];

  return (
    <div className="bg-gray-900 p-6 rounded-xl border border-white/10">
      <h3 className="text-xl font-bold text-white mb-4">{title}</h3>
      <ChartComponent data={chartData} />
    </div>
  );
}

第二步:注册到 A2UI

将图表组件添加到注册表中,以便 Agent 可以使用它。

// registry.ts
import { createRegistry } from '@a2ui/react';
import { DashboardChart } from './components/DashboardChart';

export const registry = createRegistry({
  'dashboard-chart': DashboardChart,
  // ... 其他组件
});

第三步:配置 Agent 提示词

教会 LLM 如何使用图表组件。

SYSTEM_PROMPT = """
你是一个数据分析助手。当用户请求数据可视化时:

1. 分析数据结构。
2. 选择最佳图表类型:
   - `bar`: 用于跨类别比较。
   - `line`: 用于时间趋势。
   - `pie`: 用于整体比例。
3. 使用以下 JSON 结构响应:

{
  "type": "dashboard-chart",
  "props": {
    "title": "图表标题",
    "chartType": "bar|line|pie",
    "data": {
      "labels": ["标签1", "标签2", ...],
      "datasets": [{
        "label": "系列名称",
        "data": [10, 20, 30, ...],
        "color": "#6366f1"
      }]
    }
  }
}
"""

第四步:处理流式更新

对于大型数据集,逐步流式传输数据。

// 使用 A2UI 流式传输
<AIOutput
  messages={messages}
  registry={registry}
  onPartialUpdate={(partial) => {
    // 处理部分图表数据
    console.log('流式更新:', partial);
  }}
/>

对话示例

用户:“显示 2024 年各地区的销售业绩。”

Agent 响应

{
  "type": "dashboard-chart",
  "props": {
    "title": "2024 年各地区销售业绩",
    "chartType": "bar",
    "data": {
      "labels": ["北美", "欧洲", "亚太", "拉美"],
      "datasets": [{
        "label": "收入(百万美元)",
        "data": [45, 38, 52, 18],
        "color": "#10b981"
      }]
    }
  }
}

最佳实践

  1. 始终验证数据:确保数组长度匹配。
  2. 使用颜色令牌:在设计系统中定义调色板。
  3. 添加加载状态:数据流式传输时显示骨架屏。
  4. 优雅处理错误:为格式错误的数据显示后备 UI。

tutorialdashboardcharts