API Router 入门:按难度分级调用,再省 40%
2026-06-11 · 6 分钟阅读
核心思路:不是所有请求都需要最强模型。翻译"你好"不需要 Claude Opus,小学数学不需要 DeepSeek V4 Pro。把任务按难度分级,简单扔 Flash,复杂扔 Pro,月账单再砍 40%。
一、为什么需要 Router?
看一组真实数据。假设你每天处理 1000 次 API 调用:
| 方案 | 全部用 Pro | 全部用 Flash | Router 分级 |
|---|---|---|---|
| 简单任务(80%) | ¥265/月 | ¥53/月 | ¥53/月 |
| 复杂任务(20%) | ¥66/月 | 质量差 | ¥66/月 |
| 合计 | ¥331/月 | 质量妥协 | ¥119/月 |
Router方案比全Pro方案省了 64%。比全Flash方案保证了质量。
方案A:Nginx 简单路由(适合轻量场景)
用 Nginx 根据请求路径或 Header 转发到不同后端:
# nginx.conf
upstream deepseek_flash {
server api.deepseek.com:443;
}
upstream deepseek_pro {
server api.deepseek.com:443;
}
server {
listen 8080;
# 简单任务 → Flash
location /v1/chat/simple {
proxy_pass https://deepseek_flash/v1/chat/completions;
proxy_set_header Authorization "Bearer $DEEPSEEK_KEY";
}
# 复杂任务 → Pro
location /v1/chat/complex {
proxy_pass https://deepseek_pro/v1/chat/completions;
proxy_set_header Authorization "Bearer $DEEPSEEK_KEY";
}
}
在你的应用里,简单任务调 /v1/chat/simple,复杂任务调 /v1/chat/complex。
方案B:LiteLLM Proxy(推荐,适合生产环境)
LiteLLM 是一个开源的 LLM 代理,支持 100+ 模型、负载均衡、成本追踪。它内置了 Router 能力。
# 安装
pip install litellm[proxy]
# 创建 litellm_config.yaml
model_list:
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o
api_key: ${OPENAI_API_KEY}
router_settings:
routing_strategy: "latency-based-routing"
allowed_fails: 3
num_retries: 2
general_settings:
master_key: ${LITELLM_MASTER_KEY}
# 启动
litellm --config litellm_config.yaml --port 4000
# 调用(和调 OpenAI 一模一样)
curl http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer sk-xxx" \
-d '{"model":"gpt-4o","messages":[{"role":"user","content":"hi"}]}'
方案C:按 System Prompt 关键词自动路由
更智能的做法——根据用户 Prompt 内容自动选模型:
# router.py — 最简单的智能路由
import re
def route_model(prompt: str) -> str:
"""根据 prompt 内容自动选模型"""
prompt_lower = prompt.lower()
# 复杂任务关键词 → Pro
complex_keywords = [
"explain", "analyze", "debug", "review",
"architecture", "design pattern", "optimize",
"解释", "分析", "架构", "优化", "调试"
]
if any(k in prompt_lower for k in complex_keywords):
return "deepseek-v4-pro"
# 代码任务 → Pro
if any(k in prompt_lower for k in ["code", "function", "class", "bug"]):
return "deepseek-v4-pro"
# 默认 → Flash
return "deepseek-v4-flash"
# 使用
model = route_model(user_input)
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": user_input}]
)
这个方案成本最低,不需要额外部署服务。把这份逻辑集成到你的 API 封装层即可。
什么时候该用哪个模型?
| 任务类型 | 推荐模型 | 理由 |
|---|---|---|
| 翻译、摘要、改写 | DeepSeek V4 Flash | Flash 完全够用,Pro 浪费 |
| 客服对话 | DeepSeek V4 Flash | 80%是常见问题 |
| 代码生成、Debug | DeepSeek V4 Pro | 代码需要推理能力 |
| 数学推理 | DeepSeek V4 Pro | 需要完整推理链 |
| 长文写作 | DeepSeek V4 Pro | 需要连贯性和深度 |
| 图片理解 | GPT-4o | 多模态保底 |
监控指标
Router 上线后要监控两个核心指标:
- Flash/Pro 分流比例:理想是 80/20。如果 Pro 比例超过 40%,说明分类规则太宽松。
- 用户满意度:如果 Flash 处理了它不该处理的任务,用户会抱怨"回复质量下降"。