ITADN
BerriAI/litellm
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

🚅 LiteLLM

LiteLLM AI Gateway

支持 100+ LLM 的开源 AI 网关。自托管。企业级就绪。以 OpenAI 格式调用任意 LLM。

Deploy to Render Deploy on Railway Deploy on AWS Deploy on GCP

LiteLLM 代理服务器 (AI 网关) | 托管代理 | 企业版 | 网站

PyPI Version GitHub Stars Y Combinator W23 Whatsapp Discord
    <img src="https://img.shields.io/static/v1?label=Chat%20on&message=Slack&color=black&logo=Slack&style=flat-square" alt="Slack">
</a>
<a href="https://codspeed.io/BerriAI/litellm?utm_source=badge">
    <img src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" alt="CodSpeed"/>
</a>

LiteLLM AI Gateway

什么是 LiteLLM

LiteLLM 是一个开源的 AI Gateway,为您提供一个统一的接口,以 OpenAI 格式调用 100+ LLM 提供商——OpenAI、Anthropic、Gemini、Bedrock、Azure 等。

您可以将其用作 Python SDK 进行直接的库集成,或者将 AI Gateway (Proxy Server) 部署为团队或组织的集中式服务。

跳转至 LiteLLM Proxy (LLM Gateway) 文档
跳转至支持的 LLM 提供商


为什么选择 LiteLLM

跨提供商管理 LLM 调用会迅速变得复杂——每个模型都有不同的 SDK、认证模式、请求格式和错误类型。LiteLLM 消除了这些摩擦:

  • 统一 API — 一个接口支持 100+ LLM,无需处理特定提供商的 SDK
  • 即插即用的 OpenAI 兼容性 — 无需重写代码即可切换提供商
  • 生产就绪的网关 — 开箱即用的虚拟密钥、支出跟踪、护栏、负载均衡和管理仪表板
  • 8ms P95 延迟 在 1k RPS 下 (基准测试)

OSS 采用者

StripeimageGoogle ADKGreptileOpenHands

Netflix

OpenAI Agents SDK

功能

LLMs - 调用 100+ LLMs(Python SDK + AI Gateway)

所有支持的端点 - /chat/completions/responses/embeddings/images/audio/batches/rerank/a2a/messages 等。

Python SDK

uv add 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": "Hello!"}])

# Anthropic  
response = completion(model="anthropic/claude-sonnet-4-20250514", messages=[{"role": "user", "content": "Hello!"}])

AI 网关(代理服务器)

入门指南 - 端到端教程 - 设置虚拟密钥,发起您的第一个请求

uv tool install 'litellm[proxy]'
litellm --model gpt-4o
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": "Hello!"}]
)

文档:LLM 提供商

Agents - 调用 A2A Agents (Python SDK + AI Gateway)

支持的提供商 - LangGraph, Vertex AI Agent Engine, Azure AI Foundry, Bedrock AgentCore, Pydantic AI

Python SDK - A2A 协议

from litellm.a2a_protocol import A2AClient
from a2a.types import SendMessageRequest, MessageSendParams
from uuid import uuid4

client = A2AClient(base_url="http://localhost:10001")

request = SendMessageRequest(
    id=str(uuid4()),
    params=MessageSendParams(
        message={
            "role": "user",
            "parts": [{"kind": "text", "text": "Hello!"}],
            "messageId": uuid4().hex,
        }
    )
)
response = await client.send_message(request)

AI Gateway (代理服务器)

步骤 1. 将您的 Agent 添加到 AI Gateway — 为每个 agent 将 protocolVersion 设置为 1.00.3

步骤 2. 通过 A2A SDK 调用 Agent(需要 a2a-sdk>=1.1.0

import httpx
from a2a.client import A2ACardResolver, ClientConfig, ClientFactory
from a2a.types import Message, Part, Role, SendMessageRequest
from a2a.utils.constants import TransportProtocol
from uuid import uuid4

base_url = "http://localhost:4000/a2a/my-agent"  # LiteLLM proxy + agent name
headers = {"Authorization": "Bearer sk-1234"}    # LiteLLM Virtual Key

async with httpx.AsyncClient(headers=headers, timeout=60.0) as http_client:
    resolver = A2ACardResolver(httpx_client=http_client, base_url=base_url)
    agent_card = await resolver.get_agent_card()
    config = ClientConfig(
        httpx_client=http_client,
        streaming=False,
        supported_protocol_bindings=[TransportProtocol.JSONRPC, TransportProtocol.HTTP_JSON],
    )
    client = ClientFactory(config).create(agent_card)

    request = SendMessageRequest(
        message=Message(
            message_id=uuid4().hex,
            role=Role.ROLE_USER,
            parts=[Part(text="Hello!")],
        )
    )
    async for event in client.send_message(request):
        populated = event.ListFields()
        if populated and populated[0][0].name in ("message", "msg"):
            print("".join(getattr(p, "text", "") or "" for p in populated[0][1].parts))

文档:A2A Agent Gateway

MCP Tools - 将 MCP 服务器连接到任意 LLM(Python SDK + AI Gateway)

Python SDK - MCP Bridge

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from litellm import experimental_mcp_client
import litellm

server_params = StdioServerParameters(command="python", args=["mcp_server.py"])

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()

        # Load MCP tools in OpenAI format
        tools = await experimental_mcp_client.load_mcp_tools(session=session, format="openai")

        # Use with any LiteLLM model
        response = await litellm.acompletion(
            model="gpt-4o",
            messages=[{"role": "user", "content": "What's 3 + 5?"}],
            tools=tools
        )

AI Gateway - MCP Gateway

Step 1. 将您的 MCP Server 添加到 AI Gateway

Step 2. 通过 /chat/completions 调用 MCP 工具

curl -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
  -H 'Authorization: Bearer sk-1234' \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Summarize the latest open PR"}],
    "tools": [{
      "type": "mcp",
      "server_url": "litellm_proxy/mcp/github",
      "server_label": "github_mcp",
      "require_approval": "never"
    }]
  }'

在 Cursor IDE 中使用

{
  "mcpServers": {
    "LiteLLM": {
      "url": "http://localhost:4000/mcp/",
      "headers": {
        "x-litellm-api-key": "Bearer sk-1234"
      }
    }
  }
}

文档:MCP Gateway

支持的提供商(网站支持的模型 | 文档)

提供商/chat/completions/messages/responses/embeddings/image/generations/audio/transcriptions/audio/speech/moderations/batches/rerank
Abliteration (abliteration)
AI/ML API (aiml)
AI21 (ai21)
AI21 Chat (ai21_chat)
Aleph Alpha
Amazon Nova
Anthropic (anthropic)
Anthropic Text (anthropic_text)
Anyscale
AssemblyAI (assemblyai)
Auto Router (auto_router)
AWS - Bedrock (bedrock)
AWS - Sagemaker (sagemaker)
Azure (azure)
Azure AI (azure_ai)
Azure Text (azure_text)
Baseten (baseten)

| Bytez (bytez) | ✅ | ✅ | ✅ | | | | | | | | | Cerebras (cerebras) | ✅ | ✅ | ✅ | | | | | | | | | Clarifai (clarifai) | ✅ | ✅ | ✅ | | | | | | | | | Cloudflare AI Workers (cloudflare) | ✅ | ✅ | ✅ | | | | | | | | | Codestral (codestral) | ✅ | ✅ | ✅ | | | | | | | | | Cohere (cohere) | ✅ | ✅ | ✅ | ✅ | | | | | | ✅ | | Cohere Chat (cohere_chat) | ✅ | ✅ | ✅ | | | | | | | | | CometAPI (cometapi) | ✅ | ✅ | ✅ | ✅ | | | | | | | | CompactifAI (compactifai) | ✅ | ✅ | ✅ | | | | | | | | | Custom (custom) | ✅ | ✅ | ✅ | | | | | | | | | Custom OpenAI (custom_openai) | ✅ | ✅ | ✅ | | | ✅ | ✅ | ✅ | ✅ | | | Dashscope (dashscope) | ✅ | ✅ | ✅ | ✅ | | | | | | ✅ | | Databricks (databricks) | ✅ | ✅ | ✅ | | | | | | | | | DataRobot (datarobot) | ✅ | ✅ | ✅ | | | | | | | | | Deepgram (deepgram) | ✅ | ✅ | ✅ | | | ✅ | | | | | | DeepInfra (deepinfra) | ✅ | ✅ | ✅ | | | | | | | | | Deepseek (deepseek) | ✅ | ✅ | ✅ | | | | | | | | | ElevenLabs (elevenlabs) | ✅ | ✅ | ✅ | | | ✅ | ✅ | | | | | Empower (empower) | ✅ | ✅ | ✅ | | | | | | | | | Fal AI (fal_ai) | ✅ | ✅ | ✅ | | ✅ | | | | | | | Featherless AI (featherless_ai) | ✅ | ✅ | ✅ | | | | | | | | | Fireworks AI (fireworks_ai) | ✅ | ✅ | ✅ | | | | | | | | | FriendliAI (friendliai) | ✅ | ✅ | ✅ | | | | | | | | | Galadriel (galadriel) | ✅ | ✅ | ✅ | | | | | | | |

| GitHub Copilot (github_copilot) | ✅ | ✅ | ✅ | ✅ | | | | | | | | GitHub Models (github) | ✅ | ✅ | ✅ | | | | | | | | | Google - PaLM | ✅ | ✅ | ✅ | | | | | | | | | Google - Vertex AI (vertex_ai) | ✅ | ✅ | ✅ | ✅ | ✅ | | | | | | | Google AI Studio - Gemini (gemini) | ✅ | ✅ | ✅ | | | | | | | | | GradientAI (gradient_ai) | ✅ | ✅ | ✅ | | | | | | | | | Groq AI (groq) | ✅ | ✅ | ✅ | | | | | | | | | Heroku (heroku) | ✅ | ✅ | ✅ | | | | | | | | | Hosted VLLM (hosted_vllm) | ✅ | ✅ | ✅ | | | | | | | | | Huggingface (huggingface) | ✅ | ✅ | ✅ | ✅ | | | | | | ✅ | | Hyperbolic (hyperbolic) | ✅ | ✅ | ✅ | | | | | | | | | IBM - Watsonx.ai (watsonx) | ✅ | ✅ | ✅ | ✅ | | | | | | | | Infinity (infinity) | | | | ✅ | | | | | | | | Jina AI (jina_ai) | | | | ✅ | | | | | | | | Lambda AI (lambda_ai) | ✅ | ✅ | ✅ | | | | | | | | | Lemonade (lemonade) | ✅ | ✅ | ✅ | | | | | | | | | LiteLLM Proxy (litellm_proxy) | ✅ | ✅ | ✅ | ✅ | ✅ | | | | | | | Llamafile (llamafile) | ✅ | ✅ | ✅ | | | | | | | | | LM Studio (lm_studio) | ✅ | ✅ | ✅ | | | | | | | | | Maritalk (maritalk) | ✅ | ✅ | ✅ | | | | | | | | | Meta - Llama API (meta_llama) | ✅ | ✅ | ✅ | | | | | | | | | Mistral AI API (mistral) | ✅ | ✅ | ✅ | ✅ | | | | | | | | ModelScope (modelscope) | ✅ | ✅ | ✅ | | ✅ | | | | | | | Moonshot (moonshot) | ✅ | ✅ | ✅ | | | | | | | |

| Morph (morph) | ✅ | ✅ | ✅ | | | | | | | | | Nebius AI Studio (nebius) | ✅ | ✅ | ✅ | ✅ | | | | | | | | NLP Cloud (nlp_cloud) | ✅ | ✅ | ✅ | | | | | | | | | Novita AI (novita) | ✅ | ✅ | ✅ | | | | | | | | | Nscale (nscale) | ✅ | ✅ | ✅ | | | | | | | | | Nvidia NIM (nvidia_nim) | ✅ | ✅ | ✅ | | | | | | | | | OCI (oci) | ✅ | ✅ | ✅ | | | | | | | | | Ollama (ollama) | ✅ | ✅ | ✅ | ✅ | | | | | | | | Ollama Chat (ollama_chat) | ✅ | ✅ | ✅ | | | | | | | | | Oobabooga (oobabooga) | ✅ | ✅ | ✅ | | | ✅ | ✅ | ✅ | ✅ | | | OpenAI (openai) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | | OpenAI-like (openai_like) | | | | ✅ | | | | | | | | OpenRouter (openrouter) | ✅ | ✅ | ✅ | | | | | | | | | OVHCloud AI Endpoints (ovhcloud) | ✅ | ✅ | ✅ | | | | | | | | | Perplexity AI (perplexity) | ✅ | ✅ | ✅ | | | | | | | | | Petals (petals) | ✅ | ✅ | ✅ | | | | | | | | | Pinstripes (pinstripes) | ✅ | ✅ | ✅ | | | | | | | | | Predibase (predibase) | ✅ | ✅ | ✅ | | | | | | | | | Recraft (recraft) | | | | | ✅ | | | | | | | Replicate (replicate) | ✅ | ✅ | ✅ | | | | | | | | | Sagemaker Chat (sagemaker_chat) | ✅ | ✅ | ✅ | | | | | | | | | Sambanova (sambanova) | ✅ | ✅ | ✅ | | | | | | | | | Snowflake (snowflake) | ✅ | ✅ | ✅ | | | | | | | | | Text Completion Codestral (text-completion-codestral) | ✅ | ✅ | ✅ | | | | | | | |

| 文本补全 OpenAI (text-completion-openai) | ✅ | ✅ | ✅ | | | ✅ | ✅ | ✅ | ✅ | | | Together AI (together_ai) | ✅ | ✅ | ✅ | | | | | | | | | Topaz (topaz) | ✅ | ✅ | ✅ | | | | | | | | | Triton (triton) | ✅ | ✅ | ✅ | | | | | | | | | V0 (v0) | ✅ | ✅ | ✅ | | | | | | | | | Vercel AI Gateway (vercel_ai_gateway) | ✅ | ✅ | ✅ | | | | | | | | | VLLM (vllm) | ✅ | ✅ | ✅ | | | | | | | | | Volcengine (volcengine) | ✅ | ✅ | ✅ | | | | | | | | | Voyage AI (voyage) | | | | ✅ | | | | | | | | WandB Inference (wandb) | ✅ | ✅ | ✅ | | | | | | | | | Watsonx Text (watsonx_text) | ✅ | ✅ | ✅ | | | | | | | | | xAI (xai) | ✅ | ✅ | ✅ | | | | | | | | | Xinference (xinference) | | | | ✅ | | | | | | |

Read the Docs


快速入门

您可以通过 Proxy Server 或 Python SDK 使用 LiteLLM。两者都为您提供了一个统一的接口,用于访问多个 LLM(100+ LLM)。请选择最适合您需求的选项:

LiteLLM AI GatewayLiteLLM Python SDK
使用场景访问多个 LLM 的中心服务(LLM Gateway)在您的 Python 代码中直接使用 LiteLLM
谁在使用?Gen AI Enablement / ML Platform Teams构建 LLM 项目的开发者
主要功能集中式 API 网关,具备身份验证和授权功能,按项目/用户进行多租户成本跟踪和支出管理,按项目自定义(日志记录、护栏、缓存),用于安全访问控制的虚拟密钥,用于监控和管理的 admin dashboard UI在您的代码库中直接集成 Python 库,跨多个部署(例如 Azure/OpenAI)的具有重试/回退逻辑的 Router - Router,应用级负载均衡和成本跟踪,具有 OpenAI 兼容错误的异常处理,可观测性回调(Lunary, MLflow, Langfuse, 等)

稳定版本: 使用带有 -stable 标签的 docker 镜像。这些镜像在发布前已经过 12 小时负载测试。有关发布周期的更多信息,请参见此处

支持更多提供商。如果缺少某个提供商或 LLM 平台,请提交 功能请求

使用 Terraform 部署到 AWS 或 GCP

使用已发布的 Terraform 模块,将 LiteLLM 代理作为生产就绪的组件化堆栈运行(网关、后端、UI 位于独立服务;托管 Postgres + Redis + 对象存储)。这两个模块均位于 公共 Terraform Registry — 无需身份验证。

AWS — ECS Fargate + Aurora + ElastiCache + ALB

Launch in AWS CloudShell — 打开一个浏览器内的 shell,已认证到您的 AWS 账户。进入后,运行:

git clone https://github.com/BerriAI/litellm.git
cd litellm/terraform/litellm/aws/examples/default
cp terraform.tfvars.example terraform.tfvars   # edit region/tenant/env
terraform init && terraform apply

模块页面 →

或者从您自己的根配置中调用该模块:

# main.tf
terraform {
  required_version = ">= 1.6.0"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.60" }
  }
}

provider "aws" {
  region = "us-west-2"
}

module "litellm" {
  source  = "BerriAI/litellm/aws"
  version = "~> 1.89"

  region = "us-west-2"
  azs    = ["us-west-2a", "us-west-2b"]
  tenant = "acme"
  env    = "prod"

  # Production: provide an ACM cert. Without one, set allow_plaintext_alb = true
  # (dev/trial only).
  # acm_certificate_arn = "arn:aws:acm:us-west-2:111122223333:certificate/..."
  allow_plaintext_alb = true
}

output "litellm_url" {
  value = module.litellm.alb_dns_name
}
terraform init
terraform apply

Provider API 密钥存储在 AWS Secrets Manager 中;通过 gateway_extra_secrets 引用 ARN。完整的输入列表和架构图见 注册表页面

GCP — Cloud Run + Cloud SQL + Memorystore + HTTPS LB

Open in Cloud Shell

真正的 1 键操作。打开 Cloud Shell,克隆此仓库,并通过内置的 DeployStack 教程 引导你完成 terraform apply —— 选择项目后,教程会设置 Artifact Registry 远程仓库,根据你的回答编写 terraform.tfvars,并运行 apply。

模块页面 →

若要改为从你自己的配置中调用该模块,由于 Cloud Run 无法直接从 ghcr.io 拉取,因此首先需设置一个由 GHCR 支持的 Artifact Registry 一次性远程仓库:

gcloud artifacts repositories create litellm \
  --location=us-central1 \
  --repository-format=docker \
  --mode=remote-repository \
  --remote-docker-repo=https://ghcr.io \
  --project=my-gcp-project

然后:

# main.tf
terraform {
  required_version = ">= 1.6.0"
  required_providers {
    google      = { source = "hashicorp/google",      version = "~> 6.10" }
    google-beta = { source = "hashicorp/google-beta", version = "~> 6.10" }
  }
}

provider "google"      { project = "my-gcp-project"; region = "us-central1" }
provider "google-beta" { project = "my-gcp-project"; region = "us-central1" }

module "litellm" {
  source  = "BerriAI/litellm/google"
  version = "~> 1.89"

  project_id = "my-gcp-project"
  region     = "us-central1"
  tenant     = "acme"
  env        = "prod"

  # Replace my-gcp-project with your GCP project ID (same value as project_id above).
  image_registry = "us-central1-docker.pkg.dev/my-gcp-project/litellm/berriai"

  # Production: provide DNS already pointing at the LB IP for Google-managed certs.
  # Without one, set allow_plaintext_lb = true (dev/trial only).
  # lb_domains         = ["proxy.example.com"]
  allow_plaintext_lb = true
}

output "litellm_url" {
  value = module.litellm.load_balancer_url
}
terraform init
terraform apply

Provider API 密钥存储在 Secret Manager 中;通过 gateway_extra_secrets 引用资源 ID(例如 projects/my-gcp-project/secrets/openai-api-key)。完整的输入列表和架构图位于 registry 页面

两个栈均包含

  • 完整的组件化拆分(网关 / 后端 / UI 作为独立服务)
  • 托管 Postgres(写入器 + 读取器)和 Redis
  • 用于代理状态 + 文件上传的版本化对象存储
  • 在您的云密钥管理器中自动生成的 LITELLM_MASTER_KEY
  • 在代理启动前运行 prisma migrate deploy 的一次性迁移任务
  • Helm chart 相同的 proxy_config 接口 — 将 YAML 作为类型化映射传入

Terraform 模块位于本仓库的 terraform/litellm/aws/terraform/litellm/gcp/;注册表条目是每次发布时更新的只读镜像。

以开发者模式运行

服务

  1. 在根目录设置 .env 文件
  2. 运行依赖服务 docker-compose up db prometheus

Backend

  1. Run make bootstrap
  2. Start proxy backend: uv run python litellm/proxy/proxy_cli.py

前端

  1. 导航至 ui/litellm-dashboard(依赖项已通过 make bootstrap 安装)
  2. 启动仪表盘:npm run dev

验证 Docker 镜像签名

所有发布到 GHCR 的 LiteLLM Docker 镜像均使用 cosign 进行签名。每个版本都使用在 commit 0112e53 中引入的同一密钥进行签名。

使用固定的提交哈希值进行验证(推荐):

提交哈希在密码学上是不可变的,因此这是确保你正在使用原始签名密钥的最强方式:

cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/0112e53046018d726492c814b3644b7d376029d0/cosign.pub \
  ghcr.io/berriai/litellm:<release-tag>

使用发布标签进行验证(便捷方式):

此仓库中的标签受保护,并解析为相同的密钥。此选项更易读,但依赖于标签保护规则:

cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/<release-tag>/cosign.pub \
  ghcr.io/berriai/litellm:<release-tag>

<release-tag> 替换为您正在部署的版本(例如 v1.83.0-stable)。


Enterprise

面向需要更高安全性、用户管理和专业支持的企业

获取企业许可证 与创始人洽谈

涵盖内容:

  • LiteLLM 商业许可证下的功能:
  • 功能优先级排序
  • 自定义集成
  • 专业支持 - 专属 discord + slack
  • 自定义 SLA
  • 通过单点登录实现安全访问

贡献

我们欢迎对 LiteLLM 的贡献!无论是修复 bug、添加功能还是改进文档,我们都感谢您的帮助。

贡献者快速入门

这需要安装 uv。

git clone https://github.com/BerriAI/litellm.git
cd litellm
make install-dev    # Install development dependencies
make format         # Format your code
make lint           # Run all linting checks
make test-unit      # Run unit tests
make format-check   # Check formatting only

有关详细的贡献指南,请参阅 CONTRIBUTING.md

📖 贡献文档? LiteLLM 文档已迁移至独立仓库:BerriAI/litellm-docs。请在那里提交文档 PR。文档托管于 docs.litellm.ai

代码质量 / 代码检查

LiteLLM 遵循 Google Python Style Guide

我们的自动化检查包括:

  • Black 用于代码格式化
  • Ruff 用于代码检查和代码质量
  • MyPy 用于类型检查
  • 循环导入检测
  • 导入安全检查

在您的 PR 被合并之前,必须通过所有这些检查。

支持 / 与创始人交流

贡献者