关于 llm-gateway
llm-gateway 是一项技能,介绍如何用 LiteLLM 为托管及自托管 LLM 后端配置统一网关,涵盖路由、访问限制、成本控制、缓存、故障切换和健康监控。
主要功能
- 01路由至多个 LLM 提供商和自托管模型
- 02设置团队或用户的速率与支出限制
- 03用虚拟密钥集中管理凭证访问
- 04配置缓存和自动故障切换
- 05监控健康状态及模型支出
适用场景
- 01通过单一端点提供多个 LLM 后端
- 02为团队或应用设置使用预算
- 03借助缓存减少重复请求成本
- 04通过备用模型应对提供商故障
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ bagelhole/ devops-security-agent-skills --skill llm-gateway安装后在 Claude Code 中输入/llm-gateway确认已加载。
详细介绍
大模型网关
一个统一的 API 网关,可在各服务提供商和可自托管模型之间路由大模型请求,并提供速率限制、成本跟踪、缓存和故障转移功能。
何时使用此技能
在以下情况下使用此技能:
- 在单一端点后接入多个大模型后端(OpenAI、Anthropic、vLLM、Ollama)
- 强制执行针对团队或用户的速率限制和支出预算
- 在服务提供商不可用时实现自动回退
- 添加语义缓存,将 API 成本降低 20–50%
- 集中管理 API 密钥,而不是将密钥分发给每个应用
前置条件
- Docker 和 Docker Compose
- PostgreSQL 或 SQLite 数据库(用于 LiteLLM 状态)
- 大模型 API 密钥(OpenAI、Anthropic 等)或可自托管的 vLLM 端点
- 可选:用于缓存和速率限制的 Redis
LiteLLM 代理 — 快速入门
LiteLLM 是事实上的开源大模型网关,提供与 OpenAI 兼容的 API。
# Run with Docker
docker run -d \
--name litellm-proxy \
-p 4000:4000 \
-e OPENAI_API_KEY=$OPENAI_API_KEY \
-e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
-v $(pwd)/litellm-config.yaml:/app/config.yaml \
ghcr.io/berriai/litellm:main-latest \
--config /app/config.yaml \
--detailed_debug
LiteLLM 配置
# litellm-config.yaml
model_list:
# OpenAI models
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o
api_key: os.environ/OPENAI_API_KEY
rpm: 10000
tpm: 2000000
- model_name: gpt-4o-mini
litellm_params:
model: openai/gpt-4o-mini
api_key: os.environ/OPENAI_API_KEY
# Anthropic
- model_name: claude-sonnet-4-6
litellm_params:
model: anthropic/claude-sonnet-4-6
api_key: os.environ/ANTHROPIC_API_KEY
# Self-hosted vLLM instances (load balanced)
- model_name: llama-3.1-8b
litellm_params:
model: openai/meta-llama/Llama-3.1-8B-Instruct
api_base: http://vllm-1:8000/v1
api_key: fake # vLLM key
- model_name: llama-3.1-8b
litellm_params:
model: openai/meta-llama/Llama-3.1-8B-Instruct
api_base: http://vllm-2:8000/v1 # second replica — auto load balanced
api_key: fake
# Fallback: cheap model if primary fails
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o-mini # fallback to cheaper model
api_key: os.environ/OPENAI_API_KEY
router_settings:
routing_strategy: least-busy # or: latency-based, simple-shuffle
num_retries: 3
retry_after: 5
allowed_fails: 2
cooldown_time: 60
# Fallback configuration
fallbacks:
- gpt-4o: [claude-sonnet-4-6]
- claude-sonnet-4-6: [gpt-4o]
litellm_settings:
# Semantic caching
cache: true
cache_params:
type: redis
host: redis
port: 6379
similarity_threshold: 0.90 # cache if >90% semantic similarity
# Logging
success_callback: ["langfuse"]
failure_callback: ["langfuse"]
langfuse_public_key: os.environ/LANGFUSE_PUBLIC_KEY
langfuse_secret_key: os.environ/LANGFUSE_SECRET_KEY
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY
database_url: postgresql://litellm:password@postgres:5432/litellm
store_model_in_db: true
Docker Compose:完整网关堆栈
services:
litellm:
image: ghcr.io/berriai/litellm:main-latest
command: ["--config", "/app/config.yaml", "--port", "4000"]
volumes:
- ./litellm-config.yaml:/app/config.yaml
ports:
- "4000:4000"
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
- LITELLM_MASTER_KEY=${LITELLM_MASTER_KEY}
- DATABASE_URL=postgresql://litellm:password@postgres:5432/litellm
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
restart: unless-stopped
postgres:
image: postgres:16-alpine
environment:
POSTGRES_DB: litellm
POSTGRES_USER: litellm
POSTGRES_PASSWORD: password
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U litellm"]
interval: 5s
retries: 5
restart: unless-stopped
redis:
image: redis:7-alpine
command: redis-server --maxmemory 2gb --maxmemory-policy allkeys-lru
volumes:
- redis-data:/data
restart: unless-stopped
volumes:
postgres-data:
redis-data:
虚拟密钥和速率限制
# Create a virtual API key for a team (via LiteLLM API)
curl -X POST http://localhost:4000/key/generate \
-H "Authorization: Bearer $LITELLM_MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"team_id": "team-backend",
"key_alias": "backend-team-key",
"models": ["gpt-4o-mini", "llama-3.1-8b"],
"max_budget": 100, # USD limit
"budget_duration": "monthly",
"rpm_limit": 100, # requests per minute
"tpm_limit": 500000 # tokens per minute
}'
# View spend
curl http://localhost:4000/spend/keys \
-H "Authorization: Bearer $LITELLM_MASTER_KEY"
Nginx 负载均衡器(替代方案/补充方案)
# nginx.conf — round-robin across vLLM replicas
upstream vllm_backends {
least_conn;
server vllm-1:8000 max_fails=3 fail_timeout=30s;
server vllm-2:8000 max_fails=3 fail_timeout=30s;
server vllm-3:8000 max_fails=3 fail_timeout=30s;
keepalive 32;
}
server {
listen 80;
server_name llm-api.internal;
# Rate limiting
limit_req_zone $http_authorization zone=per_key:10m rate=100r/m;
limit_req zone=per_key burst=20 nodelay;
location /v1/ {
proxy_pass http://vllm_backends;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_read_timeout 300s; # long timeout for streaming
proxy_buffering off; # required for SSE streaming
proxy_cache_bypass 1;
}
}
监控网关运行状况
# Check LiteLLM health
curl http://localhost:4000/health
# Model-level health
curl http://localhost:4000/health/liveliness
# Spend by model
curl http://localhost:4000/spend/models \
-H "Authorization: Bearer $LITELLM_MASTER_KEY"
# Active virtual keys
curl http://localhost:4000/key/list \
-H "Authorization: Bearer $LITELLM_MASTER_KEY"
常见问题
| 问题 | 原因 | 修复方法 |
|---|---|---|
后端出现 ConnectionRefusedError | 无法连接后端 | 检查 api_base URL;确认后端运行正常 |
| 速率限制错误(429) | 超出预算/RPM 限制 | 提高限制,或切换到备用模型 |
| 流式响应缓慢 | 已启用 proxy_buffering | 在 Nginx 中设置 proxy_buffering off |
| 缓存未命中率高 | 阈值过于严格 | 将 similarity_threshold 调低至 0.85 |
| Postgres 连接错误 | 数据库尚未就绪 | 添加带有 condition: service_healthy 的 depends_on |
最佳实践
- 为每个团队/应用使用虚拟密钥——切勿泄露服务提供商的原始 API 密钥。
- 使用 Redis 启用
cache: true,缓存重复或相似的查询;成本可降低 30–50%。 - 设置
num_retries: 3并配置回退选项,以妥善应对服务提供商中断。 - 将所有请求记录到 Langfuse 或 OpenTelemetry,以便进行成本归因和调试。
- 自托管模型使用
least-busy路由策略,避免 GPU 饱和。
相关技能
- vllm-server - 后端推理服务
- llm-inference-scaling - 后端自动扩缩容
- llm-caching - 语义缓存模式
- llm-cost-optimization - 成本管理
评论
支持 Markdown