版本基准:LiteLLM v1.80.x(2026年3月)
GitHub:https://github.com/BerriAI/litellm
Stars:~36.5k | Forks:~5.9k


目录

1.项目概述
2.两种使用方式:SDK vs Proxy
3.核心 API 接口全景
4.各接口详细调用方式
        4.1 文本对话(Chat Completions)
        4.2 图生文 / 视觉理解(Vision)
        4.3 文生图(Image Generation)
        4.4 图片编辑(Image Edit)
        4.5 语音识别 ASR(Audio Transcription)
        4.6 语音合成 TTS(Text-to-Speech)
        4.7 向量嵌入(Embeddings)
        4.8 重排序(Rerank)
        4.9 视频生成(Video Generation)
        4.10 文本补全(Text Completion)
        4.11 批处理(Batch)
        4.12 Responses API
5.多模型路由与负载均衡
6.支持的主流 Provider 矩阵
7.企业级功能
8.典型使用场景
9.架构设计总结
10.与同类框架对比
11.最佳实践建议


1. 项目概述

LiteLLM 是由 BerriAI 开源的 AI Gateway + Python SDK,目标是用一套统一的 OpenAI 兼容接口调用 100+ LLM Provider(OpenAI、Anthropic、Bedrock、Vertex AI、Azure、Groq、Cohere 等),同时提供成本追踪、负载均衡、故障回退、Guardrails 等企业级能力。

核心价值主张:

  • 统一接口:无论底层 Provider 如何变化,业务代码不变,只换 model 字符串
  • 多模态全覆盖:文本、图像、音频、视频、向量、重排序,一个框架全包
  • 生产就绪:P95 延迟 8ms(1k RPS),支持水平扩展
  • OpenAI 兼容:现有 OpenAI SDK 代码改一行 base_url 即可接入

2. 两种使用方式:SDK vs Proxy

LiteLLM 提供两种使用模式,适用于不同场景:

维度 Python SDK Proxy Server(AI Gateway)
部署方式 直接 pip install litellm 嵌入代码 独立进程/容器运行
适用对象 个人开发者、单一应用 平台团队、多租户企业
认证管理 应用自己管理 API Key 统一虚拟 Key,集中管控
成本追踪 应用级别 多项目/多用户/多团队级别
负载均衡 Router 类,代码层 配置文件驱动,网关层
与现有系统集成 需改代码 只改 base_url,零代码改动
管理界面 有 Admin Dashboard UI

2.1 Python SDK 快速开始

pip install litellm
from litellm import completion
import os

os.environ["OPENAI_API_KEY"] = "your-openai-key"
os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-key"

# 调用 OpenAI
response = completion(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "你好!"}]
)

# 调用 Anthropic,代码完全一样,只换 model 字符串
response = completion(
    model="anthropic/claude-sonnet-4-20250514",
    messages=[{"role": "user", "content": "你好!"}]
)

2.2 Proxy Server 快速开始

pip install 'litellm[proxy]'
litellm --model gpt-4o
# Proxy 监听 http://0.0.0.0:4000
# 现有 OpenAI 代码只需改 base_url,其余不变
import openai
client = openai.OpenAI(
    api_key="anything",
    base_url="http://0.0.0.0:4000"
)
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "你好!"}]
)

3. 核心 API 接口全景

LiteLLM 不是只有一个接口,而是针对不同模态提供了多个专用接口,各接口对应不同的 AI 能力:

LiteLLM 支持的 API 端点
├── /chat/completions     → 文本对话 + 多模态理解(图文、视频理解)
├── /responses            → OpenAI Responses API 兼容(含 Web Search 工具等)
├── /embeddings           → 向量嵌入(文本/图像)
├── /images/generations   → 文生图
├── /images/edits         → 图片编辑
├── /audio/transcriptions → 语音识别 ASR
├── /audio/speech         → 语音合成 TTS
├── /rerank               → 文档重排序
├── /batches              → 批量异步处理
├── /video/generations    → 视频生成(新增)
└── /messages             → Anthropic 原生格式

模型 mode 分类(来自官方 model_prices_and_context_window.json):

mode 值 对应能力
chat 文本对话、多模态理解
completion 传统文本补全
embedding 向量嵌入
image_generation 文生图
audio_transcription 语音转文字
audio_speech 文字转语音
rerank 重排序
moderation 内容审核
search 搜索

4. 各接口详细调用方式

4.1 文本对话(Chat Completions)

最核心的接口,支持 100+ Provider,统一使用 completion() 函数。

Python SDK:

from litellm import completion

# 同步调用
response = completion(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "解释量子纠缠"}],
    temperature=0.7,
    max_tokens=1000,
)
print(response.choices[0].message.content)

# 异步调用
from litellm import acompletion
import asyncio

async def main():
    response = await acompletion(
        model="anthropic/claude-sonnet-4-20250514",
        messages=[{"role": "user", "content": "你好"}]
    )
    return response

asyncio.run(main())

# 流式输出
response = completion(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "写一首诗"}],
    stream=True
)
for chunk in response:
    print(chunk.choices[0].delta.content or "", end="")

支持的 Provider(部分):

# OpenAI
completion(model="openai/gpt-4o", ...)
# Anthropic
completion(model="anthropic/claude-opus-4-20250514", ...)
# Google Vertex AI
completion(model="vertex_ai/gemini-2.0-flash", ...)
# AWS Bedrock
completion(model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0", ...)
# Azure OpenAI
completion(model="azure/my-deployment-name", ...)
# Groq(高速推理)
completion(model="groq/llama-3.3-70b-versatile", ...)
# 本地 Ollama
completion(model="ollama/llama3", ...)
# DeepSeek
completion(model="deepseek/deepseek-chat", ...)

工具调用(Function Calling):

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "获取城市天气",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名"}
            },
            "required": ["city"]
        }
    }
}]

response = completion(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "上海今天天气怎么样?"}],
    tools=tools,
    tool_choice="auto"
)

4.2 图生文 / 视觉理解(Vision)

同样使用 completion() 接口,通过在 content 中传入图像 URL 或 base64 数据实现。LiteLLM 会自动将图像格式适配给不同 Provider。

from litellm import completion

# 方式一:传入图片 URL
response = completion(
    model="openai/gpt-4o",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "描述这张图片里有什么?"
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://example.com/image.jpg"
                }
            }
        ]
    }]
)

# 方式二:传入 base64 编码图片
import base64

with open("image.jpg", "rb") as f:
    image_data = base64.b64encode(f.read()).decode("utf-8")

response = completion(
    model="anthropic/claude-opus-4-20250514",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "这张图里有几只猫?"
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{image_data}"
                }
            }
        ]
    }]
)

支持视觉理解的 Provider:

  • OpenAI GPT-4o, GPT-4 Turbo
  • Anthropic Claude 3/4 系列
  • Google Gemini Pro Vision, Gemini Flash
  • AWS Bedrock(Claude、Nova 系列)
  • Azure OpenAI GPT-4 Vision

4.3 文生图(Image Generation)

使用独立的 image_generation() 函数,对应 /images/generations 端点。

from litellm import image_generation

# DALL-E 3 生成图片
response = image_generation(
    model="dall-e-3",
    prompt="一只在太空中漂浮的橘色猫咪,赛博朋克风格,8K超清",
    n=1,
    size="1024x1024",
    quality="hd",        # standard / hd(DALL-E 3 专属)
    style="vivid"        # vivid / natural(DALL-E 3 专属)
)
image_url = response.data[0].url
print(image_url)

# Stability AI(Stable Diffusion)
response = image_generation(
    model="stability/stable-diffusion-xl-1024-v1-0",
    prompt="水墨风格的山水画,中国传统艺术",
    n=1,
    size="1024x1024"
)

# Vertex AI Imagen
response = image_generation(
    model="vertex_ai/imagegeneration@006",
    prompt="An astronaut riding a horse on Mars",
    vertex_ai_project="my-project",
    vertex_ai_location="us-central1"
)

# Fal AI(FLUX 系列)
response = image_generation(
    model="fal_ai/flux/dev",
    prompt="A futuristic city at sunset",
    n=1,
    size="1024x1024"
)

# 异步版本
from litellm import aimage_generation
response = await aimage_generation(
    model="dall-e-3",
    prompt="..."
)

主要文生图 Provider 对比:

Provider 模型示例 特点
OpenAI dall-e-3, gpt-image-1 质量高,prompt 理解强
Stability AI stable-diffusion-xl-1024-v1-0 开源可私有化
Vertex AI imagegeneration@006, Imagen 4 Google 生态,企业级
Fal AI flux/dev, flux/pro 速度快,FLUX 系列
AWS Bedrock Stability 模型 企业合规

4.4 图片编辑(Image Edit)

from litellm import image_edit

# 图片编辑(需要原图 + 蒙版 + prompt)
with open("original.png", "rb") as img, open("mask.png", "rb") as mask:
    response = image_edit(
        model="dall-e-2",
        image=img,
        mask=mask,
        prompt="将背景改为星空",
        n=1,
        size="1024x1024"
    )

image_url = response.data[0].url

# 异步版本
from litellm import aimage_edit
response = await aimage_edit(model="dall-e-2", ...)

4.5 语音识别 ASR(Audio Transcription)

使用 transcription() 函数,对应 /audio/transcriptions 端点,兼容 OpenAI Whisper API 格式。

from litellm import transcription

# OpenAI Whisper
audio_file = open("speech.mp3", "rb")
response = transcription(
    model="whisper-1",
    file=audio_file,
    language="zh",          # 指定语言(可选,自动检测)
    response_format="json", # json / text / srt / verbose_json / vtt
    temperature=0.0
)
print(response.text)

# OpenAI GPT-4o Transcribe(更新的模型)
response = transcription(
    model="gpt-4o-transcribe",
    file=open("audio.wav", "rb")
)

# Azure Whisper
response = transcription(
    model="azure/azure-whisper",
    file=audio_file,
    api_version="2024-02-15-preview",
    api_base="https://your-azure-endpoint.openai.azure.com/",
    api_key="your-azure-key"
)

# ElevenLabs(高精度转录)
response = transcription(
    model="elevenlabs/scribe_v1",
    file=audio_file
)

# 异步版本
from litellm import atranscription
response = await atranscription(model="whisper-1", file=audio_file)

通过 Proxy 调用(OpenAI SDK 兼容):

from openai import OpenAI

client = OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
audio_file = open("speech.mp3", "rb")
transcript = client.audio.transcriptions.create(
    model="whisper",
    file=audio_file
)
print(transcript.text)

通过 curl 调用:

curl --location 'http://0.0.0.0:4000/v1/audio/transcriptions' \
  --header 'Authorization: Bearer sk-1234' \
  --form 'file=@"./audio.wav"' \
  --form 'model="whisper"'

4.6 语音合成 TTS(Text-to-Speech)

使用 speech() 函数,对应 /audio/speech 端点,兼容 OpenAI TTS API 格式。

from litellm import speech
import io

# OpenAI TTS
response = speech(
    model="tts-1",          # tts-1 / tts-1-hd
    input="你好,欢迎使用 LiteLLM!",
    voice="alloy",          # alloy / echo / fable / onyx / nova / shimmer
    response_format="mp3",  # mp3 / opus / aac / flac
    speed=1.0               # 0.25 ~ 4.0
)

# 保存为文件
with open("output.mp3", "wb") as f:
    f.write(response.content)

# Azure TTS
response = speech(
    model="azure/tts-1-hd",
    input="Hello World",
    voice="nova",
    api_base="https://your-azure-endpoint.openai.azure.com/",
    api_key="your-azure-key"
)

# 通过 chat/completions 模型生成语音(特殊功能)
# LiteLLM 允许用 /audio/speech 端点调用 chat 模型生成语音
response = speech(
    model="openai/gpt-4o",
    input="解释人工智能的发展历程"
)

# 异步版本
from litellm import aspeech
response = await aspeech(model="tts-1", input="Hello")

通过 Proxy 调用:

from openai import OpenAI

client = OpenAI(api_key="sk-1234", base_url="http://0.0.0.0:4000")
response = client.audio.speech.create(
    model="tts-1",
    voice="alloy",
    input="Hello world!"
)
response.stream_to_file("output.mp3")

4.7 向量嵌入(Embeddings)

使用 embedding() 函数,对应 /embeddings 端点,支持文本嵌入和多模态嵌入。

from litellm import embedding

# 文本嵌入
response = embedding(
    model="text-embedding-3-small",
    input=["这是第一段文本", "这是第二段文本"],
    encoding_format="float"  # float / base64
)
vectors = [item["embedding"] for item in response.data]
print(f"向量维度: {len(vectors[0])}")

# OpenAI text-embedding-3-large
response = embedding(
    model="text-embedding-3-large",
    input=["LiteLLM supports 100+ providers"],
    dimensions=1536  # 可降维,节省存储
)

# Cohere 嵌入(多语言支持强)
response = embedding(
    model="cohere/embed-multilingual-v3.0",
    input=["中文文本嵌入测试"],
    input_type="search_document"  # search_query / search_document / classification
)

# AWS Bedrock 嵌入
response = embedding(
    model="bedrock/amazon.titan-embed-text-v1",
    input=["Amazon Titan embedding"]
)

# 图像嵌入(多模态)
import base64
with open("image.jpg", "rb") as f:
    img_base64 = base64.b64encode(f.read()).decode()

response = embedding(
    model="vertex_ai/multimodalembedding@001",
    input=[img_base64]  # 传入 base64 图像
)

# 异步版本
from litellm import aembedding
response = await aembedding(model="text-embedding-3-small", input=["hello"])

4.8 重排序(Rerank)

使用 rerank() 函数,对应 /rerank 端点,遵循 Cohere Rerank API 规范。适用于 RAG 系统中的检索结果重排。

from litellm import rerank

# Cohere Rerank
response = rerank(
    model="cohere/rerank-english-v3.0",
    query="什么是机器学习?",
    documents=[
        "机器学习是人工智能的一个分支,通过数据训练模型",
        "深度学习是机器学习的子集,使用神经网络",
        "生物学是研究生命体的科学",
        "Python 是一种编程语言"
    ],
    top_n=2  # 返回最相关的前2个
)

for result in response.results:
    print(f"排名 {result.index}: 分数 {result.relevance_score:.4f}")
    print(f"  文本: {response.documents[result.index]}")

# Jina Rerank
response = rerank(
    model="jina_ai/jina-reranker-v2-base-multilingual",
    query="机器学习介绍",
    documents=["doc1", "doc2", "doc3"]
)

# 异步版本
from litellm import arerank
response = await arerank(model="cohere/rerank-english-v3.0", ...)

4.9 视频生成(Video Generation)

使用 video_generation() 函数(较新功能),支持文生视频和图生视频。

import litellm
import time

# 提交视频生成任务(异步 Job 模式)
response = litellm.video_generation(
    model="modelslab/text-to-video",
    prompt="城市夜景的延时摄影,航拍视角,4K画质",
    seconds=4,
    size="512x512"
)
job_id = response.id
print(f"已提交任务: {job_id}")

# 轮询任务状态
while True:
    status = litellm.video_status(video_id=job_id)
    print(f"状态: {status.status}")
    if status.status == "completed":
        break
    elif status.status == "failed":
        raise RuntimeError(f"视频生成失败: {status}")
    time.sleep(10)

# 下载视频
video_bytes = litellm.video_content(video_id=job_id)
with open("output.mp4", "wb") as f:
    f.write(video_bytes)

# OpenAI Sora(通过统一接口)
response = litellm.video_generation(
    model="sora/sora-1080p",
    prompt="A serene mountain lake at dawn"
)

注意:视频生成 API 因提供商不同,普遍采用"提交-轮询-下载"的异步 Job 模式,LiteLLM 通过 video_status()video_content() 统一封装了这一流程。


4.10 文本补全(Text Completion)

传统非对话式文本补全接口(相对较少使用):

from litellm import text_completion

response = text_completion(
    model="gpt-3.5-turbo-instruct",
    prompt="Python 中实现快速排序的代码:",
    max_tokens=500,
    temperature=0.3
)
print(response.choices[0].text)

4.11 批处理(Batch)

对应 /batches 端点,适用于大批量离线处理任务,成本通常低 50%。

import litellm

# 创建批处理任务文件
batch_data = [
    {"custom_id": "req-1", "method": "POST", "url": "/v1/chat/completions",
     "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "翻译:Hello World"}]}},
    {"custom_id": "req-2", "method": "POST", "url": "/v1/chat/completions",
     "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "计算 2+2"}]}},
]

# 上传并创建 batch
file_obj = litellm.create_file(
    file=json.dumps(batch_data).encode(),
    purpose="batch",
    custom_llm_provider="openai"
)

batch = litellm.create_batch(
    completion_window="24h",
    endpoint="/v1/chat/completions",
    input_file_id=file_obj.id,
    custom_llm_provider="openai"
)

# 查询状态
status = litellm.retrieve_batch(batch_id=batch.id, custom_llm_provider="openai")
print(status.status)  # validating / in_progress / completed / failed

4.12 Responses API

兼容 OpenAI Responses API,支持内置工具(Web Search、Code Interpreter 等):

import litellm

response = litellm.responses(
    model="openai/o3-deep-research-2025-06-26",
    input="分析 2025 年 AI 行业的最新进展",
    tools=[
        {"type": "web_search_preview"},
        {"type": "code_interpreter", "container": {"type": "auto"}}
    ]
)

5. 多模型路由与负载均衡

这是 LiteLLM 核心差异化能力之一,通过 Router 类实现企业级的智能路由。

5.1 基础路由配置

from litellm import Router

model_list = [
    # 主要 Provider:Azure GPT-4
    {
        "model_name": "gpt-4",
        "litellm_params": {
            "model": "azure/chatgpt-v-2",
            "api_key": "azure-key-1",
            "api_base": "https://endpoint1.openai.azure.com/",
            "rpm": 60,   # 每分钟请求数限制
            "tpm": 90000 # 每分钟 token 数限制
        }
    },
    # 同模型第二个实例(不同 region)
    {
        "model_name": "gpt-4",
        "litellm_params": {
            "model": "azure/chatgpt-v-2",
            "api_key": "azure-key-2",
            "api_base": "https://endpoint2.openai.azure.com/",
            "rpm": 60
        }
    },
    # 故障回退:OpenAI 直连
    {
        "model_name": "gpt-4-fallback",
        "litellm_params": {
            "model": "openai/gpt-4",
            "api_key": "openai-key"
        }
    }
]

router = Router(
    model_list=model_list,
    routing_strategy="usage-based-routing-v2",  # 按剩余容量路由
    num_retries=3,
    fallbacks=[{"gpt-4": ["gpt-4-fallback"]}],
    timeout=30
)

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

5.2 六种路由策略

策略名称 说明 适用场景
simple-shuffle 随机洗牌,默认策略 均等负载分配
least-busy 选择当前并发请求最少的节点 控制并发,防止单点过载
usage-based-routing 按 RPM/TPM 剩余容量选择 精确限流控制
usage-based-routing-v2 增强版,使用 token_counter 预估 更精准的流量控制
latency-based-routing 选择历史平均延迟最低的节点 对延迟敏感的场景
cost-based-routing 选择单次调用成本最低的节点 成本优化优先

5.3 故障回退策略

router = Router(
    model_list=model_list,
    # 通用故障回退
    fallbacks=[{"gpt-4": ["claude-3-opus", "gemini-pro"]}],
    # 上下文窗口溢出时的专用回退
    context_window_fallbacks=[{"gpt-4": ["gpt-4-32k"]}],
    # 内容政策违规时的回退
    content_policy_fallbacks=[{"gpt-4": ["claude-3-opus"]}],
    # 冷却时间(模型失败次数过多后暂停使用的时间)
    cooldown_time=30,
    # 允许每分钟最大失败次数(超过则冷却)
    allowed_fails=3
)

5.4 Proxy 配置文件驱动(config.yaml)

model_list:
  - model_name: claude-primary
    litellm_params:
      model: anthropic/claude-sonnet-4-20250514
      api_key: os.environ/ANTHROPIC_API_KEY
  
  - model_name: claude-vertex-fallback
    litellm_params:
      model: vertex_ai/claude-sonnet-4-20250514
      vertex_project: my-project
  
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: os.environ/OPENAI_API_KEY
      rpm: 500
      tpm: 2000000

router_settings:
  routing_strategy: least-busy
  num_retries: 3
  timeout: 60
  fallbacks:
    - claude-primary:
        - claude-vertex-fallback
  redis_host: redis.example.com  # 多实例共享路由状态
  redis_port: 6379

general_settings:
  master_key: sk-your-master-key

6. 支持的主流 Provider 矩阵

Provider 文本对话 视觉理解 文生图 ASR TTS Embedding Rerank
OpenAI
Anthropic
Google Vertex AI
AWS Bedrock
Azure OpenAI
Cohere
Groq
ElevenLabs
Stability AI
Fal AI
Jina AI
HuggingFace
Ollama(本地)
DeepSeek
Mistral

7. 企业级功能

7.1 成本追踪与预算管理

import litellm

# 开启成本回调
litellm.success_callback = ["langfuse"]  # 或 mlflow、s3 等

response = litellm.completion(
    model="gpt-4o",
    messages=[{"role": "user", "content": "hello"}]
)

# 获取本次调用成本
cost = litellm.completion_cost(completion_response=response)
print(f"本次调用费用: ${cost:.6f}")

Proxy 支持:

  • 按 virtual key 设置预算限额
  • 按团队/项目追踪支出
  • 超额自动拦截

7.2 Guardrails(内容安全护栏)

# config.yaml
guardrails:
  - guardrail_name: "input-safety"
    litellm_params:
      guardrail: aporia  # 或 bedrock-guardrails / lakera / custom
      mode: "during_call"
      api_key: os.environ/APORIA_API_KEY

7.3 缓存

import litellm
from litellm.caching import Cache

# 开启 Redis 缓存
litellm.cache = Cache(type="redis", host="localhost", port=6379)

# 相同请求命中缓存,不再调用 Provider
response = litellm.completion(
    model="gpt-4o",
    messages=[{"role": "user", "content": "2+2=?"}],
    cache={"no-cache": False}  # 使用缓存
)

7.4 可观测性集成

LiteLLM 支持一行代码接入主流可观测性平台:

litellm.success_callback = ["langfuse", "mlflow", "lunary", "helicone"]
litellm.failure_callback = ["langfuse"]

支持的平台:Langfuse、MLflow、Lunary、Helicone、Datadog、S3、GCS、Prometheus 等。

7.5 虚拟 Key 管理(Proxy)

# 创建虚拟 key,设置每日预算 $10,限速 100 RPM
curl -X POST 'http://0.0.0.0:4000/key/generate' \
  -H 'Authorization: Bearer sk-master-key' \
  -d '{
    "budget_duration": "1d",
    "max_budget": 10,
    "rpm_limit": 100,
    "models": ["gpt-4o", "claude-sonnet-4"]
  }'

8. 典型使用场景

场景一:RAG 知识库系统

典型链路:文档嵌入 → 向量检索 → 重排序 → 生成答案

from litellm import embedding, rerank, completion

# 1. 文档向量化(选用性价比高的嵌入模型)
def embed_docs(texts):
    response = embedding(
        model="text-embedding-3-small",
        input=texts
    )
    return [item["embedding"] for item in response.data]

# 2. 检索后重排序(提升精度)
def rerank_docs(query, retrieved_docs):
    response = rerank(
        model="cohere/rerank-english-v3.0",
        query=query,
        documents=retrieved_docs,
        top_n=3
    )
    return [retrieved_docs[r.index] for r in response.results]

# 3. 生成答案(主模型 + 故障回退)
def generate_answer(query, context):
    response = completion(
        model="openai/gpt-4o",
        messages=[
            {"role": "system", "content": f"基于以下上下文回答问题:\n{context}"},
            {"role": "user", "content": query}
        ]
    )
    return response.choices[0].message.content

场景二:多模态内容处理管线

from litellm import transcription, completion, image_generation, speech

# 音频 → 文本 → 摘要 → 配图 → 朗读
def multimodal_pipeline(audio_file_path):
    # 1. ASR:语音转文字
    with open(audio_file_path, "rb") as f:
        transcript = transcription(model="whisper-1", file=f)
    text = transcript.text

    # 2. LLM:生成摘要
    summary_resp = completion(
        model="anthropic/claude-sonnet-4-20250514",
        messages=[{"role": "user", "content": f"请为以下内容生成100字摘要:{text}"}]
    )
    summary = summary_resp.choices[0].message.content

    # 3. 文生图:为摘要配图
    img_resp = image_generation(
        model="dall-e-3",
        prompt=f"为这段内容生成配图:{summary[:200]}",
        size="1024x1024"
    )
    image_url = img_resp.data[0].url

    # 4. TTS:摘要转语音
    audio_resp = speech(
        model="tts-1-hd",
        input=summary,
        voice="nova"
    )
    with open("summary.mp3", "wb") as f:
        f.write(audio_resp.content)

    return {"summary": summary, "image_url": image_url, "audio": "summary.mp3"}

场景三:多 Provider 成本优化

from litellm import Router

# 策略:优先使用便宜模型,复杂任务升级到强模型
router = Router(
    model_list=[
        {"model_name": "fast-cheap", "litellm_params": {"model": "groq/llama-3.1-8b-instant"}},
        {"model_name": "balanced", "litellm_params": {"model": "openai/gpt-4o-mini"}},
        {"model_name": "powerful", "litellm_params": {"model": "openai/gpt-4o"}},
        {"model_name": "powerful-fallback", "litellm_params": {"model": "anthropic/claude-sonnet-4-20250514"}},
    ],
    routing_strategy="cost-based-routing",
    fallbacks=[{"powerful": ["powerful-fallback"]}]
)

# 简单任务 → 快速便宜模型
response = router.completion("fast-cheap", messages=[{"role": "user", "content": "翻译:Hello"}])

# 复杂推理 → 强模型(自动故障回退到 Claude)
response = router.completion("powerful", messages=[{"role": "user", "content": "分析这篇研究报告..."}])

场景四:企业 AI Gateway 统一管控

适用于大型企业为内部多个业务团队统一提供 AI 服务,无需各团队自行管理 API Key:

业务团队 A ──→ │                        │──→ OpenAI GPT-4o
业务团队 B ──→ │   LiteLLM Proxy        │──→ Azure OpenAI
业务团队 C ──→ │   (AI Gateway)         │──→ AWS Bedrock
内部工具   ──→ │   + 认证/限流/计费/审计 │──→ Anthropic Claude

每个团队持有独立虚拟 key,独立计费,网关层统一做:

  • 身份认证(SSO/LDAP 集成)
  • 预算限额(防止超支)
  • 内容审核(Guardrails)
  • 请求日志(合规审计)

9. 架构设计总结

核心设计原则

是否只有一个接口?——不是。

LiteLLM 的接口设计遵循"按模态分接口,按 Provider 统一"的原则:

✅ 同一模态(如文本对话):无论 OpenAI/Claude/Gemini,用同一个 completion() 接口
❌ 不同模态(如文本 vs 图像):必须用不同接口(completion vs image_generation)

这与 OpenAI 自身的 API 设计哲学一致:

模态 LiteLLM 函数 HTTP 端点
文本对话 + 视觉理解 completion() /chat/completions
文生图 image_generation() /images/generations
图片编辑 image_edit() /images/edits
语音识别 transcription() /audio/transcriptions
语音合成 speech() /audio/speech
向量嵌入 embedding() /embeddings
重排序 rerank() /rerank
视频生成 video_generation() /video/generations

统一化的层次

LiteLLM 在以下层面实现统一:

  1. 接口参数统一:不同 Provider 的参数差异由 LiteLLM 内部适配
  2. 错误类型统一:将各 Provider 的错误映射为 OpenAI 兼容错误类型
  3. 响应格式统一:返回统一的响应对象(ModelResponseImageResponse 等)
  4. 成本计算统一:基于 model_prices_and_context_window.json 统一计价

10. 与同类框架对比

维度 LiteLLM OpenRouter LangChain Portkey
部署方式 SDK + 自托管 Proxy 托管云服务 仅 SDK 托管云服务
数据隐私 完全自控 数据经 OpenRouter 完全自控 数据经 Portkey
Provider 数量 100+ 100+ 部分 100+
负载均衡 ✅ 完整 Router 有限
成本追踪 ✅ 详细
企业功能 ✅ 完整 有限
开源 ✅ Apache 2.0 ❌ 闭源 ✅ MIT ❌ 闭源
多模态 ✅ 全覆盖 部分 部分 部分
延迟开销 8ms P95 网络依赖 极低 网络依赖

11. 最佳实践建议

针对不同团队规模的选型建议

个人开发者 / 小型团队:

  • 直接使用 Python SDK,配合 Router 实现基础的故障回退
  • 不需要部署 Proxy,减少运维负担

中型团队(10-100 人):

  • 部署 LiteLLM Proxy,统一管理 API Key
  • 利用虚拟 Key 为不同项目/环境分配独立限额
  • 接入 Langfuse 做成本追踪和可观测性

大型企业(100+ 人):

  • 多实例 Proxy + Redis 共享路由状态,实现水平扩展
  • 使用 config.yaml 驱动配置,结合 CI/CD 管理
  • 配置 Guardrails 满足合规要求
  • 使用 PostgreSQL 存储虚拟 Key 和使用记录

多模态应用接口选用指南

需求 推荐接口 推荐 Provider
聊天机器人、文本分析 completion() OpenAI GPT-4o / Claude Sonnet
图片理解、OCR、文档分析 completion() + 图像内容 GPT-4o Vision / Claude 3.5 Sonnet
营销素材生成 image_generation() DALL-E 3 / Stability XL
播客/视频字幕 transcription() Whisper-1 / GPT-4o Transcribe
有声书/语音助手 speech() OpenAI TTS-1-HD / ElevenLabs
语义搜索/RAG 嵌入 embedding() text-embedding-3-small
RAG 检索精度提升 rerank() Cohere Rerank v3
短视频内容生成 video_generation() ModelsLab / Sora

关键注意事项

  1. 视觉理解不需要单独接口:图生文直接通过 completion() 传入图像内容即可,LiteLLM 自动处理不同 Provider 的图像格式差异
  2. 视频理解同理:对于支持视频输入的模型(如 Gemini),视频理解也走 completion() 接口
  3. 视频生成是例外:视频生成因其异步 Job 特性,需要单独的 video_generation() + video_status() + video_content() 三步流程
  4. 成本控制:在生产环境务必配置 max_budget 和成本回调,防止意外超支
  5. 流式输出:对话场景建议使用 stream=True,提升用户体验

报告生成时间:2026年3月 | 数据来源:LiteLLM 官方 GitHub、官方文档、DeepWiki 分析

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐