系统架构

深入了解 AI Router Platform 的技术架构、核心模块和数据流设计

架构概览

AI Router Platform 采用微服务架构设计,通过 API Gateway 提供统一入口,后端由多个独立服务组成, 支持水平扩展故障隔离。系统设计遵循高可用、高性能、高安全三大原则。

graph TB Client[客户端
Web/Mobile/SDK] subgraph Gateway["API Gateway 层"] APIGW[API Gateway
认证/限流/路由] end subgraph Core["核心服务层"] Router[Auto Router
智能路由] KeyPool[Key Pool
API Key 管理] Billing[Billing System
计费系统] Auth[Auth & RBAC
认证授权] end subgraph Support["辅助服务层"] Cost[Cost Monitor
成本监控] SLA[SLA Monitor
SLA 监控] Notify[Notification
通知服务] QA[Quality Assurance
质量保障] end subgraph Data["数据层"] PG[(PostgreSQL
主数据库)] Redis[(Redis
缓存)] end subgraph Providers["AI 提供商"] OpenAI[OpenAI] Anthropic[Anthropic] Google[Google] Bedrock[AWS Bedrock] Others[Others...] end Client -->|HTTPS| APIGW APIGW --> Router APIGW --> Billing APIGW --> Auth Router --> KeyPool KeyPool --> OpenAI KeyPool --> Anthropic KeyPool --> Google KeyPool --> Bedrock KeyPool --> Others Router --> Cost Router --> SLA Billing --> Notify Cost --> Notify Router --> PG Billing --> PG Auth --> PG Cost --> PG SLA --> PG APIGW --> Redis KeyPool --> Redis Router --> Redis style Client fill:#3b82f6,stroke:#2563eb,color:#fff style APIGW fill:#8b5cf6,stroke:#7c3aed,color:#fff style Router fill:#10b981,stroke:#059669,color:#fff style KeyPool fill:#10b981,stroke:#059669,color:#fff style Billing fill:#10b981,stroke:#059669,color:#fff style Auth fill:#10b981,stroke:#059669,color:#fff style Cost fill:#f59e0b,stroke:#d97706,color:#fff style SLA fill:#f59e0b,stroke:#d97706,color:#fff style Notify fill:#f59e0b,stroke:#d97706,color:#fff style QA fill:#f59e0b,stroke:#d97706,color:#fff style PG fill:#ef4444,stroke:#dc2626,color:#fff style Redis fill:#ef4444,stroke:#dc2626,color:#fff

客户端层

Web、Mobile、SDK 多端接入

网关层

统一入口、认证、限流

服务层

核心业务 + 辅助服务

数据层

持久化 + 缓存

请求数据流

从客户端发起请求到返回响应的完整数据流,展示系统各模块的协作流程。

sequenceDiagram
    participant C as 客户端
    participant GW as API Gateway
    participant Auth as 认证服务
    participant Router as 智能路由
    participant Pool as Key Pool
    participant Provider as AI Provider
    participant Billing as 计费服务
    participant DB as 数据库

    C->>GW: POST /v1/chat/completions
    GW->>Auth: 验证 API Key
    Auth->>DB: 查询用户信息
    DB-->>Auth: 返回用户数据
    Auth-->>GW: 认证通过

    GW->>Router: 智能路由请求
    Router->>DB: 获取路由策略
    DB-->>Router: 返回策略配置
    Router->>Pool: 选择最优 Provider
    Pool->>DB: 获取可用 Keys
    DB-->>Pool: 返回 Key 列表
    Pool-->>Router: 返回最优 Key

    Router->>Provider: 转发请求 (带 API Key)
    Provider-->>Router: 返回 AI 响应

    Router->>Billing: 记录使用量
    Billing->>DB: 保存计费记录

    Router-->>GW: 返回响应
    GW-->>C: 返回结果

    Note over Billing,DB: 异步处理:
成本监控、SLA 统计
1

认证验证

API Gateway 验证 JWT Token 或 API Key,确认用户身份和权限

2

智能路由

Auto Router 根据策略(成本、延迟、成功率)选择最优提供商

3

Key 选择

Key Pool 从可用 Keys 中选择健康度最高的 Key

4

请求转发

使用选定的 Provider Key 转发请求到 AI 提供商

5

计费统计

记录 Token 使用量、成本,更新用户余额

6

异步任务

更新 SLA 指标、成本监控、发送告警通知(后台任务)

核心模块

Auto Router Service

智能路由与调度引擎

智能路由服务是系统的核心组件,负责根据多维度指标(成本、延迟、成功率、负载)智能选择最优的 AI 提供商。 支持 6 种调度策略,可动态切换以满足不同场景需求。

6 种路由策略

🔄 Round Robin

轮询调度,平均分配请求到各提供商

⚖️ Weighted

加权轮询,按权重分配流量

🛡️ Failover

故障转移,主提供商失败自动切换备用

⚡ Latency Priority

延迟优先,选择响应最快的提供商

✅ Success Rate Priority

成功率优先,选择最稳定的提供商

📊 Comprehensive Score

综合评分,平衡多个指标选择最优

路由决策流程

graph LR
    A[接收请求] --> B{解析模型}
    B --> C[查询路由策略]
    C --> D{策略类型}
    D -->|综合评分| E[计算 Provider 评分]
    D -->|延迟优先| F[选择最低延迟]
    D -->|成功率优先| G[选择最高成功率]
    D -->|故障转移| H[选择主/备]
    E --> I[选择最优 Provider]
    F --> I
    G --> I
    H --> I
    I --> J[返回路由决策]

    style A fill:#3b82f6,color:#fff
    style J fill:#10b981,color:#fff
                            

技术实现

  • 文件: internal/services/auto_router.go
  • 性能指标缓存: Redis 缓存 5 分钟,减少数据库查询
  • 模型变体支持: gpt-4:openai 语法指定提供商
  • 实时指标更新: 每次请求后更新延迟、成功率统计

Key Pool Service

API Key 池管理与负载均衡

Key Pool 管理所有 Provider 的 API Keys,实现负载均衡、健康检查、自动故障转移。 所有 Keys 使用 AES-256 加密存储,确保安全性。

Key 选择流程

graph TD
    A[收到路由请求] --> B[获取 Provider Keys]
    B --> C{Keys 可用?}
    C -->|否| D[返回无可用 Key 错误]
    C -->|是| E[过滤健康 Keys]
    E --> F{健康 Keys 数量}
    F -->|0| G[尝试降级 Keys]
    F -->|>0| H[计算 Key 健康度]
    G --> I{有降级 Keys?}
    I -->|否| D
    I -->|是| H
    H --> J[选择健康度最高的 Key]
    J --> K[更新 Key 使用统计]
    K --> L[返回选定 Key]

    style A fill:#3b82f6,color:#fff
    style L fill:#10b981,color:#fff
    style D fill:#ef4444,color:#fff
                            
🔄 负载均衡

多个 Keys 轮询使用,避免单个 Key 过载

💚 健康检查

实时监控 Key 状态,自动禁用失效 Keys

🔐 加密存储

AES-256 加密,密钥环境变量管理

📊 使用统计

记录每个 Key 的成功率、延迟、使用次数

技术实现

  • 文件: internal/services/key_pool.go
  • 加密: internal/crypto/encryption.go
  • 健康度计算: 成功率 × 0.7 + (1 - 归一化延迟) × 0.3
  • 故障转移: Key 连续失败 3 次自动禁用 30 分钟

Billing System

实时计费与余额管理

计费系统实时追踪每次 API 调用的 Token 使用量,按模型定价计费,支持余额扣款、充值、发票生成等完整财务流程。

计费流程

sequenceDiagram
    participant Router as 智能路由
    participant Billing as 计费服务
    participant DB as 数据库
    participant User as 用户余额
    participant Monitor as 成本监控

    Router->>Billing: 记录使用量
(tokens, model) Billing->>DB: 查询模型定价 DB-->>Billing: 返回价格 Billing->>Billing: 计算费用
tokens × price Billing->>User: 扣减余额 User-->>Billing: 余额更新成功 Billing->>DB: 保存计费记录 Billing->>Monitor: 触发成本监控 Monitor->>Monitor: 检查预算告警 Note over Monitor: 异步任务:
告警、统计、报表
💰 实时计费

Token 级别精确计费,每次请求即时扣款

📄 自动账单

每月自动生成详细账单和发票

🔔 余额预警

余额不足自动通知,支持自动充值

💳 多种付款

支持信用卡、支付宝、微信支付

🎫 促销码

支持优惠券、促销码、折扣活动

📊 使用报表

详细的使用统计和成本分析

Auth & RBAC

认证授权与权限管理

基于角色的访问控制(RBAC)系统,支持多租户隔离、细粒度权限管理、JWT Token 认证。

RBAC 模型

graph TD User[用户] -->|belongs to| Org[组织] User -->|has| Role[角色] Role -->|has| Perm[权限] Perm -->|on| Resource[资源] subgraph Roles["内置角色"] Admin[Admin
管理员] Dev[Developer
开发者] Viewer[Viewer
查看者] end subgraph Permissions["权限类型"] Read[Read 读取] Write[Write 写入] Delete[Delete 删除] Manage[Manage 管理] end Admin -->|all| Permissions Dev -->|Read, Write| Permissions Viewer -->|Read| Permissions style User fill:#3b82f6,color:#fff style Org fill:#8b5cf6,color:#fff style Role fill:#10b981,color:#fff

👨‍💼 Admin

完整权限:管理用户、配置、计费

👨‍💻 Developer

开发权限:创建 Keys、查看日志

👀 Viewer

只读权限:查看统计和状态

技术栈

⚙️ 后端技术

  • Go 1.22+
  • Gin Web Framework
  • GORM ORM
  • JWT-Go
  • go-redis/redis/v9

💾 数据存储

  • PostgreSQL 16
  • Redis 7 (Cache & Queue)
  • AWS S3 (Logs)

🌐 前端技术

  • Tailwind CSS
  • shadcn/ui Components
  • Vanilla JavaScript

🚀 基础设施

  • Docker & Docker Compose
  • Kubernetes (K8s)
  • Nginx Load Balancer
  • Prometheus Monitoring
  • Grafana Dashboards
  • GitHub Actions CI/CD

部署架构

生产环境采用多可用区部署,通过 Kubernetes 实现自动扩缩容和故障恢复, Nginx 负载均衡器分发流量,保证 99.9%+ SLA

graph TB
    Internet[Internet]

    subgraph CDN["Cloudflare CDN"]
        CDN1[Edge Servers]
    end

    subgraph LB["Load Balancer"]
        Nginx[Nginx LB]
    end

    subgraph K8s["Kubernetes Cluster"]
        subgraph AZ1["可用区 1"]
            API1[API Gateway × 2]
            Service1[Services × 3]
        end

        subgraph AZ2["可用区 2"]
            API2[API Gateway × 2]
            Service2[Services × 3]
        end

        subgraph AZ3["可用区 3"]
            API3[API Gateway × 1]
            Service3[Services × 2]
        end
    end

    subgraph Data["数据层"]
        PG_Master[(PG Master)]
        PG_Replica1[(PG Replica)]
        PG_Replica2[(PG Replica)]
        Redis_Master[(Redis Master)]
        Redis_Sentinel1[(Redis Sentinel)]
        Redis_Sentinel2[(Redis Sentinel)]
    end

    Internet --> CDN1
    CDN1 --> Nginx
    Nginx --> API1
    Nginx --> API2
    Nginx --> API3

    API1 --> Service1
    API2 --> Service2
    API3 --> Service3

    Service1 --> PG_Master
    Service2 --> PG_Replica1
    Service3 --> PG_Replica2

    Service1 --> Redis_Master
    Service2 --> Redis_Master
    Service3 --> Redis_Master

    PG_Master -.-> PG_Replica1
    PG_Master -.-> PG_Replica2
    Redis_Sentinel1 -.-> Redis_Master
    Redis_Sentinel2 -.-> Redis_Master

    style Internet fill:#3b82f6,color:#fff
    style CDN1 fill:#f59e0b,color:#fff
    style Nginx fill:#8b5cf6,color:#fff
    style PG_Master fill:#ef4444,color:#fff
    style Redis_Master fill:#ef4444,color:#fff
                        

生产环境配置

API Gateway 实例: 5 个 (跨 3 个 AZ)
服务实例: 8 个 (每服务 2+)
PostgreSQL: 1 主 + 2 从
Redis: 哨兵模式 (3 节点)
可用区: 3 个 (us-east-1a/b/c)
自动扩缩容: HPA (CPU 70%)
备份策略: 每日全量 + 实时增量
监控: Prometheus + Grafana

设计原则

🛡️

高可用性

  • • 多副本部署,单点故障自动恢复
  • • 多可用区架构,区域级容灾
  • • 健康检查和自动故障转移
  • • 目标 SLA: 99.9%
📈

可扩展性

  • • 微服务架构,服务独立扩展
  • • 无状态设计,水平扩展
  • • Kubernetes HPA 自动扩缩容
  • • 数据库读写分离
🔐

安全性

  • • API Key AES-256 加密存储
  • • HTTPS 全站加密传输
  • • RBAC 细粒度权限控制
  • • 完整的审计日志

高性能

  • • Redis 缓存热点数据
  • • 数据库连接池复用
  • • 异步任务队列处理
  • • CDN 静态资源加速