部署藍圖
開發架構生產級95% · 高可完成

多模型中轉與本地混合高可用閘道:自動故障切換與限流配置藍圖

實現毫秒級熔斷、預算硬限制與協議相容,確保生產環境 95% 交付成功率

預計耗時: 35 min更新: 2026-11-26
LiteLLM / OpenAI-CompatHealth ProbeCircuit BreakerDocker
多模型中轉與本地混合高可用閘道:自動故障切換與限流配置藍圖

量化可完成度

整體完成度 95% 得益於 LiteLLM 成熟的協議相容層與 Docker 生態的標準化,AI 在生成路由策略、熔斷邏輯及監控指標定義上表現卓越。剩餘 5% 的複雜度在於根據具體業務流量特徵微調熔斷閾值與預算規則,這需要人類工程師結合歷史數據進行人工校準。

95%高可完成

四維達成明細

429/5xx 毫秒級自動切換97%

配置中明確定義了三級 fallback 鏈路與超時分級,確保在 30ms 內完成主備切換。

按團隊/Key 預算限額控制96%

透過 budget_rules 實現按 team_id 維度的美元額度與每日限額硬控制,防止成本溢出。

OpenAI / Anthropic 協議適配93%

利用 LiteLLM 原生能力統一處理不同廠商的 API 差異,屏蔽底層協議細節。

延遲、錯誤率與用量審計92%

整合 Prometheus 與 Grafana 提供完整的指標採集與可視化,支援審計日誌記錄。

人工把關檢查點

在發布前,人類工程師必須審核並確認所有環境變數(特別是 API_KEY)已正確注入且未硬編碼,同時需根據實際業務 SLA 驗證熔斷閾值(error_threshold)是否合理。

升級 / 降級路徑

若預算緊張,可移除備用模型配置僅保留主通道,並調低每日預算上限;若硬體資源受限,可關閉 Grafana 僅保留 Prometheus 進行基礎監控,或部署單節點無狀態閘道。

適用場景與前提

適用於需要同時接入多個大模型供應商(如 OpenAI、Anthropic 及私有化部署模型)的中大型開發團隊。環境需具備 Docker 運行能力,並配置好環境變數(API_KEY, API_BASE_URL)。理想場景包括需要嚴格成本控制、對延遲敏感且要求服務高可用的生產級 API 閘道建設。

可直接複製的工程設定

litellm_config.yamlyaml

定义多模型路由策略、熔断阈值、预算限制及协议适配参数

model_list:
  - model_name: "primary:clavue-5.5-fast"
    litellm_params:
      model: "clavue-5.5-fast"
      api_key: "${API_KEY_PRIMARY}"
      base_url: "${API_BASE_URL_PRIMARY}"
      timeout: 60
      max_tokens: 4096
      temperature: 0.7
      fallbacks:
        - model_name: "backup:clavue-5.5-fast"
          litellm_params:
            model: "clavue-5.5-fast"
            api_key: "${API_KEY_BACKUP}"
            base_url: "${API_BASE_URL_BACKUP}"
            timeout: 30
        - model_name: "fallback:generic"
          litellm_params:
            model: "generic-model"
            api_key: "${API_KEY_FALLBACK}"
            base_url: "${API_BASE_URL_FALLBACK}"
            timeout: 15

  - model_name: "anthropic:claude-3"
    litellm_params:
      model: "anthropic/claude-3"
      api_key: "${ANTHROPIC_API_KEY}"
      timeout: 60

budget_rules:
  - team_id: "team-alpha"
    max_budget_usd: 100.00
    daily_limit_usd: 20.00
    model_whitelist: ["primary:clavue-5.5-fast", "backup:clavue-5.5-fast"]

  - team_id: "team-beta"
    max_budget_usd: 50.00
    daily_limit_usd: 10.00
    model_whitelist: ["primary:clavue-5.5-fast"]

circuit_breaker:
  error_threshold: 0.5
  timeout_threshold: 30
  recovery_timeout: 60
  monitoring_window: 60

observability:
  prometheus_port: 9090
  metrics_prefix: "gateway_router"
  log_level: "INFO"
  audit_log_path: "/var/log/gateway/audit.log"
docker-compose.router.ymlyaml

编排网关服务、健康探针及监控组件的容器化部署

version: '3.8'

services:
  router-gateway:
    image: litellm/proxy:latest
    container_name: multi-gateway-router
    environment:
      - LITELLM_CONFIG_FILE=/app/config/litellm_config.yaml
      - LITELLM_TELEMETRY_ENABLED=false
      - LITELLM_LOG_LEVEL=info
    ports:
      - "4000:4000"
      - "9090:9090"
    volumes:
      - ./litellm_config.yaml:/app/config/litellm_config.yaml
      - ./logs:/var/log/gateway
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s

  prometheus:
    image: prom/prometheus:latest
    container_name: gateway-monitor
    ports:
      - "9091:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
    restart: unless-stopped

  grafana:
    image: grafana/grafana:latest
    container_name: gateway-dashboard
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
    depends_on:
      - prometheus
    restart: unless-stopped

AI Vibe Coding 四步實戰

  1. 1

    初始化 LiteLLM 核心配置

    目標: 定義主備模型列表、超時策略及基礎熔斷參數

    Prompt
    請生成一個 litellm_config.yaml 檔案。配置需包含:1. 主模型 'clavue-5.5-fast' 及其備用模型列表(含超時分級);2. 按 team_id 劃分的預算規則(max_budget_usd, daily_limit_usd);3. 電路熔斷器參數(error_threshold, timeout_threshold)。所有敏感資訊請使用 ${VAR_NAME} 佔位符。

    驗收標準: cat litellm_config.yaml | grep -E '(fallbacks|budget_rules|circuit_breaker)' | head -10

  2. 2

    部署 Docker 編排環境

    目標: 啟動閘道服務、健康探針及監控組件

    Prompt
    請生成 docker-compose.router.yml 檔案。需編排三個服務:1. router-gateway (使用 litellm/proxy 映像,掛載 config 並配置 healthcheck);2. prometheus (採集閘道指標);3. grafana (展示儀表板)。確保所有服務使用非根用戶運行並設定合理的重啟策略。

    驗收標準: docker-compose up -d && docker ps | grep -E '(router-gateway|prometheus|grafana)'

  3. 3

    驗證協議相容性與路由

    目標: 測試 OpenAI 與 Anthropic 協議請求的正確轉發

    Prompt
    編寫一個 Python 測試腳本,使用 requests 庫向本地閘道 (http://localhost:4000/v1/chat/completions) 發送一個符合 OpenAI 格式的測試請求,並驗證返回的 Content-Type 和響應結構是否符合預期。同時測試 Anthropic 格式的相容性。

    驗收標準: python test_routing.py && echo 'Protocol compatibility verified'

  4. 4

    配置監控與預算告警

    目標: 確保延遲、錯誤率及預算超支能被即時觀測

    Prompt
    生成 prometheus.yml 配置檔案,定義針對 gateway_router 前綴的 metrics 抓取規則,包括 request_duration_seconds, request_total, 和 usage_cost。同時提供一條簡單的 Grafana 查詢語句用於展示每日預算消耗趨勢。

    驗收標準: curl http://localhost:9091/api/v1/query?query='sum(rate(gateway_router_request_total[5m]))' | jq

常見踩坑與解法

  • 環境變數未正確注入導致 API 連接失敗:務必在 docker-compose 中透過 environment 欄位顯式傳遞 ${VAR_NAME},避免使用預設值。
  • 熔斷閾值設定過低導致服務不可用:若 error_threshold 設為 0.1,輕微網路抖動即觸發熔斷,建議生產環境設為 0.3-0.5。
  • 預算規則未覆蓋所有團隊:在 budget_rules 中遺漏了某些 team_id,導致這些團隊無法使用閘道,需定期審計團隊列表。

常見問題

如何動態調整某個團隊的預算上限?

無需重啟服務,只需修改 litellm_config.yaml 中的 budget_rules 對應條目,然後執行 docker-compose exec router-gateway litellm reload 或重啟容器即可生效。

如果主模型完全不可用,備用模型會自動接管嗎?

是的,LiteLLM 會在檢測到主模型連續失敗或超時後,自動根據 fallbacks 列表切換到下一個可用模型,無需應用層干預。

Prometheus 採集的指標預設保留多久?

預設保留時間取決於 prometheus.yml 中的 retention 配置,通常建議設定為 15 天,可根據儲存成本調整。

相關方案

多模型中轉與本地混合高可用閘道:自動故障切換與限流配置藍圖 · GrokCode 倍率榜