LiteLLM - a single gateway to one hundred models
LiteLLM is an open AI gateway that provides one interface to over a hundred large language model providers. OpenAI, Anthropic, Gemini, Bedrock, Azure, DeepSeek, Mistral, Groq, Ollama, vLLM and dozens of other services are called in the OpenAI format, and not each according to its own rules. The project is being developed by BerriAI, the code is distributed under the MIT license, and at the time of publication the repository has about 64 thousand stars.
The problem that LiteLLM solves is familiar to anyone who has written anything more complex than one query to one model. Each provider has its own SDK, its own key variable names, its own request structure, its own error codes and its own streaming features. It’s worth adding a second model for backup or a cheaper one for routine, and branching begins in the code, and a zoo of keys begins in the configuration. LiteLLM removes this branching: the application talks to one address, and switching between providers is reduced to changing the line with the model name.
The project exists in two forms, and it is important to understand this right away.
- Python SDK. Library for Python applications. One completion call instead of six different clients.
- AI Gateway (Proxy Server). A separate service that runs next to the application or on the server and provides an HTTP API. Any clients that can work with OpenAI can connect to it, including those not written in Python.
The second option is now the main one: in fact, LiteLLM is an independent gateway, the core of which is written in Rust, and the Python SDK remains for embedding in the code.
Python SDK
Installation via uv:
uv add litellm
Then just change the import and model name. The keys are read from the usual provider environment variables:
from litellm import completion, completion_cost
import os
os.environ["OPENAI_API_KEY"] = "sk-..."
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."
response = completion(
model="openai/gpt-6.1-sol",
messages=[{"role": "user", "content": "Привет"}],
)
print(response.choices[0].message.content)
print(completion_cost(completion_response=response))
The model is specified by a string with the provider prefix. To switch to another, only it changes:
response = completion(
model="anthropic/claude-sonnet-5",
messages=[{"role": "user", "content": "Привет"}],
)
response = completion(
model="deepseek/deepseek-chat",
messages=[{"role": "user", "content": "Привет"}],
)
The rest of the code is not affected: the structure of the response is the same as that of OpenAI. For local models, Ollama and any OpenAI-compatible server work:
response = completion(
model="ollama/qwen3-coder",
messages=[{"role": "user", "content": "Привет"}],
api_base="http://localhost:11434",
)
The SDK has its own router that can handle multiple deployments of the same model, repeat requests, and go to reserve if an error occurs:
from litellm import Router
router = Router(
model_list=[
{
"model_name": "main",
"litellm_params": {
"model": "openai/gpt-6.1-sol",
"api_key": "os.environ/OPENAI_API_KEY",
},
},
{
"model_name": "backup",
"litellm_params": {
"model": "anthropic/claude-sonnet-5",
"api_key": "os.environ/ANTHROPIC_API_KEY",
},
},
],
fallbacks=[{"main": ["backup"]}],
num_retries=2,
)
response = router.completion(
model="main",
messages=[{"role": "user", "content": "Привет"}],
)
A mock mode is provided for tests: the mock_response parameter returns the specified text without accessing the network, and the litellm.drop_params flag drops parameters that a particular model does not support.
Proxy server
The gateway is installed with one command and launched without a database:
uv tool install 'litellm[proxy]'
litellm --model gpt-6.1-sol
The server listens on port 4000. Then any OpenAI client connects, just change the base address:
curl http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6.1-sol",
"messages": [{"role": "user", "content": "Привет"}]
}'
Several routing models and rules require a configuration file. The option with three providers and a backup chain looks like this:
model_list:
- model_name: fast
litellm_params:
model: openai/gpt-6.1-mini
api_key: os.environ/OPENAI_API_KEY
rpm: 500
- model_name: smart
litellm_params:
model: anthropic/claude-sonnet-5
api_key: os.environ/ANTHROPIC_API_KEY
- model_name: local
litellm_params:
model: ollama/qwen3-coder
api_base: http://localhost:11434
litellm_settings:
drop_params: true
num_retries: 3
request_timeout: 60
fallbacks:
- smart: ["fast", "local"]
context_window_fallbacks:
- fast: ["smart"]
router_settings:
routing_strategy: usage-based-routing
allowed_fails: 3
cooldown_time: 30
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY
Launch:
export LITELLM_MASTER_KEY="sk-$(openssl rand -hex 24)"
litellm --config config.yaml
The model_list section specifies what the client sees, and litellm_params.model specifies where the request actually goes. The same model_name name can be specified multiple times with different keys or regions, and LiteLLM will begin to balance between them. Given rpm and tpm the distribution becomes weighted rather than uniform.
Docker and control panel
The full version with PostgreSQL comes with a ready-made compose file. The database includes virtual keys, expense accounting and a panel:
curl -sSLO https://github.com/BerriAI/litellm/raw/main/litellm/deploy/docker/docker-compose.quickstart.yml
printf 'LITELLM_MASTER_KEY=sk-%s\nLITELLM_SALT_KEY=sk-%s\n' "$(openssl rand -hex 32)" "$(openssl rand -hex 32)" > .env
docker compose -f docker-compose.quickstart.yml up -d
After launch, the panel opens at http://localhost:4000/ui. Login admin, password - value LITELLM_MASTER_KEY from .env. In the interface, models with key verification are added, virtual keys are created and statistics are viewed.
The two keys play different roles and should not be confused:
- LITELM_MASTER_KEY - administrative key. It is used to sign requests to the Management API, and it also serves as a password for logging into the panel.
- LITELLM_SALT_KEY - encryption key for provider keys in the database. It is not rotated in place: after the change, all saved secrets will become unreadable until they are entered again.
If the database is not needed, the same image is launched with a configuration file. In this mode, requests are authorized by a master key, and models are described only in YAML:
docker run \
-v "$PWD/config.yaml:/app/config.yaml:ro" \
-e OPENAI_API_KEY \
-e LITELLM_MASTER_KEY \
-p 127.0.0.1:4000:4000 \
docker.litellm.ai/berriai/litellm:latest \
--config /app/config.yaml
Virtual keys, budgets and expenses
The main reason why a gateway is installed in a team is not a single format, but access control. Instead of the provider key, the application receives a virtual key with its own rights:
- list of allowed models;
- spending limit per day, month or entire key lifetime;
- limitations on the number of requests and tokens per minute;
- binding to a user, team or project;
- validity period and automatic accounting of spent costs.
The cost is calculated according to the price table, which is in the repository and is updated along with releases. Therefore, costs are visible immediately after installation, without manually filling out a price list. When the budget is exceeded, requests begin to be rejected with an understandable error, rather than silently going into the red.
There is an important caveat here: budgets and virtual keys only work when the database is connected. Without it, max_budget is not applied - the gateway continues to serve requests after reaching the limit and only writes a warning to the log at startup. A request with a virtual key in this configuration will return the error No connected db, and the master key does not have its own budget.
Routing and fault tolerance
In addition to redundant models, LiteLLM can distribute the load across multiple deployments. Available strategies are simple random sampling, least loaded routing, routing based on token consumption and routing based on delay. With several gateway instances, the balancing state and limit counters are transferred to Redis, otherwise each instance calculates its statistics separately:
router_settings:
redis_host: os.environ/REDIS_HOST
redis_port: 6379
redis_password: os.environ/REDIS_PASSWORD
In addition to replays and fallbacks, there is response caching, a separate fallback chain when the context window is full, a cool-down period for failed deployments, and a allowed_fails threshold that takes it out of rotation for a while. All this can be configured in one place and does not require changes in the application.
Observability and integration
LiteLLM sends logs and metrics to external systems through callbacks: Langfuse, MLflow, Lunary, OpenTelemetry, Prometheus, Datadog and others. It is enough to list the ones you need in success_callback and failure_callback. There are alerts in Slack when approaching a budget, in case of stuck requests and slow responses, guardrails for checking model input and output, as well as an MCP gateway for connecting tool servers to any provider.
The list of endpoints is not limited to chat. The gateway accepts requests to /chat/completions, /responses, /embeddings, /images, /audio, /batches, /rerank and Anthropic-compatible /messages. Therefore, not only applications, but also agent tools, including Claude Code, Codex and OpenCode, connect to it: for them, the gateway simply becomes an OpenAI- or Anthropic-compatible address.
OpenCode via LiteLLM
The practical connection looks like this: LiteLLM holds provider keys, calculates costs and switches models, and OpenCode accesses it as a regular OpenAI-compatible service. In OpenCode terms, it is its own provider with a base gateway address.
First, LiteLLM sets the model names. It is model_name from config.yaml that the agent will see, and not lines like openai/gpt-6.1-sol:
model_list:
- model_name: smart
litellm_params:
model: anthropic/claude-sonnet-5
api_key: os.environ/ANTHROPIC_API_KEY
- model_name: fast
litellm_params:
model: openai/gpt-6.1-mini
api_key: os.environ/OPENAI_API_KEY
- model_name: local
litellm_params:
model: ollama/qwen3-coder
api_base: http://localhost:11434
litellm_settings:
fallbacks:
- smart: ["fast"]
It is better for the agent to issue a separate virtual key on the Virtual Keys page rather than handing out a master key. Then for OpenCode you can limit the list of models, set a spending limit and revoke access without changing provider keys. In the mode without a database, only the master key remains.
Now the provider is described in the global OpenCode config, file ~/.config/opencode/opencode.jsonc:
{
"$schema": "https://opencode.ai/config.json",
"model": "litellm/smart",
"providers": {
"litellm": {
"name": "LiteLLM",
"env": ["LITELLM_API_KEY"],
"package": "@opencode/ai/providers/openai-compatible",
"settings": {
"baseURL": "http://localhost:4000/v1"
},
"models": {
"smart": { "name": "Smart" },
"fast": { "name": "Fast" },
"local": { "name": "Local" }
}
}
}
}
The key is not written to the file: the env field lists the variables from which OpenCode will take credentials. Before starting the agent, the variable must be set:
export LITELLM_API_KEY=sk-your-virtual-key
opencode
In Windows PowerShell, $env:LITELLM_API_KEY="sk-your-virtual-key" is used instead of export.
After launch, the models are visible in the /models list, and the model line at the top level sets the one that is selected by default. The configuration is picked up without restarting: just save the file.
What to pay attention to in this regard:
- Model names. The keys in models must match the model_name from LiteLLM. If you specify openai/gpt-6.1-sol, OpenCode will show the provider, but the request will return an error about the model being unavailable.
- Tool calling. The agent constantly calls tools, so both the primary and backup models must support them. A local model without tool support will fail even if it answers common questions.
- Backup chains. OpenCode does not know that the request went to another model, and this is convenient: a provider crash does not break the session. But when switching, the quality and price change, and the prompt cache of the new provider will be cold.
- Context. Context limits and costs can be specified in models manually, then OpenCode will show them in the interface and warn about overflow. This is optional, but useful if the models in the gateway do not match the models.dev directory.
- Address. baseURL must end in /v1 and be accessible from the OpenCode process. For a gateway in a container, localhost points to the container itself, so the host address is needed.
This scheme is convenient to use with other agents. Claude Code and Codex can also look at an OpenAI- or Anthropic-compatible address, so the gateway becomes a single point where the costs and errors of all tools are visible at once.
Things to consider
- This is an additional layer. The gateway adds latency to each request, albeit small: the documentation states about 8 ms at the 95th percentile at a thousand requests per second. For local models and streaming, this is not critical, but in a loaded system, the extra network transition is still worth taking into account.
- Simple mode is limited. Without a database, there are no keys, no budgets, no expense tracking. For a team of several people, a database is required, which means Postgres appears, which also needs to be monitored.
- Configuration priority. Since version 1.103.0, the key declared in YAML belongs to the file: editing through the panel or API for it will return an error. Keys that are not in the file live in the database. This should be taken into account when migrating from older versions, where the priority was reversed.
- Some of the features are paid. The project itself is open and free, but SSO, audit logs, advanced team management and some guardrails are covered by an Enterprise license.
- Prices and models change. The cost table is updated with releases, but figures may lag for new models or regional tariffs. For accurate reconciliation, it is better to keep your own price settings.
LiteLLM works well in two cases. For a small project, this is a way to avoid writing your own switching between providers and get a backup almost free of charge. For the team, this is a central access point: provider keys are in one place, developers receive personalized virtual keys with limits, and costs and errors are visible in one interface. If an application only needs one provider and one key, the gateway is most likely redundant - a regular SDK will suffice.
Documentation:
GitHub:
https://github.com/BerriAI/litellm
Catalog of supported models:
Gateway quick start:
https://docs.litellm.ai/docs/proxy/docker_quick_start
Configuration in YAML:
https://docs.litellm.ai/docs/proxy/configs
Python SDK:
https://docs.litellm.ai/docs/python_sdk
OpenCode Providers: