跳至主要内容

概述

在 config.yaml 中设置模型列表、api_baseapi_keytemperature 以及代理服务器设置(master-key)。

参数名称描述
model_list服务器上支持的模型列表,包含模型特定的配置
router_settingslitellm 路由设置,例如 routing_strategy="least-busy" 查看全部
litellm_settingslitellm 模块设置,例如 litellm.drop_params=True, litellm.set_verbose=True, litellm.api_base, litellm.cache 查看全部
general_settings服务器设置,例如设置 master_key: sk-my_special_key
environment_variables环境变量示例,REDIS_HOST, REDIS_PORT

完整列表: 查看 <your-proxy-url>/#/config.yaml(例如 http://0.0.0.0:4000/#/config.yaml)上的 Swagger UI 文档,了解所有可在 config.yaml 中传递的配置。

快速入门

为您的部署设置模型别名。

config.yaml 中,model_name 参数是用户端看到的用于部署的名称。

在下方的配置中

  • model_name:外部客户端传递给 litellm 的名称
  • litellm_params.model:传递给 litellm.completion() 函数的模型字符串

例如:

  • model=vllm-models 将路由至 openai/facebook/opt-125m
  • model=gpt-4o 将在 azure/gpt-4o-euazure/gpt-4o-ca 之间进行负载均衡
model_list:
- model_name: gpt-4o ### RECEIVED MODEL NAME ###
litellm_params: # all params accepted by litellm.completion() - https://docs.litellm.com.cn/docs/completion/input
model: azure/gpt-4o-eu ### MODEL NAME sent to `litellm.completion()` ###
api_base: https://my-endpoint-europe-berri-992.openai.azure.com/
api_key: "os.environ/AZURE_API_KEY_EU" # does os.getenv("AZURE_API_KEY_EU")
rpm: 6 # [OPTIONAL] Rate limit for this deployment: in requests per minute (rpm)
- model_name: bedrock-claude-v1
litellm_params:
model: bedrock/anthropic.claude-instant-v1
- model_name: gpt-4o
litellm_params:
model: azure/gpt-4o-ca
api_base: https://my-endpoint-canada-berri992.openai.azure.com/
api_key: "os.environ/AZURE_API_KEY_CA"
rpm: 6
- model_name: anthropic-claude
litellm_params:
model: bedrock/anthropic.claude-instant-v1
### [OPTIONAL] SET AWS REGION ###
aws_region_name: us-east-1
- model_name: vllm-models
litellm_params:
model: openai/facebook/opt-125m # the `openai/` prefix tells litellm it's openai compatible
api_base: http://0.0.0.0:4000/v1
api_key: none
rpm: 1440
model_info:
version: 2

# Use this if you want to make requests to `claude-3-haiku-20240307`,`claude-3-opus-20240229`,`claude-2.1` without defining them on the config.yaml
# Default models
# Works for ALL Providers and needs the default provider credentials in .env
- model_name: "*"
litellm_params:
model: "*"

litellm_settings: # module level litellm settings - https://github.com/BerriAI/litellm/blob/main/litellm/__init__.py
drop_params: True
success_callback: ["langfuse"] # OPTIONAL - if you want to start sending LLM Logs to Langfuse. Make sure to set `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` in your env

general_settings:
master_key: sk-1234 # [OPTIONAL] Only use this if you to require all calls to contain this key (Authorization: Bearer sk-1234)
alerting: ["slack"] # [OPTIONAL] If you want Slack Alerts for Hanging LLM requests, Slow llm responses, Budget Alerts. Make sure to set `SLACK_WEBHOOK_URL` in your env
信息

有关特定提供商的更多信息,请点击此处

第 2 步:使用配置启动代理

$ litellm --config /path/to/config.yaml
提示

如果需要详细调试日志,请使用 --detailed_debug 运行

$ litellm --config /path/to/config.yaml --detailed_debug

第 3 步:测试它

向 config.yaml 中 model_name=gpt-4o 的模型发送请求。

如果有多个 model_name=gpt-4o 的模型,则执行负载均衡

Langchain、OpenAI SDK 用法示例

curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data ' {
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "what llm are you"
}
]
}
'

LLM 配置 model_list

模型特定参数(API Base、Keys、Temperature、Max Tokens、Organization、Headers 等)

您可以使用配置文件来保存模型特定的信息,如 api_base、api_key、temperature、max_tokens 等。

所有输入参数

第 1 步:创建 config.yaml 文件

model_list:
- model_name: gpt-4-team1
litellm_params: # params for litellm.completion() - https://docs.litellm.com.cn/docs/completion/input#input---request-body
model: azure/chatgpt-v-2
api_base: https://openai-gpt-4-test-v-1.openai.azure.com/
api_version: "2023-05-15"
azure_ad_token: eyJ0eXAiOiJ
seed: 12
max_tokens: 20
- model_name: gpt-4-team2
litellm_params:
model: azure/gpt-4
api_key: sk-123
api_base: https://openai-gpt-4-test-v-2.openai.azure.com/
temperature: 0.2
- model_name: openai-gpt-4o
litellm_params:
model: openai/gpt-4o
extra_headers: {"AI-Resource Group": "ishaan-resource"}
api_key: sk-123
organization: org-ikDc4ex8NB
temperature: 0.2
- model_name: mistral-7b
litellm_params:
model: ollama/mistral
api_base: your_ollama_api_base

第 2 步:使用配置文件启动服务器

$ litellm --config /path/to/config.yaml

预期日志

查看控制台日志中的此行,以确认 config.yaml 已正确加载。

LiteLLM: Proxy initialized with Config, Set models:

Embedding 模型 - 使用 Sagemaker、Bedrock、Azure、OpenAI、XInference

查看支持的 Embedding 提供商和模型 请点击此处

model_list:
- model_name: bedrock-cohere
litellm_params:
model: "bedrock/cohere.command-text-v14"
aws_region_name: "us-west-2"
- model_name: bedrock-cohere
litellm_params:
model: "bedrock/cohere.command-text-v14"
aws_region_name: "us-east-2"
- model_name: bedrock-cohere
litellm_params:
model: "bedrock/cohere.command-text-v14"
aws_region_name: "us-east-1"

启动代理

litellm --config config.yaml

发送请求

bedrock-cohere 发送请求

curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data ' {
"model": "bedrock-cohere",
"messages": [
{
"role": "user",
"content": "gm"
}
]
}'

多个 OpenAI 组织

只需一个模型定义即可添加跨所有 OpenAI 组织的所有 OpenAI 模型

- model_name: *
litellm_params:
model: openai/*
api_key: os.environ/OPENAI_API_KEY
organization:
- org-1
- org-2
- org-3

LiteLLM 将自动为每个组织创建单独的部署。

通过以下方式确认

curl --location 'http://0.0.0.0:4000/v1/model/info' \
--header 'Authorization: Bearer ${LITELLM_KEY}' \
--data ''

负载均衡

信息

关于此功能的更多信息,请访问 此页面

使用此功能可调用同一模型的多个实例,并配置诸如 路由策略 等内容。

为了获得最佳性能

  • 为每个模型部署设置 tpm/rpm。加权选择将基于既定的 tpm/rpm 进行。
  • router_settings:routing_strategy 中选择您的最佳路由策略。

LiteLLM 支持

["simple-shuffle", "least-busy", "usage-based-routing","latency-based-routing"], default="simple-shuffle"`

当设置了 tpm/rpmrouting_strategy==simple-shuffle 时,litellm 将根据设定的 tpm/rpm 进行加权选择。在我们的负载测试中,为所有部署设置 tpm/rpm + routing_strategy==simple-shuffle 可最大化吞吐量

  • 当使用多个 LiteLLM 服务器 / Kubernetes 时,请设置 redis 设置 router_settings:redis_host
model_list:
- model_name: zephyr-beta
litellm_params:
model: huggingface/HuggingFaceH4/zephyr-7b-beta
api_base: http://0.0.0.0:8001
rpm: 60 # Optional[int]: When rpm/tpm set - litellm uses weighted pick for load balancing. rpm = Rate limit for this deployment: in requests per minute (rpm).
tpm: 1000 # Optional[int]: tpm = Tokens Per Minute
- model_name: zephyr-beta
litellm_params:
model: huggingface/HuggingFaceH4/zephyr-7b-beta
api_base: http://0.0.0.0:8002
rpm: 600
- model_name: zephyr-beta
litellm_params:
model: huggingface/HuggingFaceH4/zephyr-7b-beta
api_base: http://0.0.0.0:8003
rpm: 60000
- model_name: gpt-4o
litellm_params:
model: gpt-4o
api_key: <my-openai-key>
rpm: 200
- model_name: gpt-3.5-turbo-16k
litellm_params:
model: gpt-3.5-turbo-16k
api_key: <my-openai-key>
rpm: 100

litellm_settings:
num_retries: 3 # retry call 3 times on each model_name (e.g. zephyr-beta)
request_timeout: 10 # raise Timeout error if call takes longer than 10s. Sets litellm.request_timeout
fallbacks: [{"zephyr-beta": ["gpt-4o"]}] # fallback to gpt-4o if call fails num_retries
context_window_fallbacks: [{"zephyr-beta": ["gpt-3.5-turbo-16k"]}, {"gpt-4o": ["gpt-3.5-turbo-16k"]}] # fallback to gpt-3.5-turbo-16k if context window error
allowed_fails: 3 # cooldown model if it fails > 1 call in a minute.

router_settings: # router_settings are optional
routing_strategy: simple-shuffle # Literal["simple-shuffle", "least-busy", "usage-based-routing","latency-based-routing"], default="simple-shuffle"
model_group_alias: {"gpt-4": "gpt-4o"} # all requests with `gpt-4` will be routed to models with `gpt-4o`
num_retries: 2
timeout: 30 # 30 seconds
redis_host: <your redis host> # set this when using multiple litellm proxy deployments, load balancing state stored in redis
redis_password: <your redis password>
redis_port: 1992

设置 虚拟密钥 (Virtual keys)自定义回调 (custom_callbacks) 后,您可以查看您的成本。

从环境变量加载 API 密钥 / 配置值

如果您有保存在环境中的密钥,且不想将其暴露在 config.yaml 中,以下是如何从环境变量中加载模型特定密钥的方法。这适用于 config.yaml 中的任何值

os.environ/<YOUR-ENV-VAR> # runs os.getenv("YOUR-ENV-VAR")
model_list:
- model_name: gpt-4-team1
litellm_params: # params for litellm.completion() - https://docs.litellm.com.cn/docs/completion/input#input---request-body
model: azure/chatgpt-v-2
api_base: https://openai-gpt-4-test-v-1.openai.azure.com/
api_version: "2023-05-15"
api_key: os.environ/AZURE_NORTH_AMERICA_API_KEY # 👈 KEY CHANGE

查看代码

感谢 @David Manouchehri 在此方面的帮助。

集中式凭证管理

定义一次凭证并在多个模型中重复使用。这有助于

  • 轮换密钥
  • 减少配置重复
model_list:
- model_name: gpt-4o
litellm_params:
model: azure/gpt-4o
litellm_credential_name: default_azure_credential # Reference credential below

credential_list:
- credential_name: default_azure_credential
credential_values:
api_key: os.environ/AZURE_API_KEY # Load from environment
api_base: os.environ/AZURE_API_BASE
api_version: "2023-05-15"
credential_info:
description: "Production credentials for EU region"
custom_llm_provider: "azure"

关键参数

  • credential_name:凭证集的唯一标识符
  • credential_values:凭证/密钥的键值对(支持 os.environ/ 语法)
  • credential_info:用户提供的凭证信息的键值对。不需要键值对,但必须存在此字典。

从密钥管理器(Azure Vault 等)加载 API 密钥

在 LiteLLM Proxy 中使用密钥管理器

为模型设置支持的环境 - productionstagingdevelopment

如果您想控制在特定 litellm 环境中暴露哪些模型,请使用此功能

支持的环境

  • production
  • staging
  • development
  1. 在您的环境中设置 LITELLM_ENVIRONMENT="<environment>"。可以是 productionstagingdevelopment 中的一个

  2. 对于每个模型,在 model_info.supported_environments 中设置支持环境的列表

model_list:
- model_name: gpt-3.5-turbo-16k
litellm_params:
model: openai/gpt-3.5-turbo-16k
api_key: os.environ/OPENAI_API_KEY
model_info:
supported_environments: ["development", "production", "staging"]
- model_name: gpt-4
litellm_params:
model: openai/gpt-4
api_key: os.environ/OPENAI_API_KEY
model_info:
supported_environments: ["production", "staging"]
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o
api_key: os.environ/OPENAI_API_KEY
model_info:
supported_environments: ["production"]

设置自定义提示模板

LiteLLM 默认会检查模型是否有 提示模板并应用它(例如,如果 huggingface 模型在其 tokenizer_config.json 中保存了聊天模板)。但是,您也可以在 config.yaml 中为您的代理设置自定义提示模板

第 1 步:在 config.yaml 中保存您的提示模板

# Model-specific parameters
model_list:
- model_name: mistral-7b # model alias
litellm_params: # actual params for litellm.completion()
model: "huggingface/mistralai/Mistral-7B-Instruct-v0.1"
api_base: "<your-api-base>"
api_key: "<your-api-key>" # [OPTIONAL] for hf inference endpoints
initial_prompt_value: "\n"
roles: {"system":{"pre_message":"<|im_start|>system\n", "post_message":"<|im_end|>"}, "assistant":{"pre_message":"<|im_start|>assistant\n","post_message":"<|im_end|>"}, "user":{"pre_message":"<|im_start|>user\n","post_message":"<|im_end|>"}}
final_prompt_value: "\n"
bos_token: " "
eos_token: " "
max_tokens: 4096

第 2 步:使用配置文件启动服务器

$ litellm --config /path/to/config.yaml

设置自定义分词器(tokenizer)

如果您正在使用 /utils/token_counter 端点,并且想为模型设置自定义 huggingface 分词器,您可以在 config.yaml 中进行设置

model_list:
- model_name: openai-deepseek
litellm_params:
model: deepseek/deepseek-chat
api_key: os.environ/OPENAI_API_KEY
model_info:
access_groups: ["restricted-models"]
custom_tokenizer:
identifier: deepseek-ai/DeepSeek-V3-Base
revision: main
auth_token: os.environ/HUGGINGFACE_API_KEY

规范

custom_tokenizer:
identifier: str # huggingface model identifier
revision: str # huggingface model revision (usually 'main')
auth_token: Optional[str] # huggingface auth token

常规设置 general_settings(数据库连接等)

配置数据库连接池限制 + 连接超时

general_settings:
database_connection_pool_limit: 10 # sets connection pool per worker for prisma client to postgres db (default: 10, recommended: 10-20)
database_connection_timeout: 60 # sets a 60s timeout for any connection call to the db

如何计算正确的值

连接限制是针对每个工作进程 (worker process) 应用的,而不是针对每个实例。这意味着如果您有多个工作进程,每个进程将创建自己的连接池。

公式

database_connection_pool_limit = MAX_DB_CONNECTIONS ÷ (number_of_instances × number_of_workers_per_instance)

示例

  • 您的数据库允许的最大连接数为 100
  • 您正在运行 1 个 LiteLLM 实例
  • 每个实例有 8 个工作进程(通过 --num_workers 8 设置)

计算:100 ÷ (1 × 8) = 12.5

由于不应使用 12.5,向下取整至 10 以留出安全缓冲。这意味着

  • 8 个工作进程中的每一个都将拥有 10 的连接池限制
  • 最大连接总数:8 个进程 × 10 个连接 = 80 个连接
  • 这安全地保持在数据库的 100 个连接限制之内

限制空闲数据库连接 + 传递额外的 Prisma URL 参数

如果您发现大量从未关闭的空闲 Prisma 连接,请设置 database_socket_timeout,以便 Prisma 关闭任何超过阈值仍处于静默状态的连接。您还可以使用 database_connect_timeout 限制 Prisma 等待打开新连接的时间,并通过 database_extra_connection_params 传递任意额外的查询字符串参数给 Prisma。

这些对应于相同名称的 Prisma PostgreSQL 连接 URL 参数(减去 database_ 前缀),LiteLLM 会将它们附加到 DATABASE_URLDIRECT_URL 中。

general_settings:
database_connection_pool_limit: 20
database_socket_timeout: 300 # close any connection idle/slow for >5 min
database_connect_timeout: 15 # fail fast if a new connection can't be established within 15s
database_extra_connection_params:
pgbouncer: "true" # set if running behind PgBouncer
statement_cache_size: 0
sslmode: "require"

说明

  • database_socket_timeout 是从 LiteLLM 限制空闲数据库连接的主要控制旋钮。
  • 当未设置时,database_connect_timeoutdatabase_socket_timeout 将从 URL 中省略,从而应用 Prisma 的默认值。
  • database_extra_connection_params 是一个无类型传递 — 您在此处设置的任何键都会覆盖 LiteLLM 为该键设置的默认值(例如,您可以从此字典中覆盖 pool_timeout)。将其用于 sslmodepgbouncerstatement_cache_size 或任何其他 Prisma URL 参数。

LiteLLM 许可证密钥(企业版)

要启用 LiteLLM 企业版功能,请将您的许可证密钥设置为环境变量

export LITELLM_LICENSE="eyJ..."

许可证密钥是购买 LiteLLM 企业版许可证时提供的 JWT 令牌。设置后,LiteLLM 将自动检测并激活企业版功能。

您也可以将其添加到您的 .env 文件中

LITELLM_LICENSE="eyJ..."

额外功能

禁用 Swagger UI

要从基本 URL 禁用 Swagger 文档,请设置

NO_DOCS="True"

在您的环境中,并重启代理。

禁用 Redoc

要禁用 Redoc 文档(默认为 <your-proxy-url>/redoc),请设置

NO_REDOC="True"

在您的环境中,并重启代理。

为代理使用 CONFIG_FILE_PATH(更轻松的 Azure 容器部署)

  1. 设置 config.yaml
model_list:
- model_name: gpt-4o
litellm_params:
model: gpt-4o
api_key: os.environ/OPENAI_API_KEY
  1. 将文件路径存储为环境变量
CONFIG_FILE_PATH="/path/to/config.yaml"
  1. 启动 Proxy
$ litellm

# RUNNING on http://0.0.0.0:4000

将 LiteLLM config.yaml 文件作为 s3、GCS 存储桶对象/URL 提供

如果您无法在部署服务上挂载配置文件(例如 AWS Fargate, Railway 等),请使用此功能

LiteLLM Proxy 将从 s3 存储桶或 GCS 存储桶读取您的 config.yaml

设置以下 .env 变量

LITELLM_CONFIG_BUCKET_TYPE = "gcs" # set this to "gcs"
LITELLM_CONFIG_BUCKET_NAME = "litellm-proxy" # your bucket name on GCS
LITELLM_CONFIG_BUCKET_OBJECT_KEY = "proxy_config.yaml" # object key on GCS

使用这些环境变量启动 litellm 代理 - litellm 将从 GCS 读取您的配置

docker run --name litellm-proxy \
-e DATABASE_URL=<database_url> \
-e LITELLM_CONFIG_BUCKET_NAME=<bucket_name> \
-e LITELLM_CONFIG_BUCKET_OBJECT_KEY="<object_key>> \
-e LITELLM_CONFIG_BUCKET_TYPE="gcs" \
-p 4000:4000 \
docker.litellm.ai/berriai/litellm-database:main-latest --detailed_debug