OmniCS / docs /ARCHITECTURE.md
qf46578's picture
🦞 Add: docs/ARCHITECTURE.md
2fab4bf verified
|
Raw History Blame
23.8 kB

OmniCS - 企业级电商智能客服系统

项目概述

名称: OmniCS (Omni-channel Customer Service)
定位: 企业级多平台电商智能客服系统
启动日期: 2026-02-16


一、系统架构

┌─────────────────────────────────────────────────────────────────┐
│                        Electron Client                          │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐           │
│  │ 淘宝千牛  │ │ 京东京麦  │ │ 拼多多   │ │ 闲鱼/小红书│           │
│  │ 自动化   │ │ 自动化   │ │ 自动化   │ │ 自动化    │           │
│  └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘           │
│       │            │            │            │                  │
│       └────────────┴────────────┴────────────┘                  │
│                         │                                       │
│                    ┌────▼────┐                                  │
│                    │ OCR引擎 │                                  │
│                    └────┬────┘                                  │
│                    ┌────▼────┐                                  │
│                    │自动化引擎│                                  │
│                    └────┬────┘                                  │
└─────────────────────────┼───────────────────────────────────────┘
                          │ WebSocket / REST API
                          ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Node.js Backend                            │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐           │
│  │ 消息路由  │ │ 知识库   │ │ 大模型   │ │ 敏感词   │           │
│  │ 服务    │ │ 服务     │ │ 服务     │ │ 检测服务  │           │
│  └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘           │
│       │            │            │            │                  │
│       └────────────┴────────────┴────────────┘                  │
│                         │                                       │
│                    ┌────▼────┐                                  │
│                    │ 角色管理 │                                  │
│                    │ 服务    │                                  │
│                    └────┬────┘                                  │
└─────────────────────────┼───────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────────┐
│                      PostgreSQL                                 │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐           │
│  │ 用户表   │ │ 会话表   │ │ 消息表   │ │ 知识库表  │           │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘           │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐           │
│  │ 角色表   │ │ 平台表   │ │ 敏感词表  │ │ 日志表   │           │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘           │
└─────────────────────────────────────────────────────────────────┘

二、核心模块设计

2.1 消息处理流程

客户消息
    │
    ▼
┌─────────────┐
│ 关键词检测   │──触发──▶ 转人工/子账号
└──────┬──────┘
       │ 未触发
       ▼
┌─────────────────────────────┐
│    并行处理 (Race)           │
│  ┌─────────┐  ┌─────────┐   │
│  │知识库检索│  │大模型生成│   │
│  └────┬────┘  └────┬────┘   │
└───────┼────────────┼────────┘
        │            │
        ▼            ▼
   ┌────────────────────┐
   │ 知识库有答案?      │
   │ ──是──▶ 使用知识库 │
   │ ──否──▶ 使用大模型 │
   └─────────┬──────────┘
             │
             ▼
   ┌────────────────────┐
   │ 敏感词/违禁词检测   │
   └─────────┬──────────┘
             │
       ┌─────┴─────┐
       │           │
    通过         不通过
       │           │
       ▼           ▼
   发送消息   重新生成+提示

2.2 平台适配器模式

每个电商平台实现统一的接口:

interface PlatformAdapter {
  // 初始化
  init(): Promise<void>;
  
  // 获取客户列表
  getCustomerList(): Promise<Customer[]>;
  
  // 获取客户消息
  getMessages(customerId: string): Promise<Message[]>;
  
  // 发送消息
  sendMessage(customerId: string, message: string): Promise<void>;
  
  // 转人工
  transferToHuman(customerId: string, subAccount: string): Promise<void>;
  
  // OCR识别区域配置
  getOCRRegions(): OCRRegions;
}

2.3 角色系统设计

interface Role {
  id: string;
  name: string;           // 老板、销售、客服、财务、运营、剪辑、售后、人力
  permissions: string[];  // 权限列表
  knowledgeBases: string[]; // 关联的知识库
  systemPrompt: string;   // 角色提示词
  responseStyle: ResponseStyle;
  transferRules: TransferRule[]; // 转接规则
}

interface ResponseStyle {
  tone: 'formal' | 'casual' | 'friendly' | 'professional';
  maxLength: number;
  emojiUsage: boolean;
  signature: string;
}

三、数据库设计

3.1 核心表结构

-- 用户表
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  username VARCHAR(50) UNIQUE NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  role_id UUID REFERENCES roles(id),
  platform_accounts JSONB, -- 平台账号绑定
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 角色表
CREATE TABLE roles (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name VARCHAR(50) NOT NULL,
  display_name VARCHAR(100),
  permissions JSONB,
  system_prompt TEXT,
  response_style JSONB,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 平台配置表
CREATE TABLE platforms (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name VARCHAR(50) NOT NULL, -- taobao, jd, pdd, xianyu, xiaohongshu, wechat
  display_name VARCHAR(100),
  adapter_class VARCHAR(100),
  config JSONB,
  ocr_regions JSONB,
  automation_config JSONB,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 会话表
CREATE TABLE conversations (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  platform_id UUID REFERENCES platforms(id),
  customer_id VARCHAR(100) NOT NULL,
  customer_name VARCHAR(200),
  customer_avatar VARCHAR(500),
  status VARCHAR(20) DEFAULT 'active', -- active, waiting, closed, transferred
  assigned_user_id UUID REFERENCES users(id),
  assigned_role_id UUID REFERENCES roles(id),
  last_message_at TIMESTAMP,
  unread_count INTEGER DEFAULT 0,
  metadata JSONB,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 消息表
CREATE TABLE messages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  conversation_id UUID REFERENCES conversations(id),
  direction VARCHAR(10) NOT NULL, -- inbound, outbound
  content TEXT NOT NULL,
  content_type VARCHAR(20) DEFAULT 'text', -- text, image, product, order
  sender_type VARCHAR(20), -- customer, agent, system
  sender_id VARCHAR(100),
  ai_generated BOOLEAN DEFAULT false,
  knowledge_source VARCHAR(100), -- 知识库来源
  sensitivity_check_passed BOOLEAN,
  sensitivity_issues JSONB,
  metadata JSONB,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 知识库表
CREATE TABLE knowledge_bases (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name VARCHAR(100) NOT NULL,
  description TEXT,
  category VARCHAR(50), -- product, policy, faq, common
  embedding_model VARCHAR(50),
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 知识条目表
CREATE TABLE knowledge_items (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  knowledge_base_id UUID REFERENCES knowledge_bases(id),
  question TEXT NOT NULL,
  answer TEXT NOT NULL,
  keywords VARCHAR[],
  embedding vector(1536), -- OpenAI embedding dimension
  category VARCHAR(50),
  tags VARCHAR[],
  usage_count INTEGER DEFAULT 0,
  effectiveness_score DECIMAL(3,2),
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 敏感词表
CREATE TABLE sensitive_words (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  word VARCHAR(100) NOT NULL,
  category VARCHAR(50), -- sensitive, prohibited, advertising
  severity INTEGER DEFAULT 1, -- 1-5
  replacement VARCHAR(100),
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 关键词触发规则表
CREATE TABLE keyword_rules (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  keywords VARCHAR[] NOT NULL,
  action VARCHAR(20) NOT NULL, -- transfer, alert, block
  transfer_to_role_id UUID REFERENCES roles(id),
  transfer_to_user_id UUID REFERENCES users(id),
  sub_account VARCHAR(100),
  priority INTEGER DEFAULT 0,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 操作日志表
CREATE TABLE operation_logs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES users(id),
  action VARCHAR(50) NOT NULL,
  entity_type VARCHAR(50),
  entity_id UUID,
  details JSONB,
  ip_address VARCHAR(45),
  user_agent VARCHAR(500),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- AI生成记录表
CREATE TABLE ai_generation_logs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  message_id UUID REFERENCES messages(id),
  model VARCHAR(50),
  prompt TEXT,
  response TEXT,
  knowledge_used JSONB,
  generation_time_ms INTEGER,
  tokens_used INTEGER,
  sensitivity_passed BOOLEAN,
  retry_count INTEGER DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3.2 索引设计

CREATE INDEX idx_conversations_platform_customer ON conversations(platform_id, customer_id);
CREATE INDEX idx_conversations_status ON conversations(status);
CREATE INDEX idx_messages_conversation ON messages(conversation_id, created_at);
CREATE INDEX idx_knowledge_items_embedding ON knowledge_items USING ivfflat (embedding vector_cosine_ops);
CREATE INDEX idx_sensitive_words_word ON sensitive_words(word);
CREATE INDEX idx_keyword_rules_keywords ON keyword_rules USING gin(keywords);

四、API设计

4.1 RESTful API

# 认证
POST   /api/auth/login
POST   /api/auth/logout
GET    /api/auth/me

# 用户管理
GET    /api/users
POST   /api/users
GET    /api/users/:id
PUT    /api/users/:id
DELETE /api/users/:id

# 角色管理
GET    /api/roles
POST   /api/roles
GET    /api/roles/:id
PUT    /api/roles/:id
DELETE /api/roles/:id

# 平台管理
GET    /api/platforms
GET    /api/platforms/:id
PUT    /api/platforms/:id
POST   /api/platforms/:id/connect
DELETE /api/platforms/:id/disconnect

# 会话管理
GET    /api/conversations
GET    /api/conversations/:id
PUT    /api/conversations/:id
POST   /api/conversations/:id/transfer
POST   /api/conversations/:id/close

# 消息管理
GET    /api/conversations/:id/messages
POST   /api/conversations/:id/messages
POST   /api/conversations/:id/messages/ai-generate

# 知识库管理
GET    /api/knowledge-bases
POST   /api/knowledge-bases
GET    /api/knowledge-bases/:id
PUT    /api/knowledge-bases/:id
DELETE /api/knowledge-bases/:id

GET    /api/knowledge-bases/:id/items
POST   /api/knowledge-bases/:id/items
PUT    /api/knowledge-items/:id
DELETE /api/knowledge-items/:id
POST   /api/knowledge-bases/:id/batch-import

# 敏感词管理
GET    /api/sensitive-words
POST   /api/sensitive-words
PUT    /api/sensitive-words/:id
DELETE /api/sensitive-words/:id

# 关键词规则
GET    /api/keyword-rules
POST   /api/keyword-rules
PUT    /api/keyword-rules/:id
DELETE /api/keyword-rules/:id

# 统计分析
GET    /api/stats/overview
GET    /api/stats/conversations
GET    /api/stats/messages
GET    /api/stats/knowledge
GET    /api/stats/ai-usage

4.2 WebSocket事件

# 客户端发送
conversation:join        # 加入会话房间
conversation:leave       # 离开会话房间
message:send            # 发送消息
message:typing          # 正在输入

# 服务端推送
conversation:new        # 新会话
conversation:update     # 会话更新
message:new             # 新消息
message:status          # 消息状态
customer:typing         # 客户正在输入
alert:triggered         # 关键词告警

五、Electron自动化模块

5.1 千牛客户端自动化流程

1. 检测千牛进程是否运行
2. 设置千牛为右下角弹窗模式
3. 轮询检测新消息弹窗
4. OCR识别弹窗内容获取客户信息
5. 模拟点击进入聊天界面
6. OCR识别客户消息区域
7. 处理消息并生成回复
8. 模拟点击输入框
9. 模拟输入回复内容
10. 模拟点击发送按钮
11. 返回轮询状态

5.2 OCR区域配置

interface OCRRegions {
  // 弹窗区域
  popup: { x: number; y: number; width: number; height: number };
  
  // 客户消息区域
  customerMessages: { x: number; y: number; width: number; height: number };
  
  // 输入框区域
  inputBox: { x: number; y: number; width: number; height: number };
  
  // 发送按钮区域
  sendButton: { x: number; y: number; width: number; height: number };
  
  // 自己发送的消息区域(排除)
  ownMessages: { x: number; y: number; width: number; height: number };
}

5.3 自动化控制

interface AutomationController {
  // 截屏
  captureScreen(region?: Region): Promise<Buffer>;
  
  // OCR识别
  recognizeText(image: Buffer): Promise<OCRResult>;
  
  // 模拟鼠标移动
  moveTo(x: number, y: number): Promise<void>;
  
  // 模拟点击
  click(x: number, y: number, button?: 'left' | 'right'): Promise<void>;
  
  // 模拟输入
  type(text: string): Promise<void>;
  
  // 模拟快捷键
  hotKey(keys: string[]): Promise<void>;
  
  // 查找图片
  findImage(template: Buffer): Promise<{ x: number; y: number } | null>;
  
  // 等待元素出现
  waitForImage(template: Buffer, timeout?: number): Promise<{ x: number; y: number }>;
}

六、大模型集成

6.1 支持的模型

模型 提供商 API 说明
豆包 字节跳动 豆包API 主力模型
通义千问 阿里云 阿里云API 备用模型
文心一言 百度 百度API 备用模型
DeepSeek DeepSeek DeepSeek API 复杂推理

6.2 提示词模板

const SYSTEM_PROMPT_TEMPLATE = `
你是{company_name}的{role_name}。

## 角色设定
{role_description}

## 回复风格
- 语调: {tone}
- 最大长度: {maxLength}字
- 表情使用: {emojiUsage ? "适度使用" : "不使用"}
- 落款: {signature}

## 知识上下文
{knowledge_context}

## 对话历史
{conversation_history}

## 客户消息
{customer_message}

## 敏感词限制
以下词汇禁止在回复中出现: {sensitive_words}

请根据以上信息生成专业、友好的回复。
`;

const RETRY_PROMPT_TEMPLATE = `
你上一次的回复包含敏感词: {detected_words}
请重新生成回复,确保不包含这些词汇。

原客户消息: {customer_message}
知识上下文: {knowledge_context}

请重新生成回复。
`;

七、敏感词检测

7.1 检测流程

interface SensitivityCheckResult {
  passed: boolean;
  detected: Array<{
    word: string;
    category: string;
    severity: number;
    position: [number, number];
  }>;
  sanitizedText?: string;
}

async function checkSensitivity(text: string): Promise<SensitivityCheckResult> {
  // 1. 精确匹配敏感词
  // 2. 模糊匹配(编辑距离)
  // 3. 拼音检测
  // 4. 正则规则检测
  // 5. AI辅助检测
}

7.2 敏感词分类

sensitive:
  - 政治敏感词
  - 色情词汇
  - 暴力词汇
  - 歧视词汇

prohibited:
  - 竞品名称
  - 外部联系方式
  - 价格承诺超限
  - 虚假宣传词汇

advertising:
  - 绝对化用语(最、第一、唯一)
  - 限时限量的虚假表述

八、知识库设计

8.1 知识库结构

知识库
├── 产品知识
│   ├── 商品介绍
│   ├── 规格参数
│   ├── 使用说明
│   └── 常见问题
├── 政策规则
│   ├── 退换货政策
│   ├── 物流政策
│   ├── 促销规则
│   └── 会员规则
├── 服务流程
│   ├── 下单流程
│   ├── 支付流程
│   ├── 发货流程
│   └── 售后流程
├── 常见问题
│   ├── 售前咨询
│   ├── 售中服务
│   └── 售后问题
└── 话术模板
    ├── 问候语
    ├── 推荐话术
    ├── 催付话术
    └── 道歉话术

8.2 检索策略

interface KnowledgeSearchStrategy {
  // 关键词精确匹配
  exactMatch(query: string): Promise<KnowledgeItem[]>;
  
  // 向量相似度检索
  vectorSearch(query: string, topK: number): Promise<KnowledgeItem[]>;
  
  // 混合检索(关键词+向量)
  hybridSearch(query: string): Promise<KnowledgeItem[]>;
  
  // 分类过滤
  categoryFilter(items: KnowledgeItem[], category: string): KnowledgeItem[];
}

九、部署架构

9.1 云端部署

┌─────────────────────────────────────────────────────────────┐
│                      负载均衡器                              │
└─────────────────────────┬───────────────────────────────────┘
                          │
          ┌───────────────┼───────────────┐
          │               │               │
          ▼               ▼               ▼
    ┌──────────┐    ┌──────────┐    ┌──────────┐
    │ Node.js  │    │ Node.js  │    │ Node.js  │
    │ 实例 1   │    │ 实例 2   │    │ 实例 3   │
    └────┬─────┘    └────┬─────┘    └────┬─────┘
         │               │               │
         └───────────────┼───────────────┘
                         │
                         ▼
              ┌─────────────────────┐
              │    PostgreSQL       │
              │   (主从复制)        │
              └─────────────────────┘
                         │
                         ▼
              ┌─────────────────────┐
              │     Redis           │
              │   (缓存/队列)       │
              └─────────────────────┘

9.2 Docker部署

version: '3.8'
services:
  app:
    build: ./backend
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/omics
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=omics
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
    volumes:
      - pgdata:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    volumes:
      - redisdata:/data

volumes:
  pgdata:
  redisdata:

十、开发计划

Phase 1: 基础架构 (Week 1-2)

  • 项目初始化
  • 数据库设计与迁移
  • 后端API框架搭建
  • 前端项目初始化
  • Electron应用基础

Phase 2: 核心功能 (Week 3-4)

  • 用户认证系统
  • 角色权限管理
  • 消息处理流程
  • WebSocket实时通信

Phase 3: 平台适配 (Week 5-6)

  • 千牛客户端自动化
  • OCR识别模块
  • 模拟操作模块
  • 多平台适配器

Phase 4: AI能力 (Week 7-8)

  • 知识库系统
  • 大模型集成
  • 敏感词检测
  • 关键词触发

Phase 5: 优化部署 (Week 9-10)

  • 性能优化
  • 日志监控
  • 部署上线
  • 压力测试

十一、技术选型详情

前端技术栈

{
  "react": "^18.2.0",
  "typescript": "^5.0.0",
  "electron": "^28.0.0",
  "antd": "^5.12.0",
  "zustand": "^4.4.0",
  "react-query": "^5.0.0",
  "socket.io-client": "^4.6.0"
}

后端技术栈

{
  "node": ">=20.0.0",
  "express": "^4.18.0",
  "typescript": "^5.0.0",
  "typeorm": "^0.3.0",
  "pg": "^8.11.0",
  "redis": "^4.6.0",
  "socket.io": "^4.6.0",
  "bullmq": "^4.0.0"
}

自动化技术栈

{
  "robotjs": "^0.10.0",
  "nut-js": "^4.0.0",
  "tesseract.js": "^5.0.0",
  "sharp": "^0.33.0",
  "screenshot-desktop": "^1.15.0"
}

文档版本: 1.0.0 最后更新: 2026-02-16