统一 LLM API 网关 — 多 Provider 容灾切换,一行代码接入
DeepSeek 挂了?自动切通义千问。通义千问限速?切 OpenAI。
你是不是也遇到过这些情况:
- DeepSeek API 超时,整个应用卡住
- 通义千问限速,排队等待
- 想同时用 DeepSeek(便宜)和 GPT-4o(质量好),但代码里要写两套逻辑
- 每个月 API 花了多少钱,完全没概念
LLM Gateway 解决这些问题:在你的应用和 LLM Provider 之间加一层,自动处理容灾、路由、统计。
你的应用 → LLM Gateway (localhost:8000) → DeepSeek / 通义千问 / OpenAI
↓ 某个挂了自动切到下一个
git clone https://github.com/Vincent-crypto-coder/llm-gateway.git
cd llm-gateway
pip install -r requirements.txtcp config.example.yaml config.yaml
# 编辑 config.yaml,填入你的 API Keypython -m gateway --config config.yaml --port 8000你的代码一行不用改,只改 base_url:
from openai import OpenAI
client = OpenAI(
api_key="any-key",
base_url="http://localhost:8000/v1" # 指向 Gateway
)
# 正常使用,Gateway 自动路由
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "你好"}]
)
print(response.choices[0].message.content)# config.yaml
failover:
strategy: priority # priority / round-robin / lowest-latency
failure_threshold: 3 # 连续失败 3 次后标记不可用
recovery_interval: 300 # 5 分钟后自动恢复三种策略:
- priority:按优先级顺序,最高优先级的 Provider 挂了才切下一个
- round-robin:轮流调用,负载均衡
- lowest-latency:选延迟最低的 Provider
所有 OpenAI 兼容的 API 都能接入:
| Provider | 模型 | 价格(每 1M tokens) |
|---|---|---|
| DeepSeek | deepseek-chat | ¥1 / ¥2 |
| 通义千问 | qwen-turbo | ¥0.3 / ¥0.6 |
| 通义千问 | qwen-plus | ¥0.8 / ¥2.0 |
| OpenAI | gpt-4o-mini | ¥1.08 / ¥4.32 |
| 智谱 | glm-4-flash | 免费 |
| Kimi | moonshot-v1-8k | ¥12 / ¥12 |
# 查看统计
curl http://localhost:8000/stats?days=7返回:
{
"period_days": 7,
"total": {
"total_requests": 1234,
"total_tokens": 567890,
"total_cost": 12.34,
"avg_latency": 856.2
},
"by_provider": [
{"provider": "deepseek", "requests": 800, "cost": 8.5},
{"provider": "dashscope", "requests": 434, "cost": 3.8}
]
}curl http://localhost:8000/status{
"providers": [
{
"name": "deepseek",
"healthy": true,
"total_requests": 800,
"avg_latency_ms": 1200.5,
"consecutive_failures": 0
},
{
"name": "dashscope",
"healthy": true,
"total_requests": 434,
"avg_latency_ms": 450.2,
"consecutive_failures": 0
}
]
}providers:
- name: deepseek # Provider 名称
base_url: https://api.deepseek.com
api_key: ${DEEPSEEK_API_KEY} # 支持环境变量
models: [deepseek-chat] # 支持的模型列表
priority: 1 # 优先级(数字越小越优先)
timeout: 30 # 超时时间(秒)
max_retries: 2 # 最大重试次数
rpm_limit: 60 # 每分钟请求限制
failover:
strategy: priority # 容灾策略
failure_threshold: 3 # 连续失败几次后标记不可用
recovery_interval: 300 # 不可用后多久重试(秒)API Key 支持从环境变量读取:
export DEEPSEEK_API_KEY=sk-xxx
export DASHSCOPE_API_KEY=sk-yyy
export OPENAI_API_KEY=sk-zzz
python -m gateway --config config.yamldocker build -t llm-gateway .
docker run -p 8000:8000 \
-e DEEPSEEK_API_KEY=sk-xxx \
-e DASHSCOPE_API_KEY=sk-yyy \
-v ./config.yaml:/app/config.yaml \
llm-gateway| 端点 | 方法 | 说明 |
|---|---|---|
/v1/chat/completions |
POST | 兼容 OpenAI 的 Chat API |
/v1/models |
GET | 列出所有可用模型 |
/status |
GET | Provider 状态监控 |
/stats?days=7 |
GET | 用量统计 |
/ |
GET | Gateway 信息 |
欢迎提交 PR!特别是:
- 新的 Provider 适配
- Web Dashboard UI
- 语义缓存功能
- 更多的定价数据
如果这个仓库帮到了你,给个 Star 吧 ⭐
Made with 🔀 by Vincent