跳至主要内容

LiteLLM:实用示例指南

了解什么是 LiteLLM,以及如何用它统一调用各类 LLM 提供商的 API,涵盖基础 API 用法、错误处理、回退、流式输出、结构化结果与成本跟踪。
· 12分钟 阅读

使用 AI 探索

在不同 LLM 提供商之间切换,不应该迫使您重写整个代码库。但在如今使用多个 AI 服务时,这几乎是常态。每家提供商都有自己的 SDK、认证方式和响应格式。LiteLLM 用统一接口解决了这些问题。

在本教程中,我将介绍 LiteLLM 的主要组成部分,并从基础 API 调用开始,逐步展示流式响应、结构化输出以及成本跟踪的用法。

什么是 LiteLLM?

LiteLLM 是一个开源 Python 库,充当 AI 模型的“通用翻译器”。您无需为每家提供商学习不同的 API,只需使用一个接口即可连接 100 多个 LLM 服务。

该框架由两部分构成:Python SDK 让您一次编写,多处运行;代理服务器则为需要大规模管理 AI 服务的团队和企业提供集中网关。

LiteLLM 还带来以下优势:

  • 内置成本跟踪:在一个仪表板中查看所有提供商的支出,而无需逐个查看账单系统
  • 自动故障转移:当某个提供商宕机或触发限流时,LiteLLM 会自动尝试您的备选方案
  • 自托管选项:如需数据隐私或合规性,您可以在自有服务器上运行全部组件

请注意, OpenRouter 也提供类似的多模型统一接入,但其定价与功能集有所不同。

代理服务器可为每个团队设置支出上限,跨项目跟踪使用量,并集中管理 API 密钥。所有配置均通过简单的 YAML 文件完成。

LiteLLM 适用于不同类型的用户:

  • 个人开发者,希望在不逐一注册账户的情况下测试多个模型
  • 小型团队,需要成本可视化并避免供应商锁定
  • 大型企业,需要集中管理、预算控制和细化的使用分析

该库采用 MIT 许可,完全开源。您可以审阅代码、按需修改,也可为项目贡献代码。

现在您已了解 LiteLLM 的能力,接下来开始配置环境。

先决条件

使用 LiteLLM 前,您需要完成一些准备工作。如果您之前用过 AI 模型,大多数步骤可能已经就绪。

Python 环境

需要 Python 3.7 或更高版本。多数系统已具备,您可以用以下命令检查版本:

import sys
print(f"Python version: {sys.version_info.major}.{sys.version_info.minor}")

安装依赖

安装 LiteLLM 和 python-dotenv,以便管理环境变量:

uv add litellm python-dotenv
# or with pip: pip install litellm python-dotenv

API 密钥

您需要所用提供商的 API 密钥。本文将使用两种模型:

将密钥存入项目目录下的 .env 文件:

OPENAI_API_KEY=your_openai_key_here
ANTHROPIC_API_KEY=your_anthropic_key_here

环境检查

运行以下脚本检查配置:

import os
import sys
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Check Python version
print(f"Python version: {sys.version_info.major}.{sys.version_info.minor}")

# Check LiteLLM
try:
   import litellm
   print("✓ LiteLLM installed")
except ImportError:
   print("✗ LiteLLM not installed")

# Check API keys
openai_key = os.getenv("OPENAI_API_KEY")
anthropic_key = os.getenv("ANTHROPIC_API_KEY")

if openai_key:
   print(f"✓ OpenAI API key found")
else:
   print("✗ OpenAI API key not found")

if anthropic_key:
   print(f"✓ Anthropic API key found")
else:
   print("✗ Anthropic API key not found")
Python version: 3.11
✓ LiteLLM installed
✓ OpenAI API key found
✓ Anthropic API key found

如果以上均显示绿色对勾,说明一切就绪。若有检查未通过,请确认依赖已安装且已将 API 密钥添加到 .env 文件。

用 LiteLLM 发起首个 API 调用

LiteLLM 使用与 OpenAI 类似的接口,但可适配任意提供商。

基础配置

先导入如下模块:

import litellm
from dotenv import load_dotenv

# Load your API keys
load_dotenv()

对 GPT-5 的基础请求遵循以下模式:定义消息、调用 litellm.completion(),并获取响应。

messages = [
   {"role": "user", "content": "Write a simple Python function that adds two numbers"}
]

response = litellm.completion(
   model="gpt-5",
   messages=messages
)

print(response.choices[0].message.content)
def add(a, b):
   """Return the sum of a and b."""
   return a + b

您刚刚通过 LiteLLM 调用了GPT-5。响应对象遵循 OpenAI 的格式,如果您使用过他们的 API,这会很熟悉。您可能还想查看实际使用的模型及 Token 用量:

print(f"Model used: {response.model}")
print(f"Response ID: {response.id}")
print(f"Total tokens: {response.usage.total_tokens}")
Model used: gpt-5-2025-08-07
Response ID: chatcmpl-CIbZWUDE1amW2vHtHDmieTX6hnZUq
Total tokens: 557

切换提供商

LiteLLM 的真正威力在于切换提供商。想试试Claude Sonnet 4?只需改一个参数:

response = litellm.completion(
   model="anthropic/claude-sonnet-4-20250514",
   messages=messages
)

print(response.choices[0].message.content)
Here's a simple Python function that adds two numbers:

def add_numbers(a, b):
   """
   Adds two numbers and returns the result.
  
   Args:
       a: First number
       b: Second number
  
   Returns:
       The sum of a and b
   """
   return a + b

# Example usage:
result = add_numbers(5, 3)
print(result)  # Output: 8

This function:
- Takes two parameters a and b
- Returns their sum using the + operator
- Works with integers, floats, and even negative numbers
- Includes a docstring to explain what the function does

相同的代码结构,不同的提供商。Claude 给出更详尽的响应,包含文档与示例;而 GPT-5 更为简洁。

基础错误处理

为可能的异常添加基础错误处理:

try:
   response = litellm.completion(
       model="gpt-5",
       messages=messages
   )
   print(response.choices[0].message.content)
except Exception as e:
   print(f"API call failed: {e}")

此模式可捕获常见问题,如无效 API 密钥、网络故障或模型不可用。

下一步

您已掌握在任意提供商上使用 LiteLLM 的基本模式。入门文档涵盖了更多支持的模型及参数说明,Completion 函数参考展示了全部可用选项。

在构建生产级应用时,您还应遵循API 设计最佳实践,以打造可靠且高性能的系统。

提供商切换与回退

LiteLLM 的回退系统可自动处理提供商故障,避免用户看到报错。在构建真实应用时,您需要无需额外编码即可工作的备选方案。

基础回退配置

要设置回退,在调用中添加 fallbacks 列表:

messages = [
   {"role": "user", "content": "Explain what a Python decorator is in one sentence"}
]

response = litellm.completion(
   model="gpt-5",
   messages=messages,
   fallbacks=["anthropic/claude-sonnet-4-20250514"]
)

print(f"Response: {response.choices[0].message.content}")
print(f"Model used: {response.model}")
Response: A Python decorator is a callable that wraps another function or class to augment its behavior and returns it, applied with the @ syntax so you can add reusable functionality without changing the original code.
Model used: gpt-5-2025-08-07

如果 GPT-5 失败,LiteLLM 会自动尝试 Claude Sonnet 4。无论如何,用户都能得到响应。

构建回退链

您可以串联多个提供商以提升可靠性。继续使用上面的消息:

response = litellm.completion(
   model="gpt-5",
   messages=messages,
   fallbacks=["anthropic/claude-sonnet-4-20250514", "gpt-3.5-turbo"]
)

print(f"Model used: {response.model}")
Model used: gpt-5-2025-08-07

LiteLLM 会按顺序尝试模型。主模型失败则尝试第一个回退,再失败则尝试第二个。多层保护更稳妥。

添加重试

结合回退与重试,进一步提升可靠性:

response = litellm.completion(
   model="gpt-5",
   messages=messages,  # Same messages as before
   num_retries=2
)

在转向回退前,对同一模型重试两次。适合暂时的网络波动或突发限流。

回退能自动处理大多数失败,但仍应捕获全部模型均失败的情况:

try:
   response = litellm.completion(
       model="gpt-5",
       messages=messages,  # Same messages as before
       fallbacks=["anthropic/claude-sonnet-4-20250514"],
       num_retries=2
   )
   return response.choices[0].message.content
except Exception as e:
   # All models failed - handle gracefully
   return "Sorry, I'm having trouble right now. Please try again."

即使提供商运行正常,用户仍可能遇到另一个问题:令人沮丧的等待。有人在您的应用中点击提交,几秒钟内看不到任何反馈,会怀疑是否出错。

用流式传输实现实时响应

多数 AI API 的响应一次性返回,类似下载文件。在完整响应就绪前,用户不会得到任何反馈。流式传输改变了这一点,随着文本生成逐字显示。

为什么流式输出能改善体验

相比等待完整响应,流式会在 AI 生成时即时显示文本。看看差异:

import litellm
from dotenv import load_dotenv

load_dotenv()

messages = [{"role": "user", "content": "What is Python in one sentence?"}]

response = litellm.completion(
   model="gpt-5",
   messages=messages,
   stream=True
)

for chunk in response:
   if chunk.choices[0].delta.content:
       print(chunk.choices[0].delta.content, end="", flush=True)
Python is a high-level, interpreted, dynamically typed, general-purpose programming language known for its readability and vast ecosystem, used across web development, data science, automation, scripting, and more.

文本会逐步出现,而非一次性显示(在您的机器上运行上述片段时)。用户能立即看到进度,比盯着加载旋转图标的体验好得多。

流式传输的工作原理

这是基于分片(chunk)进行的。您拿到的是许多小片段(delta),而非一个完整响应。有时片段为空,因此应妥善处理以确保稳健:

response = litellm.completion(
   model="anthropic/claude-sonnet-4-20250514",
   messages=[{"role": "user", "content": "Define JavaScript in exactly two sentences"}],
   stream=True
)

for chunk in response:
   if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:
       print(f"'{chunk.choices[0].delta.content}'", end=" ")
'JavaScript is a high' '-level, interpreted programming language primarily used for creating' ' interactive and dynamic content on web pages, running' ' in web browsers to manip' 'ulate HTML elements, handle user events' ', and communicate with servers.' ' Originally designed for client-side web development, JavaScript has evolve' 'd into a versatile language that can also' ' be used for server-side development, mobile applications' ', and desktop software through various runtime' ' environments like Node.js.'

让流式输出可复用

在真实应用中,您既要流式展示,也要获取完整响应。下面这个函数可以两者兼顾:

def stream_and_capture(model, messages):
   """Stream response while capturing the complete text"""
   response = litellm.completion(
       model=model,
       messages=messages,
       stream=True
   )
  
   full_response = ""
   for chunk in response:
       if chunk.choices[0].delta.content:
           content = chunk.choices[0].delta.content
           print(content, end="", flush=True)
           full_response += content
  
   print()  # New line after response
   return full_response

# Test it
messages = [{"role": "user", "content": "Define APIs in 2 sentences max"}]
result = stream_and_capture("gpt-5", messages)
APIs (Application Programming Interfaces) are standardized contracts, often exposed as endpoints, that specify how software components or services can communicate, including the allowed operations, inputs, and outputs. They let developers access functionality or data without knowing the underlying implementation, enabling modular, interoperable systems.

参数 end="" 可避免在片段间换行;flush=True 强制立即显示而非缓冲。

带回退的流式输出

您也可以将流式与回退系统结合,以提升可靠性:

response = litellm.completion(
   model="gpt-5",
   messages=[{"role": "user", "content": "Define machine learning in one sentence"}],
   fallbacks=["anthropic/claude-sonnet-4-20250514"],
   stream=True
)

for chunk in response:
   if chunk.choices[0].delta.content:
       print(chunk.choices[0].delta.content, end="", flush=True)
Machine learning is a branch of artificial intelligence where algorithms learn patterns from data to make predictions or decisions without being explicitly programmed.

即时反馈加上主模型失败时的自动切换。

流式输出让用户立即看到反馈,但在构建真实应用时还面临另一问题:文本到达后,您的代码需要对其进行处理。您可能要提取数据、写入数据库或传递给其他函数。纯文本解析既麻烦,又容易因格式变化而出错。

使用结构化输出

实际情况是这样的:您构建了一个分析客户反馈的应用。AI 返回的文本类似“情感为正向,置信度 0.85,关键词:responsive、helpful、fast。”您写了正则来提取置信度与关键词,测试一切正常。

随后 AI 稍微改变了响应格式为“情感:正向(置信度:0.85)。关键词包括 responsive、helpful 和 fast。”您的正则失效,数据管道停摆,客户情感报告不再显示得分,仪表盘崩溃。您花数小时修复昨天还正常的解析代码。

结构化输出从一开始就以可预测的格式返回数据,从而绕开此问题。

获取 JSON 而非文本

LiteLLM 可返回 JSON 而非纯文本。您在提示词中声明所需结构,它会按要求格式化返回:

import litellm
from dotenv import load_dotenv

load_dotenv()

messages = [{"role": "user", "content": "Describe Python as a programming language. Return as JSON with fields: language, difficulty, description"}]

response = litellm.completion(
   model="gpt-5",
   messages=messages,
   response_format={"type": "json_object"}
)

print(response.choices[0].message.content)
{
 "language": "Python",
 "difficulty": "Beginner-friendly (easy to learn, moderate to master)",
 "description": "Python is a high-level, interpreted, dynamically typed, general-purpose programming language focused on readability and developer productivity. It supports multiple paradigms (object-oriented, functional, procedural), uses indentation for block structure, and includes a large standard library with an extensive third-party ecosystem (PyPI). Common uses include web development, data science, machine learning, automation/scripting, scientific computing, and DevOps. While not the fastest for CPU-bound tasks, it integrates well with C/C++ and accelerators, and runs cross-platform."
}

这种结构化方式能消除常见的解析问题。无需在文本中东翻西找,您会得到包含所请求字段的有效 JSON。没有解析头疼,也没有格式意外。

使用 JSON 数据

原始 JSON 字符串需先转换为 Python 对象,才能在应用中使用:您需要把字符串转成可操作的 Python 对象:

import json

messages = [{"role": "user", "content": "Describe JavaScript in 2 sentences. Return as JSON with fields: name, paradigm, use_cases (array of exactly 3 items)"}]

response = litellm.completion(
   model="anthropic/claude-sonnet-4-20250514",
   messages=messages,
   response_format={"type": "json_object"}
)

# Parse the JSON response
data = json.loads(response.choices[0].message.content)
print(f"Language: {data['name']}")
print(f"Paradigm: {data['paradigm']}")
print(f"Use cases: {', '.join(data['use_cases'])}")
Language: JavaScript
Paradigm: multi-paradigm (object-oriented, functional, event-driven)
Use cases: web development and browser scripting, server-side development with Node.js, mobile app development with frameworks like React Native

有了结构化数据,您可以直接传给其他函数、存入数据库或展示在界面中,而无需任何文本处理。对于数据分析工作流,诸如Pandas AI 等工具可直接利用该结构化输出生成洞见。

用 Pydantic 增强类型安全

JSON 解析能发现语法错误,但数据类型错误或缺失字段则是另一回事。Pydantic 模型通过校验数据结构,在问题破坏应用前将其拦截:

from pydantic import BaseModel
import json

class ProgrammingLanguage(BaseModel):
   name: str
   paradigm: str
   use_cases: list[str]

messages = [{"role": "user", "content": "Describe CSS briefly. Return as JSON with fields: name, paradigm, use_cases (array of 3 items)"}]

response = litellm.completion(
   model="gpt-5",
   messages=messages,
   response_format={"type": "json_object"}
)

# Parse and validate with Pydantic
data = json.loads(response.choices[0].message.content)
language = ProgrammingLanguage(**data)

print(f"Validated data: {language.name} - {language.paradigm}")
print(f"Use cases: {language.use_cases}")
Validated data: CSS (Cascading Style Sheets) - Declarative, rule-based stylesheet language for describing the presentation of structured documents.
Use cases: ['Styling layout, colors, and typography of web pages', 'Responsive design across devices and viewports', 'Animations, transitions, and visual effects']

Pydantic 会自动校验 name 与 paradigm 为字符串,以及 use_cases 为字符串列表。若 AI 返回了错误类型或遗漏必需字段,您会得到清晰的报错,而非后续的莫名其妙的缺陷。

处理 JSON 错误

若 AI 返回的不符合 JSON 语法或不是 JSON,解析会失败。添加基础错误处理:

import json

messages = [{"role": "user", "content": "Summarize machine learning in 1 sentence. Return as JSON with topic and summary fields"}]

try:
   response = litellm.completion(
       model="anthropic/claude-sonnet-4-20250514",
       messages=messages,
       response_format={"type": "json_object"}
   )
  
   data = json.loads(response.choices[0].message.content)
   print(f"Topic: {data['topic']}")
   print(f"Summary: {data['summary']}")
  
except json.JSONDecodeError:
   print("Invalid JSON returned")
except Exception as e:
   print(f"Request failed: {e}")
Topic: machine learning
Summary: Machine learning is a subset of artificial intelligence that allows computers to learn and make predictions or decisions from data without being explicitly programmed for each specific task.

结构化输出用干净的数据结构替代凌乱的文本解析。与常规补全一样,JSON 模式也可搭配回退使用。

结构化输出让您获得稳定、可预测的数据,不会轻易“拖垮”解析逻辑。但从原型走向生产,还会遇到另一个问题:账单。每次 API 调用都要花钱,成本可能让您措手不及。

成本跟踪

比如:您的原型在测试时每天 50 次调用,每周花费约 2 美元,一切看起来都很好。上线后有了 500 名用户,每天调用变为 5,000 次。月账单从 8 美元飙升到 800 美元。

没有成本跟踪,您就不会得到预警。您无法判断哪些功能最贵、哪些模型成本更高,也无法为增长做好预算。直到几周后信用卡账单寄来,才发现支出激增。

LiteLLM 可精确追踪您在所有提供商上的花费。

理解 Token 用量

每条 AI 响应都包含详尽的使用信息,清楚地展示您被计费的内容:

import litellm
from dotenv import load_dotenv

load_dotenv()

messages = [{"role": "user", "content": "Explain what a REST API is in two sentences"}]

response = litellm.completion(
   model="gpt-5",
   messages=messages
)

print(f"Response: {response.choices[0].message.content}")
print(f"Prompt tokens: {response.usage.prompt_tokens}")
print(f"Completion tokens: {response.usage.completion_tokens}")
print(f"Total tokens: {response.usage.total_tokens}")
Response: A REST API is a web service that follows the Representational State Transfer architectural style, exposing resources identified by URLs and manipulated with HTTP methods like GET, POST, PUT, and DELETE. It uses stateless client-server communication, cacheability, and uniform representations (often JSON) to support scalable, decoupled interactions.
Prompt tokens: 15
Completion tokens: 201
Total tokens: 216

输入 Token 来自您的提示,输出 Token 来自 AI 的响应。不同提供商对两者的计价不同。

自动计算成本

仅有 Token 数并不能告诉您花了多少钱。LiteLLM 会为您计算实际成本:

# Get the cost for a completed response
cost = litellm.completion_cost(completion_response=response)
print(f"Total cost: ${cost:.4f}")
Total cost: $0.0020

LiteLLM 的定价数据库会根据模型将 Token 转换为美元金额。

手动计算成本

有时您想在调用前预估成本,或为已有文本计算成本:

# Calculate cost without making an API call
prompt_text = "Explain machine learning"
completion_text = "Machine learning is a method of data analysis that automates analytical model building."

estimated_cost = litellm.completion_cost(
   model="anthropic/claude-sonnet-4-20250514",
   prompt=prompt_text,
   completion=completion_text
)

print(f"Estimated cost: ${estimated_cost:.4f}")
Estimated cost: $0.0002

这对于做预算和模型对比很有用。

跟踪多次 API 调用

对于会进行多次调用的应用,您可以累计跟踪成本:

total_cost = 0.0

conversation = [
   "What is Python?",
   "How do you install Python packages?",
   "What are virtual environments?"
]

for i, question in enumerate(conversation):
   response = litellm.completion(
       model="gpt-5",
       messages=[{"role": "user", "content": question}]
   )
  
   call_cost = litellm.completion_cost(completion_response=response)
   total_cost += call_cost
  
   print(f"Call {i+1}: ${call_cost:.4f}")

print(f"Total cost: ${total_cost:.4f}")
Call 1: $0.0057
Call 2: $0.0134
Call 3: $0.0102
Total cost: $0.0292

成本跟踪可帮助您合理选择模型,避免“账单惊喜”。清晰了解每次调用的成本,并可对比不同提供商。

结语

现在,您已经具备在不被供应商锁定的前提下构建 AI 应用的工具。您学会了基础 API 调用、自动回退、流式响应、结构化输出以及成本跟踪。

这将赋予您为每个任务自由选择最佳模型的能力。轻松切换提供商、设置自动回退并跟踪成本。当更优秀的模型出现时,您无需重写代码即可采纳。

Bexruz (Bex) Tuychiev

作者

Bexruz (Bex) Tuychiev

我是一名数据科学内容创作者,拥有超过 2 年的经验,并在 Medium 上拥有较大的读者群。我喜欢用略带讽刺的笔调撰写有关 AI 和机器学习的深度文章——毕竟总得想点办法让这些内容不那么枯燥。我已发表 130 多篇文章,并制作了一门 DataCamp 课程,另有一门正在筹备中。我的内容已被超过 500 万人次阅读,其中有 2 万人在 Medium 和 LinkedIn 上成为关注者。 

主题