開始使用
curl -fsSL https://raw.githubusercontent.com/BerriAI/litellm/main/scripts/quickstart.sh | shLiteLLM 是一個開源函式庫,可讓您使用 OpenAI 格式,透過單一、統一的介面呼叫 100+ 個 LLM(OpenAI、Anthropic、Vertex AI、Bedrock 等)。
- 使用相同的
completion()介面呼叫任何提供者,無需為每個提供者重新學習 API - 無論使用哪個提供者或模型,都能取得一致的輸出格式
- 透過 Router 在多個部署之間內建重試 / 備援邏輯
- 自我託管的 LLM Gateway (Proxy),具備虛擬金鑰、成本追蹤與管理介面
安裝
uv add litellm
若要部署完整的 AI Gateway (Proxy) 與管理介面,請依照 快速開始;其以容器執行,無需 Python 設定。若要改為從 CLI 執行,請參閱 Gateway 快速開始。
快速開始
使用您選擇的提供者進行第一次 LLM 請求:
- OpenAI
- Anthropic
- Vertex AI
- Bedrock
- Ollama
- Azure OpenAI
from litellm import completion
import os
os.environ["OPENAI_API_KEY"] = "your-api-key"
response = completion(
model="openai/gpt-5.6-terra",
messages=[{"role": "user", "content": "Hello, how are you?"}]
)
print(response.choices[0].message.content)
from litellm import completion
import os
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"
response = completion(
model="anthropic/claude-sonnet-5",
messages=[{"role": "user", "content": "Hello, how are you?"}]
)
print(response.choices[0].message.content)
from litellm import completion
import os
# auth: run 'gcloud auth application-default login'
os.environ["VERTEXAI_PROJECT"] = "your-project-id"
os.environ["VERTEXAI_LOCATION"] = "us-central1"
response = completion(
model="vertex_ai/gemini-3.1-pro-preview",
messages=[{"role": "user", "content": "Hello, how are you?"}]
)
print(response.choices[0].message.content)
from litellm import completion
import os
os.environ["AWS_ACCESS_KEY_ID"] = "your-key"
os.environ["AWS_SECRET_ACCESS_KEY"] = "your-secret"
os.environ["AWS_REGION_NAME"] = "us-east-1"
response = completion(
model="bedrock/us.anthropic.claude-sonnet-5",
messages=[{"role": "user", "content": "Hello, how are you?"}]
)
print(response.choices[0].message.content)
from litellm import completion
response = completion(
model="ollama/llama3",
messages=[{"role": "user", "content": "Hello, how are you?"}],
api_base="http://localhost:11434"
)
print(response.choices[0].message.content)
from litellm import completion
import os
os.environ["AZURE_API_KEY"] = "your-key"
os.environ["AZURE_API_BASE"] = "https://your-resource.openai.azure.com"
os.environ["AZURE_API_VERSION"] = "2024-02-01"
response = completion(
model="azure/your-deployment-name",
messages=[{"role": "user", "content": "Hello, how are you?"}]
)
print(response.choices[0].message.content)
無論使用哪個提供者,每個回應都遵循 OpenAI Chat Completions 格式。✅
回應格式
非串流回應會回傳一個 ModelResponse 物件:
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1677858242,
"model": "gpt-5.6-terra",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! I'm doing well, thanks for asking."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 13,
"completion_tokens": 12,
"total_tokens": 25
}
}
串流回應(stream=True)會產生 ModelResponseStream 區塊:
{
"id": "chatcmpl-abc123",
"object": "chat.completion.chunk",
"created": 1677858242,
"model": "gpt-5.6-terra",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"content": "Hello"
},
"finish_reason": null
}
]
}
LiteLLM 新手?
想要快速開始嗎? 請前往 教學,查看 AI 程式撰寫工具、代理程式 SDK、Proxy 設定等逐步導覽。
需要了解特定功能嗎? 查看 指南,了解串流、函式呼叫、提示快取及其他操作說明。
選擇您的路徑
- completion()、embedding()、image_generation() 等更多功能
- 具備重試、備援與負載平衡的 Router
- 跨所有提供者相容於 OpenAI 的例外狀況
- 可觀測性回呼(Langfuse、MLflow、Helicone…)
- 具備每個金鑰/團隊/使用者預算的虛擬金鑰
- 集中式記錄、防護欄與快取
- 用於監控與管理的管理介面
- 可直接替代任何相容 OpenAI 的 client
LiteLLM Python SDK
串流
加入 stream=True 以在區塊產生時接收它們:
from litellm import completion
import os
os.environ["OPENAI_API_KEY"] = "your-api-key"
for chunk in completion(
model="openai/gpt-5.6-terra",
messages=[{"role": "user", "content": "Write a short poem"}],
stream=True,
):
print(chunk.choices[0].delta.content or "", end="")
例外狀況處理
LiteLLM 會將每個提供者的錯誤對應到 OpenAI 例外類型,因此您既有的錯誤處理仍可正常運作:
import litellm
try:
litellm.completion(
model="anthropic/claude-sonnet-5",
messages=[{"role": "user", "content": "Hey!"}]
)
except litellm.AuthenticationError as e:
print(f"Bad API key: {e}")
except litellm.RateLimitError as e:
print(f"Rate limited: {e}")
except litellm.APIError as e:
print(f"API error: {e}")
記錄與可觀測性
只需一行即可將輸入/輸出傳送到 Langfuse、MLflow、Helicone、Lunary 等更多工具:
import litellm
litellm.success_callback = ["langfuse", "mlflow", "helicone"]
response = litellm.completion(
model="gpt-5.6-terra",
messages=[{"role": "user", "content": "Hi!"}]
)
追蹤成本與用量
使用回呼來擷取每個回應的成本:
import litellm
def track_cost(kwargs, completion_response, start_time, end_time):
print("Cost:", kwargs.get("response_cost", 0))
litellm.success_callback = [track_cost]
litellm.completion(
model="gpt-5.6-terra",
messages=[{"role": "user", "content": "Hello!"}],
stream=True
)
📖 自訂回呼文件 →
LiteLLM Proxy Server (LLM 閘道)
該 proxy 是一個自我託管、相容 OpenAI 的 gateway。任何可搭配 OpenAI 使用的用戶端,都可直接與該 proxy 搭配使用,無需變更程式碼。
步驟 1:啟動 proxy
- LiteLLM CLI
- Docker
litellm --model huggingface/bigcode/starcoder
# Proxy running on http://0.0.0.0:4000
model_list:
- model_name: gpt-5.6-luna
litellm_params:
model: azure/your-deployment
api_base: os.environ/AZURE_API_BASE
api_key: os.environ/AZURE_API_KEY
api_version: "2023-07-01-preview"
docker run \
-v $(pwd)/litellm_config.yaml:/app/config.yaml \
-e AZURE_API_KEY=your-key \
-e AZURE_API_BASE=https://your-resource.openai.azure.com/ \
-p 4000:4000 \
docker.litellm.ai/berriai/litellm:latest \
--config /app/config.yaml --detailed_debug
步驟 2:使用 OpenAI client 呼叫它
import openai
client = openai.OpenAI(api_key="anything", base_url="http://0.0.0.0:4000")
response = client.chat.completions.create(
model="gpt-5.6-luna",
messages=[{"role": "user", "content": "Write a short poem"}]
)
print(response.choices[0].message.content)
使用 /utils/transform_request 來精確檢查 LiteLLM 傳送給任何提供者的內容。這在除錯提示格式、標頭問題,以及提供者特定參數時很有幫助。
Agent 與 MCP Gateway
LiteLLM 是一個整合的 LLMs、agents 與 MCP 閘道,因此您不需要另外的 agent 或 MCP gateway。單一端點即可支援 100+ 個模型、A2A agents 與 MCP tools。

