返回首页

LiteLLM API聚合实战教程2026:一个接口统一管理100+AI模型,含完整Python代码

聚合实战教程:统一管理所有模型

什么是LiteLLM

LiteLLM是一个库,用统一接口调用100+个提供商。你不需要学100个API——用LiteLLM一个接口搞定所有模型。

核心价值:

# 不用LiteLLM:100个API,100种写法
import 
openai.chat..create(model="-4o", ...)

import 
anthropic.messages.create(model="-3-opus", ...)

import .generativeai
google.generativeai.GenerativeModel("-pro").generate(...)

# 用LiteLLM:1个接口,100个模型
from litellm import completion
completion(model="gpt-4o", ...)      # OpenAI
completion(model="claude-3-opus", ...)  # Anthropic
completion(model="gemini-pro", ...)    # Google
completion(model="/qwen-2.5-14b", ...)  # 本地模型

商业价值:

  • AI代理服务:帮企业管理多个AI供应商
  • 成本优化:自动选择最便宜的模型
  • 高可用:一个模型挂了自动切换
  • 计费系统:按用量向客户收费

安装

pip install litellm[proxy]

# 启动代理服务器
litellm --model gpt-4o --port 8000

核心功能

1. 统一接口

from litellm import completion

# OpenAI
resp = completion(
    model="gpt-4o",
    messages=[{"role": "user", "content": "你好"}]
)

# Anthropic
resp = completion(
    model="claude-3-opus", 
    messages=[{"role": "user", "content": "你好"}]
)

# 本地Ollama
resp = completion(
    model="ollama/qwen2.5:14b",
    messages=[{"role": "user", "content": "你好"}]
)

# 所有返回格式一样!
print(resp.choices[0].message.content)

2. 模型路由(自动选最便宜的)

from litellm import 

router = Router(
    model_list=[
        {"model_name": "smart", "litellm_params": {"model": "gpt-4o"}},
        {"model_name": "smart", "litellm_params": {"model": "claude-3-opus"}},
        {"model_name": "smart", "litellm_params": {"model": "gemini-pro"}},
    ],
    routing_strategy="least-cost",  # 自动选最便宜的
)

# 只需要调用"smart",LiteLLM自动选模型
resp = router.completion(
    model="smart",
    messages=[{"role": "user", "content": "你好"}]
)

3. 负载均衡+故障转移

router = Router(
    model_list=[
        {"model_name": "main", "litellm_params": {"model": "gpt-4o"}},
        {"model_name": "main", "litellm_params": {"model": "gpt-4o-mini"}},
        {"model_name": "main", "litellm_params": {"model": "claude-3-haiku"}},
    ],
    routing_strategy="simple-shuffle",
    num_retries=3,  # 失败重试3次
    fallbacks=[{"main": ["gpt-4o-mini"]}],  # 主模型挂了用备用
)

4. 成本追踪

from litellm import completion
import litellm

# 启用成本追踪
litellm.success_callback = ["langfuse"]  # 或 "langsmith"

resp = completion(
    model="gpt-4o",
    messages=[{"role": "user", "content": "你好"}]
)

# 查看成本
print(f"Token用量: {resp.usage}")
print(f"成本: ${resp._hidden_params['response_cost']:.4f}")

LiteLLM Proxy(企业级)

部署代理服务器

# 配置文件 config.yaml
model_list:
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: os.environ/OPENAI_API_KEY
  
  - model_name: claude-3-opus
    litellm_params:
      model: anthropic/claude-3-opus
      api_key: os.environ/ANTHROPIC_API_KEY
  
  - model_name: qwen-local
    litellm_params:
      model: ollama/qwen2.5:14b
      api_base: http://localhost:11434

# 启动代理
litellm --config config.yaml --port 8000

# 现在可以用OpenAI SDK调用任何模型

客户端使用

# 用OpenAI SDK调用LiteLLM代理
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="your-litellm-key",
)

# 调用任何模型
resp = client.chat.completions.create(
    model="gpt-4o",  # 或 "claude-3-opus" 或 "qwen-local"
    messages=[{"role": "user", "content": "你好"}]
)

用户管理和计费

# config.yaml
general_settings:
  master_key: sk-your-master-key
  
# 创建用户
# POST /user/new
{
  "user_id": "user-123",
  "max_budget": 100,  # 最大$100
  "models": ["gpt-4o", "claude-3-opus"],
  "tpm_limit": 10000,  # 每分钟10K token
}

# 用户用他们的key调用,LiteLLM自动追踪用量

商业化:AI API代理服务

架构

客户 → LiteLLM Proxy → 多个AI提供商

你的服务:
├── 统一API(客户不需要管哪个提供商)
├── 自动路由(选最便宜/最快的)
├── 用量计费(按token收费)
├── 高可用(一个挂了自动切换)
└── 数据安全(本地代理,数据不出境)

定价

成本价 + 加价20-50%

例如:
├── GPT-4o成本:$0.005/1K token
├── 你的售价:$0.0075/1K token(加价50%)
├── Claude成本:$0.015/1K token
├── 你的售价:$0.02/1K token(加价33%)

月收入预估:
├── 10个客户 × 平均$100/月 = $1000/月
├── 成本:$600/月
├── 利润:$400/月
└── 随客户增长,利润指数增长

与Hermes 集成

# 把LiteLLM做成工具
@mcp.tool()
async def chat(model: str, message: str) -> str:
    """用指定模型聊天"""
    from litellm import completion
    resp = completion(
        model=model,
        messages=[{"role": "user", "content": message}]
    )
    return resp.choices[0].message.content

@mcp.tool()
async def compare_models(message: str, models: list[str]) -> dict:
    """对比多个模型的回答"""
    results = {}
    for model in models:
        resp = completion(
            model=model,
            messages=[{"role": "user", "content": message}]
        )
        results[model] = resp.choices[0].message.content
    return results

@mcp.tool()
async def get_usage(user_id: str) -> dict:
    """查询用户用量"""
    import requests
    resp = requests.get(
        f"http://localhost:8000/user/{user_id}/usage",
        headers={"Authorization": "Bearer YOUR_MASTER_KEY"}
    )
    return resp.json()

行动清单

  1. ✅ 安装LiteLLM
  2. 🔧 配置config.yaml(接入你的API keys)
  3. 🚀 启动代理服务器
  4. 🧪 测试多模型调用
  5. 💰 设置计费系统
  6. 📢 开始推广

LiteLLM是你现有工具链的完美补充——所有工具都通过统一API调用模型。

常见问题

什么是LiteLLM

>什么是LiteLLMLiteLLM是一个Python库,用统一接口调用100+个LLM提供商。你不需要学100个API——用LiteLLM一个接口搞定所有模型。 核心价值: # 不用LiteLLM:100个API,100种写法 import openai openai.chat.completions.create(model="gpt-4o", ...) import anthropic anthropic.messages.create(model="claude-3-opus", ...) import google.generativeai g

评论