# Gen UI API 调用指南

本文档说明如何从 Dify/Coze Agent 调用 Gen UI Edge Functions，实现动态 UI 生成。

## 概述

Gen UI 系统允许 AI Agent 通过 HTTP API 调用，返回结构化的 UI Schema，前端根据 Schema 动态渲染界面组件。

```
用户输入 → Dify/Coze Agent → HTTP 调用 Edge Function → 返回 UI Schema JSON → Agent 返回给前端 → 渲染 UI
```

## 可用的 Gen UI Endpoints

| Agent 类型 | Endpoint | 用途 |
|-----------|----------|------|
| 商品管理 | `/functions/v1/product-genui` | 商品数据分析、库存管理、商品列表 |
| 营销管理 | `/functions/v1/marketing-genui` | 营销活动、优惠券、促销分析 |
| 财务管理 | `/functions/v1/finance-genui` | 财务报表、订单统计、会员分析 |
| 客服管理 | `/functions/v1/service-genui` | 售后工单、客户服务、订单发货 |
| 总经理 | `/functions/v1/manager-genui` | 全局概览、跨部门分析 |

## API 调用规范

### 请求格式

```http
POST https://{SUPABASE_PROJECT_ID}.supabase.co/functions/v1/{agent}-genui
Content-Type: application/json
Authorization: Bearer {SUPABASE_ANON_KEY}
```

### 请求体 (Request Body)

```json
{
  "message": "用户的自然语言输入",
  "conversation_id": "可选，会话ID用于上下文保持",
  "context": {
    "current_page": "当前页面，如 products, orders",
    "selected_items": ["选中的项目ID列表"],
    "filters": {
      "category": "筛选分类",
      "status": "筛选状态",
      "date_range": {
        "start": "2024-01-01",
        "end": "2024-01-31"
      }
    }
  }
}
```

### 响应格式 (Response)

```json
{
  "answer": "AI 的文字回复，解释数据或操作结果",
  "ui_schema": {
    "version": "1.0",
    "layout": "vertical",
    "gap": "md",
    "components": [
      {
        "type": "stats_row",
        "props": {
          "items": [
            { "label": "总商品", "value": 156, "trend": "+12%", "trendDirection": "up" }
          ]
        }
      }
    ]
  },
  "insights": [
    {
      "id": "insight_1",
      "type": "warning",
      "title": "库存预警",
      "description": "5款商品库存低于安全线"
    }
  ],
  "suggested_actions": [
    "查看低库存商品",
    "分析销售趋势",
    "导出商品报表"
  ],
  "conversation_id": "conv_xxx"
}
```

## 可用的 UI 组件类型

### 1. 统计行 (stats_row)

显示关键指标的统计卡片行。

```json
{
  "type": "stats_row",
  "props": {
    "items": [
      {
        "label": "今日销售额",
        "value": "¥12,580",
        "trend": "+15.2%",
        "trendDirection": "up",
        "color": "success",
        "icon": "TrendingUp"
      },
      {
        "label": "待发货订单",
        "value": 23,
        "color": "warning",
        "icon": "Package"
      }
    ],
    "columns": 4
  }
}
```

**Props 说明:**
- `items`: 统计项数组
  - `label`: 指标名称
  - `value`: 指标值（字符串或数字）
  - `trend`: 趋势文本，如 "+15%"
  - `trendDirection`: "up" | "down" | "neutral"
  - `color`: "default" | "success" | "warning" | "error" | "info"
  - `icon`: Lucide 图标名称
- `columns`: 每行显示列数（2-6）

### 2. 数据表格 (data_table)

展示列表数据的交互式表格。

```json
{
  "type": "data_table",
  "props": {
    "title": "商品列表",
    "columns": [
      { "key": "name", "label": "商品名称", "type": "text" },
      { "key": "price", "label": "价格", "type": "number" },
      { "key": "stock", "label": "库存", "type": "number" },
      { "key": "status", "label": "状态", "type": "status" }
    ],
    "data": [
      { "id": "p1", "name": "iPhone 15", "price": 5999, "stock": 50, "status": "active" },
      { "id": "p2", "name": "MacBook Pro", "price": 14999, "stock": 5, "status": "low_stock" }
    ],
    "actions": [
      { "id": "edit", "label": "编辑", "action": "product.edit", "icon": "Edit" },
      { "id": "delete", "label": "删除", "action": "product.delete", "variant": "destructive" }
    ],
    "pagination": true,
    "pageSize": 10
  }
}
```

**Props 说明:**
- `title`: 表格标题
- `columns`: 列定义数组
  - `key`: 数据字段名
  - `label`: 列标题
  - `type`: "text" | "number" | "date" | "status" | "action"
  - `width`: 可选，列宽度
- `data`: 数据行数组，每行必须有 `id` 字段
- `actions`: 行操作按钮
- `pagination`: 是否分页
- `pageSize`: 每页条数

### 3. 图表 (chart)

数据可视化图表。

```json
{
  "type": "chart",
  "props": {
    "title": "销售趋势",
    "type": "line",
    "data": [
      { "label": "1月", "value": 12000 },
      { "label": "2月", "value": 15000 },
      { "label": "3月", "value": 18000 }
    ],
    "xKey": "label",
    "yKey": "value",
    "height": 300
  }
}
```

**Props 说明:**
- `title`: 图表标题
- `type`: "bar" | "line" | "pie" | "area"
- `data`: 数据点数组
- `xKey`: X 轴数据字段
- `yKey`: Y 轴数据字段
- `height`: 图表高度（像素）

### 4. 警告框 (alert)

显示重要提示或警告信息。

```json
{
  "type": "alert",
  "props": {
    "type": "warning",
    "title": "库存不足警告",
    "description": "以下5款商品库存低于安全阈值，建议尽快补货。",
    "dismissible": true
  }
}
```

**Props 说明:**
- `type`: "info" | "warning" | "success" | "error"
- `title`: 标题
- `description`: 详细描述
- `dismissible`: 是否可关闭

### 5. 操作按钮组 (action_buttons)

一组可点击的操作按钮。

```json
{
  "type": "action_buttons",
  "props": {
    "buttons": [
      {
        "id": "export",
        "label": "导出报表",
        "action": "report.export",
        "variant": "default",
        "icon": "Download"
      },
      {
        "id": "refresh",
        "label": "刷新数据",
        "action": "data.refresh",
        "variant": "outline",
        "icon": "RefreshCw"
      }
    ],
    "layout": "horizontal",
    "align": "right"
  }
}
```

**Props 说明:**
- `buttons`: 按钮数组
  - `id`: 按钮唯一标识
  - `label`: 按钮文本
  - `action`: 点击触发的动作标识
  - `variant`: "default" | "secondary" | "destructive" | "outline" | "ghost"
  - `icon`: Lucide 图标名称
  - `disabled`: 是否禁用
  - `params`: 传递给动作的参数对象
- `layout`: "horizontal" | "vertical"
- `align`: "left" | "center" | "right"

### 6. 审批卡片 (approval_card)

用于展示待审批项目。

```json
{
  "type": "approval_card",
  "props": {
    "data": {
      "id": "approval_1",
      "title": "新品上架审批",
      "description": "iPhone 16 Pro Max 需要审批上架",
      "type": "product_launch",
      "priority": "high",
      "createdAt": "2024-01-15T10:30:00Z",
      "metadata": {
        "product_name": "iPhone 16 Pro Max",
        "price": 9999
      }
    },
    "onApprove": "approval.approve",
    "onReject": "approval.reject"
  }
}
```

### 7. 洞察卡片 (insight_card)

展示 AI 生成的数据洞察。

```json
{
  "type": "insight_card",
  "props": {
    "data": {
      "id": "insight_1",
      "type": "warning",
      "title": "销售下滑预警",
      "description": "本周销售额较上周下降12%，主要受影响品类为手机配件。",
      "action": {
        "id": "view_details",
        "label": "查看详情",
        "action": "insight.view_details"
      }
    }
  }
}
```

### 8. 进度条 (progress_bar)

显示目标完成进度。

```json
{
  "type": "progress_bar",
  "props": {
    "label": "月度销售目标",
    "value": 75000,
    "max": 100000,
    "showPercentage": true,
    "color": "success"
  }
}
```

### 9. 文本块 (text)

富文本内容展示。

```json
{
  "type": "text",
  "props": {
    "content": "## 数据分析摘要\n\n本月销售表现良好，以下是关键发现：",
    "variant": "body"
  }
}
```

**Props 说明:**
- `content`: 文本内容（支持 Markdown）
- `variant`: "h1" | "h2" | "h3" | "h4" | "body" | "caption" | "muted"

### 10. 容器 (container)

用于组合多个组件的布局容器。

```json
{
  "type": "container",
  "props": {
    "layout": "grid",
    "columns": 2,
    "gap": "md",
    "children": [
      { "type": "chart", "props": { ... } },
      { "type": "chart", "props": { ... } }
    ]
  }
}
```

**Props 说明:**
- `layout`: "vertical" | "horizontal" | "grid"
- `columns`: Grid 布局时的列数
- `gap`: "sm" | "md" | "lg"
- `children`: 子组件数组

## 意图识别关键词

为帮助 Agent 正确识别用户意图，以下是各类操作的关键词映射：

### 商品管理 (product-genui)

| 意图 | 关键词 |
|-----|--------|
| dashboard | 概览, 仪表盘, 首页, 工作台, 总览 |
| products_list | 商品列表, 所有商品, 商品管理, 查看商品 |
| low_stock | 库存不足, 低库存, 缺货, 库存预警, 补货 |
| categories | 分类, 品类, 商品分类, 类目 |
| brands | 品牌, 品牌管理, 品牌列表 |
| analytics | 分析, 报表, 统计, 数据分析, 趋势 |
| new_products | 新品, 新上架, 最新商品 |
| hot_products | 热销, 爆款, 畅销, 热门 |

### 营销管理 (marketing-genui)

| 意图 | 关键词 |
|-----|--------|
| dashboard | 营销概览, 活动总览 |
| campaigns | 营销活动, 促销活动, 活动列表 |
| coupons | 优惠券, 券管理, 发券 |
| flash_sales | 秒杀, 限时抢购, 闪购 |
| group_buy | 拼团, 团购活动 |
| analytics | 营销分析, 活动效果, ROI |

### 财务管理 (finance-genui)

| 意图 | 关键词 |
|-----|--------|
| dashboard | 财务概览, 收支总览 |
| orders | 订单统计, 销售额, 收入 |
| refunds | 退款, 退货统计 |
| membership | 会员, VIP, 会员分析 |
| transactions | 交易记录, 流水, 账单 |

### 客服管理 (service-genui)

| 意图 | 关键词 |
|-----|--------|
| dashboard | 客服概览, 服务总览 |
| after_sales | 售后, 退换货, 工单 |
| pending_orders | 待发货, 待处理订单 |
| complaints | 投诉, 差评, 客诉 |

## Dify HTTP Action 配置示例

在 Dify 中配置 HTTP Action 调用 Gen UI：

```yaml
name: call_product_genui
description: 调用商品管理 Gen UI 获取动态界面
method: POST
url: https://{PROJECT_ID}.supabase.co/functions/v1/product-genui
headers:
  Content-Type: application/json
  Authorization: Bearer {SUPABASE_ANON_KEY}
body:
  type: json
  content: |
    {
      "message": "{{user_input}}",
      "context": {
        "current_page": "{{current_page}}"
      }
    }
```

## Coze 插件配置示例

```json
{
  "name": "ProductGenUI",
  "description": "商品管理动态UI生成",
  "api": {
    "url": "https://{PROJECT_ID}.supabase.co/functions/v1/product-genui",
    "method": "POST",
    "headers": {
      "Content-Type": "application/json",
      "Authorization": "Bearer {{SUPABASE_ANON_KEY}}"
    }
  },
  "parameters": [
    {
      "name": "message",
      "type": "string",
      "required": true,
      "description": "用户输入的自然语言消息"
    },
    {
      "name": "context",
      "type": "object",
      "required": false,
      "description": "上下文信息"
    }
  ]
}
```

## 完整调用示例

### 示例 1: 查询库存不足商品

**请求:**
```json
{
  "message": "显示库存不足的商品",
  "context": {
    "current_page": "products"
  }
}
```

**响应:**
```json
{
  "answer": "发现 5 款商品库存低于安全阈值，请及时补货。",
  "ui_schema": {
    "version": "1.0",
    "layout": "vertical",
    "gap": "md",
    "components": [
      {
        "type": "alert",
        "props": {
          "type": "warning",
          "title": "库存预警",
          "description": "以下商品库存不足，建议尽快补货"
        }
      },
      {
        "type": "data_table",
        "props": {
          "title": "低库存商品",
          "columns": [
            { "key": "name", "label": "商品名称" },
            { "key": "stock", "label": "当前库存" },
            { "key": "min_stock", "label": "安全库存" }
          ],
          "data": [
            { "id": "1", "name": "iPhone 15 Pro", "stock": 3, "min_stock": 10 },
            { "id": "2", "name": "AirPods Pro", "stock": 5, "min_stock": 20 }
          ]
        }
      },
      {
        "type": "action_buttons",
        "props": {
          "buttons": [
            { "id": "restock", "label": "批量补货", "action": "stock.restock" }
          ]
        }
      }
    ]
  },
  "insights": [
    {
      "id": "1",
      "type": "warning",
      "title": "iPhone 15 Pro 即将断货",
      "description": "当前库存仅剩 3 件，预计 2 天内售罄"
    }
  ],
  "suggested_actions": [
    "查看销售趋势",
    "设置补货提醒",
    "联系供应商"
  ]
}
```

### 示例 2: 查看销售分析

**请求:**
```json
{
  "message": "展示本月销售趋势分析",
  "context": {
    "current_page": "analytics"
  }
}
```

**响应:**
```json
{
  "answer": "本月销售总额 ¥156,800，较上月增长 12.5%。",
  "ui_schema": {
    "version": "1.0",
    "layout": "vertical",
    "components": [
      {
        "type": "stats_row",
        "props": {
          "items": [
            { "label": "本月销售额", "value": "¥156,800", "trend": "+12.5%", "trendDirection": "up", "color": "success" },
            { "label": "订单数", "value": 234, "trend": "+8%", "trendDirection": "up" },
            { "label": "客单价", "value": "¥670", "trend": "-2%", "trendDirection": "down", "color": "warning" }
          ]
        }
      },
      {
        "type": "chart",
        "props": {
          "title": "日销售趋势",
          "type": "area",
          "data": [
            { "date": "1日", "sales": 5200 },
            { "date": "2日", "sales": 6100 },
            { "date": "3日", "sales": 4800 }
          ],
          "xKey": "date",
          "yKey": "sales",
          "height": 300
        }
      }
    ]
  }
}
```

## 错误处理

当调用失败时，响应格式：

```json
{
  "error": true,
  "message": "错误描述",
  "code": "ERROR_CODE"
}
```

常见错误码：
- `UNAUTHORIZED`: 认证失败
- `INVALID_REQUEST`: 请求格式错误
- `INTERNAL_ERROR`: 服务器内部错误

## 最佳实践

1. **始终传递 context**: 上下文信息帮助生成更相关的 UI
2. **保持 conversation_id**: 用于多轮对话的上下文保持
3. **处理 insights**: 将洞察信息展示给用户
4. **提供 suggested_actions**: 作为快捷操作按钮展示
5. **响应式设计**: UI Schema 组件会自动适配移动端

## 版本更新

- v1.0: 初始版本，支持基础组件
- v1.1: 新增 agent_status, agent_capabilities 组件
- v1.2: 新增 sandbox_result 组件
