# Coze 智能体集成指南

## 系统概述

这是一个 B2B 电商管理系统，采用 AI Agent 驱动的管理模式。系统前端使用 React + Lovable 构建，后端使用 Supabase Edge Functions，AI 编排层可通过 Coze 实现。

---

## 一、系统架构

```
┌─────────────────────────────────────────────────────────────────┐
│                        用户界面层 (Lovable)                       │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│  │ 营销工作台   │ │ 产品工作台   │ │ 财务工作台   │ │ 客服工作台   │ │
│  └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      API 网关层 (Edge Functions)                  │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│  │marketing-   │ │product-     │ │finance-     │ │service-     │ │
│  │genui        │ │genui        │ │genui        │ │genui        │ │
│  └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    AI 编排层 (Coze Orchestrator)                  │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │                     主编排工作流                              │ │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │ │
│  │  │意图识别  │→│任务分发  │→│Agent执行│→│结果聚合  │        │ │
│  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘        │ │
│  └─────────────────────────────────────────────────────────────┘ │
│  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐        │
│  │营销Agent│ │产品Agent│ │财务Agent│ │客服Agent│ │总经理Agent│    │
│  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘        │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                        数据层 (Supabase)                         │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐   │
│  │products │ │orders   │ │coupons  │ │campaigns│ │profiles │   │
│  └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘   │
└─────────────────────────────────────────────────────────────────┘
```

---

## 二、Agent 角色定义

### 2.1 营销 Agent (Marketing Agent)
```json
{
  "id": "marketing",
  "name": "营销专员",
  "emoji": "📈",
  "role": "营销活动管理",
  "responsibilities": [
    "优惠券管理 (创建、发放、统计)",
    "限时抢购活动 (flash_sales)",
    "拼团活动 (group_buy)",
    "支付有礼 (payment_gifts)",
    "跨店营销 (cross_store_promotions)",
    "营销数据分析与洞察"
  ],
  "capabilities": [
    "coupon.create", "coupon.update", "coupon.delete", "coupon.query",
    "flashSale.create", "flashSale.update", "flashSale.pause", "flashSale.resume",
    "groupBuy.create", "groupBuy.update", "groupBuy.cancel",
    "paymentGift.create", "paymentGift.update",
    "crossStore.create", "crossStore.approve", "crossStore.reject",
    "analytics.campaign", "analytics.roi"
  ]
}
```

### 2.2 产品 Agent (Product Agent)
```json
{
  "id": "product",
  "name": "产品专员",
  "emoji": "📦",
  "role": "商品管理",
  "responsibilities": [
    "商品信息管理 (上下架、编辑)",
    "库存管理",
    "品牌管理",
    "类目管理",
    "商品数据分析"
  ],
  "capabilities": [
    "product.create", "product.update", "product.delete", "product.query",
    "product.activate", "product.deactivate", "product.batchUpdate",
    "brand.create", "brand.update",
    "category.create", "category.update",
    "inventory.adjust", "inventory.alert"
  ]
}
```

### 2.3 财务 Agent (Finance Agent)
```json
{
  "id": "finance",
  "name": "财务专员",
  "emoji": "💰",
  "role": "财务管理",
  "responsibilities": [
    "订单财务审核",
    "退款处理",
    "会员充值管理",
    "财务报表",
    "资金流水"
  ],
  "capabilities": [
    "order.approve", "order.reject", "order.refund",
    "balance.query", "balance.adjust",
    "transaction.query", "transaction.export",
    "report.daily", "report.monthly", "report.custom"
  ]
}
```

### 2.4 客服 Agent (Service Agent)
```json
{
  "id": "service",
  "name": "客服专员",
  "emoji": "🎧",
  "role": "售后服务",
  "responsibilities": [
    "售后工单处理",
    "退换货审批",
    "客诉处理",
    "服务质量监控"
  ],
  "capabilities": [
    "afterSales.query", "afterSales.approve", "afterSales.reject",
    "afterSales.process", "afterSales.close",
    "refund.process", "exchange.process",
    "complaint.handle", "complaint.escalate"
  ]
}
```

### 2.5 总经理 Agent (Manager Agent)
```json
{
  "id": "manager",
  "name": "总经理",
  "emoji": "👔",
  "role": "全局管理与决策",
  "responsibilities": [
    "跨部门协调",
    "重大决策审批",
    "目标设定与追踪",
    "全局数据概览",
    "Agent 任务分配"
  ],
  "capabilities": [
    "goal.create", "goal.update", "goal.assign",
    "approval.override", "approval.delegate",
    "agent.assign", "agent.coordinate",
    "dashboard.overview", "analytics.global"
  ]
}
```

---

## 三、数据模型

### 3.1 核心业务表

#### products (商品表)
```sql
- id: UUID (主键)
- name: TEXT (商品名称)
- price: DECIMAL (价格)
- stock_quantity: INTEGER (库存)
- brand: TEXT (品牌)
- category: TEXT (类目)
- is_active: BOOLEAN (是否上架)
- is_hot: BOOLEAN (是否热销)
- is_recommended: BOOLEAN (是否推荐)
- specifications: JSONB (规格参数)
- images: TEXT[] (图片列表)
- created_at, updated_at: TIMESTAMP
```

#### orders (订单表)
```sql
- id: UUID (主键)
- order_number: TEXT (订单号)
- user_id: UUID (用户ID)
- status: TEXT (pending/paid/shipped/delivered/cancelled/refunded)
- total_amount: DECIMAL (总金额)
- shipping_address: TEXT (收货地址)
- tracking_number: TEXT (物流单号)
- notes: TEXT (备注)
- created_at, updated_at: TIMESTAMP
```

#### coupons (优惠券表)
```sql
- id: UUID (主键)
- code: TEXT (券码)
- name: TEXT (名称)
- type: TEXT (percentage/fixed)
- discount_value: DECIMAL (折扣值)
- min_purchase_amount: DECIMAL (最低消费)
- max_discount_amount: DECIMAL (最大抵扣)
- scope: TEXT (all/category/brand/product)
- scope_ids: TEXT[] (适用范围ID)
- total_quantity: INTEGER (总数量)
- used_quantity: INTEGER (已使用)
- start_date, end_date: TIMESTAMP
- status: TEXT (active/inactive/expired)
```

#### flash_sales (限时抢购)
```sql
- id: UUID (主键)
- name: TEXT (活动名称)
- product_id: UUID (商品ID)
- original_price: DECIMAL (原价)
- flash_price: DECIMAL (抢购价)
- stock_limit: INTEGER (限量)
- sold_count: INTEGER (已售)
- start_time, end_time: TIMESTAMP
- status: TEXT (draft/pending/active/ended/cancelled)
- type: TEXT (flash_sale/limited_time)
```

#### group_buy_activities (拼团活动)
```sql
- id: UUID (主键)
- name: TEXT (活动名称)
- product_id: UUID (商品ID)
- original_price: DECIMAL (原价)
- group_price: DECIMAL (拼团价)
- min_group_size: INTEGER (成团人数)
- max_group_size: INTEGER (最大人数)
- duration_hours: INTEGER (成团时限)
- stock_limit: INTEGER (限量)
- sold_count: INTEGER (已售)
- start_date, end_date: TIMESTAMP
- status: TEXT (draft/pending/active/ended)
```

#### after_sales_requests (售后工单)
```sql
- id: UUID (主键)
- order_id: UUID (订单ID)
- product_id: UUID (商品ID)
- user_id: UUID (用户ID)
- type: TEXT (refund/exchange/repair)
- reason: TEXT (原因)
- description: TEXT (描述)
- images: TEXT[] (图片)
- status: TEXT (pending/processing/approved/rejected/completed)
- refund_amount: DECIMAL (退款金额)
- admin_notes: TEXT (处理备注)
- processed_by: UUID (处理人)
- processed_at: TIMESTAMP
```

#### cross_store_promotions (跨店营销)
```sql
- id: UUID (主键)
- name: TEXT (活动名称)
- type: TEXT (joint_coupon/cross_discount/bundle_sale)
- store_ids: TEXT[] (参与店铺)
- config: JSONB (活动配置)
- total_budget: DECIMAL (总预算)
- used_budget: DECIMAL (已用预算)
- max_participants: INTEGER (最大参与数)
- current_participants: INTEGER (当前参与数)
- start_date, end_date: TIMESTAMP
- status: TEXT (draft/pending_review/approved/active/paused/ended/rejected)
- created_by: TEXT (创建者)
- reviewed_by: TEXT (审核人)
- review_notes: TEXT (审核备注)
```

#### goals (目标管理)
```sql
- id: UUID (主键)
- agent_type: TEXT (marketing/product/finance/service)
- title: TEXT (目标标题)
- description: TEXT (描述)
- target_value: DECIMAL (目标值)
- current_value: DECIMAL (当前值)
- unit: TEXT (单位)
- deadline: TIMESTAMP (截止日期)
- priority: TEXT (high/medium/low)
- status: TEXT (active/completed/overdue/cancelled)
- assigned_to: UUID (负责人)
- assigned_by: UUID (分配人)
```

---

## 四、API 接口规范

### 4.1 Edge Function 端点

| 端点 | 功能 | 请求方式 |
|------|------|---------|
| `/functions/v1/marketing-genui` | 营销 Agent UI 生成 | POST |
| `/functions/v1/marketing-operations` | 营销操作执行 | POST |
| `/functions/v1/product-genui` | 产品 Agent UI 生成 | POST |
| `/functions/v1/product-operations` | 产品操作执行 | POST |
| `/functions/v1/finance-genui` | 财务 Agent UI 生成 | POST |
| `/functions/v1/service-genui` | 客服 Agent UI 生成 | POST |
| `/functions/v1/service-operations` | 客服操作执行 | POST |
| `/functions/v1/manager-genui` | 总经理 Agent UI 生成 | POST |
| `/functions/v1/admin-ai-router` | AI 请求路由 | POST |

### 4.2 请求格式

```typescript
interface AgentRequest {
  // 用户消息
  message: string;
  
  // 会话 ID (用于上下文保持)
  conversation_id?: string;
  
  // 当前视图上下文
  context?: {
    current_view: string;      // 当前页面: dashboard/coupons/flash_sales/...
    selected_items?: string[]; // 选中的项目 ID
    filters?: Record<string, any>; // 当前筛选条件
    user_id?: string;          // 当前用户
    agent_type?: string;       // Agent 类型
  };
  
  // 操作请求 (用于执行具体操作)
  operation?: {
    type: string;              // 操作类型
    params: Record<string, any>; // 操作参数
  };
}
```

### 4.3 响应格式

```typescript
interface AgentResponse {
  // 回答文本
  answer: string;
  
  // 会话 ID
  conversation_id: string;
  
  // UI Schema (用于动态渲染)
  ui_schema?: UISchema;
  
  // 待执行的动作列表
  actions?: Action[];
  
  // 洞察数据
  insights?: Insight[];
  
  // 待审批项
  pending_approvals?: Approval[];
}
```

---

## 五、UI Schema 规范

### 5.1 组件类型

```typescript
type ComponentType = 
  | 'stats_row'      // 统计数据行
  | 'data_table'     // 数据表格
  | 'chart'          // 图表
  | 'progress_bar'   // 进度条
  | 'action_buttons' // 操作按钮
  | 'approval_card'  // 审批卡片
  | 'insight_card'   // 洞察卡片
  | 'alert_box'      // 警告框
  | 'text_block';    // 文本块
```

### 5.2 UI Schema 结构

```typescript
interface UISchema {
  components: UIComponent[];
}

interface UIComponent {
  type: ComponentType;
  props: ComponentProps;
}
```

### 5.3 组件示例

#### Stats Row (统计行)
```json
{
  "type": "stats_row",
  "props": {
    "stats": [
      {
        "label": "今日订单",
        "value": "156",
        "trend": { "value": 12.5, "direction": "up" },
        "icon": "shopping-cart"
      },
      {
        "label": "销售额",
        "value": "¥28,450",
        "trend": { "value": 8.3, "direction": "up" }
      }
    ]
  }
}
```

#### Data Table (数据表格)
```json
{
  "type": "data_table",
  "props": {
    "title": "待处理订单",
    "columns": [
      { "key": "order_number", "label": "订单号", "type": "text" },
      { "key": "amount", "label": "金额", "type": "currency" },
      { "key": "status", "label": "状态", "type": "badge" },
      { "key": "actions", "label": "操作", "type": "actions" }
    ],
    "rows": [
      {
        "id": "order-1",
        "order_number": "ORD-2024-001",
        "amount": 299.00,
        "status": "pending",
        "actions": ["approve", "reject"]
      }
    ]
  }
}
```

#### Chart (图表)
```json
{
  "type": "chart",
  "props": {
    "title": "销售趋势",
    "chartType": "line",
    "data": [
      { "label": "周一", "value": 1200 },
      { "label": "周二", "value": 1900 },
      { "label": "周三", "value": 1500 }
    ]
  }
}
```

#### Action Buttons (操作按钮)
```json
{
  "type": "action_buttons",
  "props": {
    "buttons": [
      {
        "id": "create_coupon",
        "label": "创建优惠券",
        "action": "navigate",
        "params": { "view": "coupon_create" },
        "variant": "primary"
      },
      {
        "id": "export_data",
        "label": "导出数据",
        "action": "execute",
        "params": { "operation": "export" },
        "variant": "outline"
      }
    ]
  }
}
```

#### Approval Card (审批卡片)
```json
{
  "type": "approval_card",
  "props": {
    "id": "approval-1",
    "title": "新建营销活动审批",
    "description": "双十一促销活动 - 全场8折",
    "requestedBy": "营销Agent",
    "requestedAt": "2024-01-15T10:30:00Z",
    "priority": "high",
    "details": {
      "活动类型": "限时折扣",
      "预计成本": "¥50,000",
      "预计收益": "¥200,000"
    },
    "actions": ["approve", "reject", "modify"]
  }
}
```

#### Insight Card (洞察卡片)
```json
{
  "type": "insight_card",
  "props": {
    "id": "insight-1",
    "type": "opportunity",
    "title": "发现销售增长机会",
    "content": "iPhone 15 系列库存充足但销量下滑，建议启动促销活动",
    "priority": "high",
    "metrics": [
      { "label": "当前库存", "value": "500件" },
      { "label": "周销量", "value": "23件" },
      { "label": "建议降价", "value": "10%" }
    ],
    "suggestedAction": {
      "label": "创建促销活动",
      "action": "create_flash_sale",
      "params": { "product_id": "xxx" }
    }
  }
}
```

---

## 六、动作 (Action) 规范

### 6.1 动作类型

```typescript
interface Action {
  type: 'page_action' | 'data_action' | 'agent_action';
  action: string;
  params: Record<string, any>;
  requiresApproval?: boolean;
  priority?: 'high' | 'medium' | 'low';
}
```

### 6.2 页面动作 (page_action)

用于 UI 导航和显示控制：

```typescript
// 导航到指定页面
{
  type: 'page_action',
  action: 'navigate',
  params: { view: 'coupons' }
}

// 打开创建表单
{
  type: 'page_action',
  action: 'open_dialog',
  params: { dialog: 'create_coupon' }
}

// 刷新数据
{
  type: 'page_action',
  action: 'refresh',
  params: { target: 'data_table' }
}

// 应用筛选
{
  type: 'page_action',
  action: 'filter',
  params: { status: 'active', date_range: 'this_week' }
}
```

### 6.3 数据动作 (data_action)

用于数据操作：

```typescript
// 创建优惠券
{
  type: 'data_action',
  action: 'coupon.create',
  params: {
    name: '新用户专享',
    type: 'percentage',
    discount_value: 20,
    min_purchase_amount: 100
  }
}

// 审批活动
{
  type: 'data_action',
  action: 'flashSale.approve',
  params: { id: 'xxx', notes: '同意上线' }
}

// 处理退款
{
  type: 'data_action',
  action: 'order.refund',
  params: { order_id: 'xxx', amount: 299.00, reason: '客户取消' }
}
```

### 6.4 Agent 动作 (agent_action)

用于 Agent 间协作：

```typescript
// 分配任务给其他 Agent
{
  type: 'agent_action',
  action: 'assign_task',
  params: {
    target_agent: 'marketing',
    task: 'create_promotion',
    context: { product_id: 'xxx' }
  }
}

// 请求审批
{
  type: 'agent_action',
  action: 'request_approval',
  params: {
    approver: 'manager',
    item_type: 'campaign',
    item_id: 'xxx'
  }
}

// 发送通知
{
  type: 'agent_action',
  action: 'notify',
  params: {
    target_agents: ['finance', 'service'],
    message: '大额退款已处理',
    priority: 'high'
  }
}
```

---

## 七、Coze 工作流设计建议

### 7.1 主编排工作流

```
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│  接收请求    │────▶│  意图识别    │────▶│  路由分发    │
└─────────────┘     └─────────────┘     └─────────────┘
                                              │
        ┌─────────────────────────────────────┼─────────────────────────────────────┐
        ▼                   ▼                 ▼                   ▼                 ▼
┌─────────────┐     ┌─────────────┐   ┌─────────────┐   ┌─────────────┐   ┌─────────────┐
│ 营销 Agent   │     │ 产品 Agent   │   │ 财务 Agent   │   │ 客服 Agent   │   │ 总经理 Agent │
└─────────────┘     └─────────────┘   └─────────────┘   └─────────────┘   └─────────────┘
        │                   │                 │                   │                 │
        └─────────────────────────────────────┼─────────────────────────────────────┘
                                              ▼
                                      ┌─────────────┐
                                      │  结果聚合    │
                                      └─────────────┘
                                              │
                                              ▼
                                      ┌─────────────┐
                                      │  格式化输出   │
                                      └─────────────┘
```

### 7.2 意图识别 Prompt

```
你是一个 B2B 电商系统的意图识别器。根据用户消息识别意图并分配给合适的 Agent。

可用的 Agent:
- marketing: 营销相关（优惠券、促销、活动）
- product: 产品相关（商品、库存、品牌、类目）
- finance: 财务相关（订单、退款、账单、报表）
- service: 客服相关（售后、投诉、退换货）
- manager: 全局管理（目标、审批、协调、分析）

用户消息: {message}
当前上下文: {context}

请返回 JSON 格式:
{
  "intent": "string (具体意图)",
  "target_agent": "string (目标Agent)",
  "entities": { ... },
  "requires_multi_agent": boolean,
  "secondary_agents": ["string"]
}
```

### 7.3 Agent 执行 Prompt 模板

```
你是{agent_name}，负责{responsibilities}。

## 你的能力
{capabilities}

## 当前数据上下文
{data_context}

## 当前目标
{current_goals}

## 用户请求
{user_message}

## 输出要求
请生成符合规范的响应，包含:
1. answer: 对用户的回答
2. ui_schema: 需要展示的 UI 组件
3. actions: 需要执行的动作
4. insights: 发现的洞察

输出 JSON 格式...
```

---

## 八、与 Lovable 前端集成

### 8.1 调用流程

```typescript
// 1. 前端发送请求到 Edge Function
const response = await supabase.functions.invoke('admin-ai-router', {
  body: {
    message: userMessage,
    conversation_id: conversationId,
    context: {
      current_view: 'dashboard',
      agent_type: 'marketing'
    }
  }
});

// 2. Edge Function 调用 Coze API
// 在 Edge Function 中:
const cozeResponse = await fetch('https://api.coze.com/...', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${COZE_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    bot_id: 'your_bot_id',
    user: userId,
    query: message,
    stream: false,
    conversation_id: conversationId
  })
});

// 3. 解析 Coze 响应并返回给前端
const result = await cozeResponse.json();
return {
  answer: result.messages[0].content,
  ui_schema: JSON.parse(result.ui_schema),
  actions: JSON.parse(result.actions)
};
```

### 8.2 前端渲染

```typescript
// 使用 DynamicRenderer 渲染 UI Schema
import { DynamicRenderer } from '@/ai/genui';

function AgentWorkbench({ response }) {
  const handleAction = (action) => {
    if (action.type === 'page_action') {
      executePageAction(action);
    } else if (action.type === 'data_action') {
      executeDataAction(action);
    }
  };

  return (
    <div>
      <div className="answer">{response.answer}</div>
      <DynamicRenderer 
        schema={response.ui_schema} 
        onAction={handleAction}
      />
    </div>
  );
}
```

---

## 九、环境变量配置

在 Supabase Edge Functions 中配置:

```bash
# Coze API 配置
COZE_API_KEY=your_coze_api_key
COZE_BOT_ID=your_main_orchestrator_bot_id

# Agent Bot IDs (可选，如果使用多 Bot 架构)
COZE_MARKETING_BOT_ID=xxx
COZE_PRODUCT_BOT_ID=xxx
COZE_FINANCE_BOT_ID=xxx
COZE_SERVICE_BOT_ID=xxx
COZE_MANAGER_BOT_ID=xxx
```

---

## 十、最佳实践

### 10.1 会话管理
- 使用 `conversation_id` 保持上下文连续性
- 定期清理过期会话
- 跨 Agent 会话需要传递完整上下文

### 10.2 错误处理
- Coze API 超时：设置合理的超时时间（30s）
- 格式解析错误：使用 fallback 默认响应
- 权限校验：在执行 data_action 前验证权限

### 10.3 性能优化
- 使用流式响应提升用户体验
- 缓存常用查询结果
- 批量处理多个操作

### 10.4 安全考虑
- 敏感操作需要二次确认
- 大额操作需要审批流程
- 记录所有操作日志

---

## 附录：完整 API 示例

### A. 营销查询示例

**请求:**
```json
{
  "message": "帮我查看本周优惠券使用情况",
  "context": {
    "current_view": "dashboard",
    "agent_type": "marketing"
  }
}
```

**期望响应:**
```json
{
  "answer": "本周优惠券使用情况如下：共发放 1,234 张，使用 567 张，使用率 45.9%。「新用户专享」券使用率最高达 78%。",
  "ui_schema": {
    "components": [
      {
        "type": "stats_row",
        "props": {
          "stats": [
            { "label": "发放总量", "value": "1,234", "trend": { "value": 15, "direction": "up" } },
            { "label": "使用数量", "value": "567" },
            { "label": "使用率", "value": "45.9%" },
            { "label": "带来销售额", "value": "¥89,450" }
          ]
        }
      },
      {
        "type": "data_table",
        "props": {
          "title": "优惠券明细",
          "columns": [
            { "key": "name", "label": "券名称" },
            { "key": "issued", "label": "发放" },
            { "key": "used", "label": "使用" },
            { "key": "rate", "label": "使用率" }
          ],
          "rows": [
            { "name": "新用户专享", "issued": 500, "used": 390, "rate": "78%" },
            { "name": "满100减20", "issued": 734, "used": 177, "rate": "24%" }
          ]
        }
      }
    ]
  },
  "insights": [
    {
      "type": "suggestion",
      "title": "优化建议",
      "content": "「满100减20」使用率偏低，建议调整门槛或增加推广"
    }
  ]
}
```

---

*文档版本: 1.0*
*最后更新: 2026-01-04*
