关于 litellm
LiteLLM 是一个 Python 接口,用一致的 OpenAI 格式调用多个 LLM 提供方,适用于需要统一接入和错误处理的应用开发者。它还提供重试与回退、流式调用、成本跟踪和代理服务模式。
主要功能
- 01统一调用 100 多个提供方
- 02映射提供方异常类型
- 03配置重试与回退逻辑
- 04支持同步及异步流式调用
- 05自动跟踪使用量与成本
- 06部署集中式 LLM 网关
适用场景
- 01在多个 LLM 提供方间路由请求
- 02统一处理提供方错误
- 03为调用配置重试与回退
- 04跟踪不同提供方的 LLM 成本
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jamie-bitflight/ claude_skills --skill litellm安装后在 Claude Code 中输入/litellm确认已加载。
详细介绍
LiteLLM
用于调用 100 多种大模型 API 的统一 Python 接口,采用一致的 OpenAI 格式。提供标准化的异常处理、重试和回退逻辑,并支持跨多个提供商跟踪成本。
何时使用此技能
在以下情况下使用此技能:
- 通过单一接口集成多个大模型提供商
- 使用兼容 OpenAI 的端点将请求路由到本地 llamafile 服务
- 为大模型调用实现重试和回退逻辑
- 构建需要在不同提供商之间实现一致错误处理的应用程序
- 跟踪不同提供商的大模型使用成本
- 在提供商专属 API 与 OpenAI 格式之间进行转换
- 使用统一配置部署大模型代理服务
- 针对云端和本地大模型端点测试应用程序
核心功能
提供商支持
LiteLLM 通过一致的 OpenAI 风格 API 支持 100 多种提供商:
- 云端提供商:OpenAI、Anthropic、Google、Azure、AWS Bedrock
- 本地服务:llamafile、Ollama、LocalAI、vLLM
- 统一格式:所有请求均使用 OpenAI 消息格式
- 异常映射:所有提供商错误均映射为 OpenAI 异常类型
主要特性
- 统一 API:所有提供商共用一个
completion()函数 - 异常处理:所有异常均继承自 OpenAI 类型
- 重试逻辑:内置重试功能,支持配置尝试次数
- 流式传输支持:所有提供商均支持同步和异步流式传输
- 成本跟踪:自动计算使用量和成本
- 代理模式:部署集中式大模型网关
安装
# Using pip
pip install litellm
# Using uv
uv add litellm
Llamafile 集成
提供商配置
所有 llamafile 模型都必须使用 llamafile/ 前缀进行路由:
model = "llamafile/mistralai/mistral-7b-instruct-v0.2"
model = "llamafile/gemma-3-3b"
API 基础 URL
api_base 必须指向 llamafile 兼容 OpenAI 的端点:
api_base = "http://localhost:8080/v1"
重要要求:
- 必须包含
/v1后缀 - 不要添加
/chat/completions等端点路径(LiteLLM 会自动添加) - llamafile 的默认端口为 8080
环境变量配置
import os
os.environ["LLAMAFILE_API_BASE"] = "http://localhost:8080/v1"
基本用法模式
同步补全
import litellm
response = litellm.completion(
model="llamafile/mistralai/mistral-7b-instruct-v0.2",
messages=[{"role": "user", "content": "Summarize this diff"}],
api_base="http://localhost:8080/v1",
temperature=0.2,
max_tokens=80,
)
print(response.choices[0].message.content)
异步补全
from litellm import acompletion
import asyncio
async def generate_message():
response = await acompletion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Write a commit message"}],
api_base="http://localhost:8080/v1",
temperature=0.3,
max_tokens=200,
)
return response.choices[0].message.content
result = asyncio.run(generate_message())
print(result)
异步流式传输
from litellm import acompletion
import asyncio
async def stream_response():
response = await acompletion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello, how are you?"}],
api_base="http://localhost:8080/v1",
stream=True,
)
async for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
asyncio.run(stream_response())
嵌入
from litellm import embedding
import os
os.environ["LLAMAFILE_API_BASE"] = "http://localhost:8080/v1"
response = embedding(model="llamafile/sentence-transformers/all-MiniLM-L6-v2", input=["Hello world"])
print(response)
异常处理
导入方式
所有异常都可以直接从 litellm 导入:
from litellm import (
BadRequestError, # 400 errors
AuthenticationError, # 401 errors
NotFoundError, # 404 errors
Timeout, # 408 errors (alias: openai.APITimeoutError)
RateLimitError, # 429 errors
APIConnectionError, # 500 errors / connection issues (default)
ServiceUnavailableError, # 503 errors
)
异常类型参考
| 状态码 | 异常类型 | 继承自 | 说明 |
|---|---|---|---|
| 400 | BadRequestError | openai.BadRequestError | 请求无效 |
| 400 | ContextWindowExceededError | litellm.BadRequestError | 超出令牌限制 |
| 400 | ContentPolicyViolationError | litellm.BadRequestError | 违反内容政策 |
| 401 | AuthenticationError | openai.AuthenticationError | 身份验证失败 |
| 403 | PermissionDeniedError | openai.PermissionDeniedError | 权限不足 |
| 404 | NotFoundError | openai.NotFoundError | 模型或端点无效 |
| 408 | Timeout | openai.APITimeoutError | 请求超时 |
| 429 | RateLimitError | openai.RateLimitError | 触发速率限制 |
| 500 | APIConnectionError | openai.APIConnectionError | 未映射错误的默认类型 |
| 500 | APIError | openai.APIError | 通用 500 错误 |
| 503 | ServiceUnavailableError | openai.APIStatusError | 服务不可用 |
| >=500 | InternalServerError | openai.InternalServerError | 未映射的 500 及以上错误 |
异常属性
所有 LiteLLM 异常都包含:
status_code:HTTP 状态码message:错误消息llm_provider:引发异常的提供方
异常处理示例
import litellm
import openai
try:
response = litellm.completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
timeout=30.0,
)
except openai.APITimeoutError as e:
# LiteLLM exceptions inherit from OpenAI types
print(f"Timeout: {e}")
except litellm.APIConnectionError as e:
print(f"Connection failed: {e.message}")
print(f"Provider: {e.llm_provider}")
从 litellm.exceptions 导入的替代方式
from litellm.exceptions import BadRequestError, AuthenticationError, APIError
try:
response = litellm.completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
)
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except BadRequestError as e:
print(f"Bad request: {e}")
except APIError as e:
print(f"API error: {e}")
检查异常是否应重试
import litellm
try:
response = litellm.completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
)
except Exception as e:
if hasattr(e, "status_code"):
should_retry = litellm._should_retry(e.status_code)
print(f"Should retry: {should_retry}")
重试和回退配置
from litellm import completion
response = completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
num_retries=3, # Retry 3 times on failure
timeout=30.0, # 30 second timeout
)
代理服务配置
对于代理部署,请使用 config.yaml:
model_list:
- model_name: commit-polish-model
litellm_params:
model: llamafile/gemma-3-3b # add llamafile/ prefix
api_base: http://localhost:8080/v1 # add api base for OpenAI compatible provider
应用集成模式
连接验证模式
import litellm
from litellm import APIConnectionError
def verify_llamafile_connection(api_base: str = "http://localhost:8080/v1") -> bool:
"""Check if llamafile server is running."""
try:
litellm.completion(
model="llamafile/test", messages=[{"role": "user", "content": "test"}], api_base=api_base, max_tokens=1
)
return True
except APIConnectionError:
return False
异步服务模式
import litellm
from litellm import acompletion, APIConnectionError
import asyncio
class AIService:
"""LiteLLM wrapper with llamafile routing."""
def __init__(self, model: str, api_base: str, temperature: float = 0.3, max_tokens: int = 200):
self.model = model
self.api_base = api_base
self.temperature = temperature
self.max_tokens = max_tokens
async def generate_commit_message(self, diff: str, system_prompt: str) -> str:
"""Generate a commit message using the LLM."""
try:
response = await acompletion(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Generate a commit message for this diff:\n\n{diff}"},
],
api_base=self.api_base,
temperature=self.temperature,
max_tokens=self.max_tokens,
)
return response.choices[0].message.content.strip()
except APIConnectionError as e:
raise RuntimeError(f"Failed to connect to llamafile server at {self.api_base}: {e.message}")
应避免的常见陷阱
- 缺少
llamafile/前缀:没有此前缀,LiteLLM 就不会将请求路由到兼容 OpenAI 的端点 - 端口错误:Llamafile 默认使用 8080,而不是 8000
- 缺少
/v1后缀:API 基础地址必须以/v1结尾 - 添加额外的路径段:请勿使用
http://localhost:8080/v1/chat/completions——LiteLLM 会自动添加端点路径 - API 密钥要求:本地 llamafile 无需 API 密钥(如果验证要求提供密钥,则使用空字符串或任意值)
配置示例
TOML 配置
# ~/.config/commit-polish/config.toml
[ai]
model = "llamafile/gemma-3-3b" # MUST have llamafile/ prefix
temperature = 0.3
max_tokens = 200
环境变量
export LLAMAFILE_API_BASE="http://localhost:8080/v1"
export LITELLM_LOG="INFO" # Enable LiteLLM debug logging
相关技能
如需了解相关工具的完整文档:
- llamafile:如果你的工作区安装了 llamafile 插件,请使用它进行服务设置、模型管理和本地 LLM 部署。否则,请直接遵循本文档中的端点和模型前缀说明。
- uv:如果你的工作区安装了 Python/uv 插件,请使用它进行项目管理、依赖处理和虚拟环境工作流。否则,请使用标准
uv命令和项目本地环境。
参考资料
官方文档
- LiteLLM 文档 - 主要文档门户
- Llamafile 提供方文档 - Llamafile 专属配置
- 异常映射 - 完整的异常参考
- GitHub 仓库 - 源代码和示例
提供方专属文档
- Llamafile API 端点 - Llamafile 兼容 OpenAI 的 API 参考
- 补全流式传输 - 流式传输实现指南
版本信息
- 文档验证依据:LiteLLM GitHub 仓库(main 分支,访问日期:2025-01-15)
- Python:3.11+
- Llamafile:0.9.3+
评论
支持 Markdown