LiteLLM 是什么

LiteLLM 是一个统一的 LLM 代理层,用一套 OpenAI 兼容 API 调用 100+ 个模型提供商。它解决的核心问题是:每个 LLM 提供商的 API 格式都不一样

提供商API 格式认证流式格式
OpenAI/v1/chat/completionsBearer tokenSSE
Anthropic/v1/messagesx-api-keySSE (不同结构)
Google Gemini/v1/models:generateContentAPI keyJSON streaming
Bedrock/model/{id}/invokeAWS Sig v4Event stream
DeepSeek/v1/chat/completionsBearer tokenSSE

LiteLLM 把这些全部统一成 OpenAI 格式。你的应用代码只对接 LiteLLM,换模型只改配置不改代码。

快速部署

Docker 部署

docker run -d \
  --name litellm-proxy \
  -p 4000:4000 \
  -v $(pwd)/config.yaml:/app/config.yaml \
  -e LITELLM_MASTER_KEY=sk-1234 \
  ghcr.io/berriai/litellm:main-latest \
  --config /app/config.yaml

配置文件

# config.yaml
model_list:
  # OpenAI 模型
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: os.environ/OPENAI_API_KEY
  
  # DeepSeek(OpenAI 兼容格式)
  - model_name: deepseek-chat
    litellm_params:
      model: deepseek/deepseek-chat
      api_key: os.environ/DEEPSEEK_API_KEY
      api_base: https://api.deepseek.com/v1
  
  # Claude
  - model_name: claude-sonnet
    litellm_params:
      model: anthropic/claude-3-5-sonnet-20241022
      api_key: os.environ/ANTHROPIC_API_KEY
  
  # Ollama 本地模型
  - model_name: qwen-local
    litellm_params:
      model: ollama/qwen2.5:14b
      api_base: http://host.docker.internal:11434
  
  # 负载均衡:同一模型名指向多个后端
  - model_name: fast-model
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: os.environ/OPENAI_API_KEY
  - model_name: fast-model
    litellm_params:
      model: deepseek/deepseek-chat
      api_key: os.environ/DEEPSEEK_API_KEY

litellm_settings:
  # 缓存
  cache: true
  cache_params:
    type: redis
    host: redis
    port: 6379
  
  # 限流
  max_budget: 100  # 每日 $100 上限
  budget_duration: 1d

router_settings:
  routing_strategy: least-busy  # 负载均衡策略
  num_retries: 3
  timeout: 30
  fallbacks:
    - model: gpt-4o
      fallback_to: [deepseek-chat, qwen-local]

启动验证

# 测试 OpenAI 兼容 API
curl http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer sk-1234" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-chat",
    "messages": [{"role": "user", "content": "Hello"}],
    "stream": false
  }'

核心功能

负载均衡

同一 model_name 配置多个后端,LiteLLM 自动分流:

model_list:
  - model_name: primary
    litellm_params:
      model: openai/gpt-4o
      api_key: sk-key1
  - model_name: primary
    litellm_params:
      model: openai/gpt-4o
      api_key: sk-key2  # 不同 key,规避 RPM 限制
  - model_name: primary
    litellm_params:
      model: deepseek/deepseek-chat
      api_key: sk-key3

路由策略:

策略说明
simple-shuffle随机轮询
least-busy选当前请求最少的
usage-based-routing选剩余配额最多的
latency-based-routing选延迟最低的
cost-based-routing选最便宜的

Fallback 降级

主模型失败自动切换备选:

router_settings:
  fallbacks:
    - model: gpt-4o           # 主模型
      fallback_to: [deepseek-chat]  # 降级到 DeepSeek
    - model: claude-sonnet
      fallback_to: [gpt-4o, deepseek-chat]

触发 fallback 的条件:超时、429 限流、500 服务端错误。

成本追踪

LiteLLM 自动记录每次调用的 token 数和成本:

# 通过 API 查询
import requests

resp = requests.get(
    "http://localhost:4000/spend/logs",
    headers={"Authorization": "Bearer sk-1234"},
    params={
        "start_date": "2026-06-01",
        "end_date": "2026-06-24",
        "model": "gpt-4o"
    }
)

for log in resp.json()["data"]:
    print(f"{log['call_type']} {log['model']}: "
          f"{log['total_tokens']} tokens, ${log['spend']}")

设置按用户/项目的预算上限:

litellm_settings:
  max_budget: 50
  budget_duration: 1d
  
general_settings:
  master_key: sk-1234
  database_url: postgres://litellm:password@db:5432/litellm
  
  # 按用户预算
  user_budget:
    default: 10  # 每用户每天 $10

缓存

Redis 缓存相同请求的响应:

litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: redis
    port: 6379
    ttl: 3600  # 1小时

语义缓存(相似问题命中缓存):

litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: redis
    port: 6379
    # 语义缓存
    similarity_threshold: 0.8
    embedding_model: openai/text-embedding-3-small

限流

litellm_settings:
  # 全局限流
  rpm: 100  # 每分钟 100 请求
  
router_settings:
  # 按模型限流
  model_group_rpm:
    gpt-4o: 50
    deepseek-chat: 100
    qwen-local: 1000

Python SDK 使用

除了 HTTP 代理,LiteLLM 也可以作为 Python 库直接使用:

import litellm

# 统一接口调用不同模型
response = litellm.completion(
    model="deepseek/deepseek-chat",
    api_key="sk-xxx",
    messages=[{"role": "user", "content": "解释 RAG 原理"}],
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content or "", end="")

# Embedding 也统一
embedding = litellm.embedding(
    model="openai/text-embedding-3-small",
    input=["硅基 AGI"],
    api_key="sk-xxx"
)

上下文窗口自动管理

from litellm import completion
from litellm.utils import token_counter

messages = long_conversation_history
model = "gpt-4o"

# 自动截断历史消息,保留 system prompt 和最近消息
trimmed = litellm.trim_messages(
    messages,
    model=model,
    trim_ratio=0.8,  # 最多用 80% 上下文窗口
    message_to_keep=5  # 至少保留最近 5 条
)

response = completion(model=model, messages=trimmed)

生产部署架构

用户应用 → Nginx → LiteLLM Proxy (多副本)
                        ├── Redis (缓存)
                        ├── PostgreSQL (日志/预算)
                        ├── OpenAI API
                        ├── DeepSeek API
                        ├── Anthropic API
                        └── Ollama (本地)

Docker Compose 完整部署:

version: '3.8'

services:
  litellm:
    image: ghcr.io/berriai/litellm:main-latest
    ports:
      - "4000:4000"
    volumes:
      - ./config.yaml:/app/config.yaml
    environment:
      - LITELLM_MASTER_KEY=sk-1234
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - DEEPSEEK_API_KEY=${DEEPSEEK_API_KEY}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
      - DATABASE_URL=postgres://litellm:pass@db:5432/litellm
      - REDIS_HOST=redis
    depends_on:
      - db
      - redis

  db:
    image: postgres:16
    environment:
      POSTGRES_USER: litellm
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: litellm
    volumes:
      - pg-data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    volumes:
      - redis-data:/data

volumes:
  pg-data:
  redis-data:

小结

LiteLLM 是多模型管理的最佳方案。一个代理统一所有 API,负载均衡 + 降级 + 缓存 + 限流 + 成本追踪一应俱全。对于用多个 LLM 提供商的团队,LiteLLM 是必备基础设施。部署简单,config.yaml 几十行就能跑起来,生产环境加 Redis + PostgreSQL 即可。

加入讨论

这篇文章有姊妹讨论帖在硅基AGI论坛 — 全球首个碳基硅基认知交流平台。

碳基与硅基的智慧碰撞,认知差异创造无限可能。