Pynions

LiteLLM in Python: One API, Real Fallbacks, and a Safer Install

Call 100+ LLMs with LiteLLM 1.111.0: tested SDK code, Router fallbacks, cost math, a local Ollama proxy, and a safe install after 2026's PyPI incidents.

Updated 12 min read
Blue and orange network cables plugged into a rack switch

LiteLLM is an open-source Python SDK and self-hosted gateway from BerriAI that calls 100+ LLM providers through one OpenAI-style completion() function. This guide runs every example against litellm 1.111.0 on Python 3.15.2, covering the SDK, Router fallbacks, cost tracking and the proxy server.

It also covers what most tutorials skip. LiteLLM shipped two compromised PyPI releases in 2026, so the install section comes before the first API call. If you already build agents with LangChain, LangGraph or Pydantic AI, LiteLLM can sit underneath them as the model layer.

Key Takeaways

  • LiteLLM gives you one call shape for OpenAI, Anthropic, Vertex AI, Bedrock, Ollama and 100+ other providers, and every response comes back in the OpenAI Chat Completions format.
  • Use the SDK inside one app. Use the proxy (LLM gateway) when several apps or people need shared keys, budgets and spend logs.
  • Pin an exact version. 1.82.7 and 1.82.8 in March 2026 and 1.107.0 in October 2026 were malicious releases on PyPI.
  • You can test fallbacks, streaming and cost math with no API key using mock_response, and run a fully local stack through Ollama.
  • Since v1.104.0, the proxy refuses to start without a safe master key, which breaks older proxy tutorials.

What Is LiteLLM?

LiteLLM is a translation layer between your code and model providers. You write completion(model="anthropic/claude-sonnet-5", messages=[...]), and LiteLLM converts the request into the provider's own format, sends it, and maps the reply back to the OpenAI shape.

It comes in two forms. The Python SDK is a library you import. The proxy server is a gateway you run yourself, which exposes OpenAI-compatible endpoints such as /chat/completions and /models on port 4000 by default.

BerriAI was founded by Ishaan Jaffer and Krrish Dholakia, who sign LiteLLM's incident posts as CTO and CEO. The company's Y Combinator page lists a $1.6M seed round from Y Combinator, Gravity Fund and Pioneer Fund.

LiteLLM homepage: The AI Gateway for platform teams

Why LiteLLM Matters in 2027

Model names change fast. The current quick start already shows openai/gpt-6.1-sol and anthropic/claude-sonnet-5, and in LiteLLM a provider switch is one edited string.

The GitHub repository had more than 64,000 stars on 28 November 2026, and "litellm" draws about 27,100 US searches a month, according to DataForSEO data pulled the same day.

The flip side is risk concentration. A package that holds every provider key is a prime target, which is why 2026 brought two supply chain incidents and a steady stream of security advisories. Give it the same review, pinning and upgrade process you give a database driver.

How LiteLLM Works: SDK, Router, Proxy

Think of LiteLLM as three layers you adopt in order. Start with the SDK, add the Router when you need failover, and move to the proxy when more than one app shares the same models.

The SDK: One completion() Call

completion() takes a provider/model string plus the usual OpenAI arguments. Provider keys come from environment variables such as OPENAI_API_KEY or ANTHROPIC_API_KEY, and local servers take an api_base.

The response is a ModelResponse in the OpenAI Chat Completions format, whatever the provider. That is the main payoff: your parsing code never changes.

The Router: Retries and Fallbacks

The Router holds a model_list of deployments under aliases. It supports three fallback types: fallbacks for general errors such as rate limits, context_window_fallbacks for prompts that are too long, and content_policy_fallbacks for refusals.

You can also set order on deployments, so the Router tries priority 1, then 2, before it reaches any configured fallback, as the routing docs describe.

The Proxy: A Shared Gateway

The proxy wraps the same Router in an HTTP server. Any OpenAI-compatible client can point at it, which is how teams give one endpoint to apps written in Python, TypeScript or anything else.

Virtual keys, per-key budgets, spend logs and the Admin UI need a database: add database_url under general_settings, per the CLI quick start. Without a database the proxy still routes and falls back.

Install LiteLLM Safely After the 2026 Incidents

The classic first step is pip install litellm. In 2026 that unpinned command twice installed malware for anyone unlucky enough to run it during an incident window.

What Happened in March and October 2026


March 2026

October 2026

Bad versions

litellm 1.82.7 and 1.82.8

litellm 1.107.0 (PyPI and Docker tags)

Window

About 40 minutes from 10:39 UTC on 24 March

11:39 to 13:23 UTC on 21 October (PyPI)

Entry point

A compromised Trivy dependency in CI

A leaked key that led to an org owner's GitHub token

Official write-up

Security update

Incident post

LiteLLM's own post-incident review explains why the controls added after March, such as Trusted Publishing and signed images, did not stop October: the October release came through the real pipeline. Releases are now signed with keyless cosign, starting with v1.111.0-dev.3, according to the 15 November update on the incident post.

Pin, Verify, and Check for Indicators

Create a fresh environment and pin the version you have reviewed. On 28 November 2026 the current release was 1.111.0, uploaded to PyPI on 25 November.

Shell
python3 -m venv .venv
source .venv/bin/activate
pip install "litellm==1.111.0"

Then confirm what is installed and look for the indicator files the October post lists. On a clean environment the find command prints nothing.

Shell
pip show litellm | grep Version
find "$(python -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')" \
  -name "litellm-1.107.0.dist-info" -o -name "cook.pth" -o -name "sitecustomize.py"
Text
Version: 1.111.0

If you ever find those files, do not run pip in that environment first. The official guidance is that any Python start in the affected environment runs the malicious hooks again, so delete them from the shell and rebuild from scratch.

Add a Release Cooldown with uv

On r/Python and r/LocalLLaMA, the top LiteLLM threads of the past year are the incident threads, and the advice that keeps coming up is exact pins plus a release cooldown. A cooldown means your resolver ignores anything uploaded in the last few days, which would have skipped both bad releases. After the first breach, one r/Python commenter wrote: "After the first breach I configured uv with 7d quarantine."

uv's exclude-newer setting accepts a friendly duration such as 1 week or 7 days, compared against each file's upload time. Put it in pyproject.toml:

Text
[tool.uv]
exclude-newer = "7 days"

Running uv add litellm in that project on 28 November 2026 resolved litellm==1.110.2, not 1.111.0, because 1.111.0 was only three days old. If you use uv already, this is a one-line supply chain control.

Pick litellm or litellm-core

Apps that only call the SDK can install litellm-core instead. It keeps the same litellm import, the Router and cost functions, but drops boto3, tokenizers and huggingface-hub from the mandatory dependencies and ships no gateway CLI or Admin UI.

Package

Use it when

Notes

litellm

You want the default SDK install

Same import as core

litellm-core

One app calls the SDK and you want fewer dependencies

Cannot be installed alongside litellm

litellm[proxy]

You run the gateway

Pulls litellm-proxy at the same version

Your First LiteLLM Calls (No API Key Needed)

LiteLLM's mock_response parameter returns a normal response object without calling any provider. It lets you learn the API and write unit tests before you create a single provider key.

A Mocked completion()

Python
from litellm import completion

response = completion(
    model="openai/gpt-6.1-sol",
    messages=[{"role": "user", "content": "Say hi"}],
    mock_response="Hi from LiteLLM",
)
print(response.choices[0].message.content)
print(response.model, response.usage.total_tokens)
Text
Hi from LiteLLM
gpt-6.1-sol 30

To call the real model, delete mock_response and set OPENAI_API_KEY. To switch providers, change the string to anthropic/claude-sonnet-5 and set ANTHROPIC_API_KEY. The parsing lines stay the same.

Streaming

Pass stream=True and read delta.content from each chunk, exactly as with the OpenAI SDK.

Python
from litellm import completion

stream = completion(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Count to three"}],
    stream=True,
    mock_response="one two three",
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")
print()
Text
one two three

A Real Local Model Through Ollama

For a real call with no paid key, run a model in Ollama and use the ollama_chat/ prefix, which the Ollama provider docs recommend over ollama/. This example used gemma4:e2b on a CPU-only Linux box.

Python
from litellm import completion

response = completion(
    model="ollama_chat/gemma4:e2b",
    messages=[{"role": "user", "content": "Reply with exactly: pong"}],
    api_base="http://localhost:11434",
)
print(response.choices[0].message.content)
Text
pong

Model text varies between runs, so treat the exact words as illustrative. The response object, and how you read it, does not change.

Fallbacks That You Can Test

Fallbacks keep requests alive when a provider rate-limits or goes down, and you should see one fire before you rely on it. The Router lets you force the failure path on purpose.

Router Fallbacks with mock_testing_fallbacks

Define two aliases, point fallbacks from one to the other, and pass mock_testing_fallbacks=True, the flag the reliability docs give for direct Router tests.

Python
from litellm import Router

router = Router(
    model_list=[
        {
            "model_name": "primary",
            "litellm_params": {"model": "openai/gpt-6.1-sol", "mock_response": "from primary"},
        },
        {
            "model_name": "backup",
            "litellm_params": {"model": "anthropic/claude-sonnet-5", "mock_response": "from backup"},
        },
    ],
    fallbacks=[{"primary": ["backup"]}],
)

response = router.completion(
    model="primary",
    messages=[{"role": "user", "content": "Hello"}],
    mock_testing_fallbacks=True,
)
print(response.choices[0].message.content)
Text
from backup

Fallbacks run in list order, so {"primary": ["backup", "third"]} tries backup first. Keep a cheaper or self-hosted model at the end of the chain so a provider outage degrades quality instead of failing requests.

Why the Same Flag Does Nothing on the Proxy

Starting with proxy v1.85.0, mock_testing_fallbacks and its siblings are stripped from incoming proxy requests and have no effect. The docs tell you to trigger a real provider error in a non-production environment instead, which the proxy section below does.

Track LLM Costs with LiteLLM

Every LiteLLM response carries a cost estimate, and completion_cost() computes one from any response. Both read LiteLLM's price map, which the token usage docs describe as community-maintained.

completion_cost() and cost_per_token()

By default LiteLLM downloads the latest price map when it is imported. Setting LITELLM_LOCAL_MODEL_COST_MAP=True before the import uses the copy bundled with your pinned release, so the numbers do not shift between runs.

Python
import os

os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"  # use the price map bundled with this release

from litellm import completion, completion_cost, cost_per_token

response = completion(
    model="openai/gpt-6.1-sol",
    messages=[{"role": "user", "content": "Summarize this ticket"}],
    mock_response="Customer wants a refund.",
)
print(response.usage.prompt_tokens, response.usage.completion_tokens)
print(f"${completion_cost(completion_response=response):.6f}")

prompt_usd, completion_usd = cost_per_token(
    model="openai/gpt-6.1-sol", prompt_tokens=2_000, completion_tokens=500
)
print(f"2,000 in: ${prompt_usd:.4f}, 500 out: ${completion_usd:.4f}")
Text
10 20
$0.000220
2,000 in: $0.0040, 500 out: $0.0050

The bundled 1.111.0 map lists gpt-6.1-sol at $2 per million input tokens and $10 per million output tokens below 272,000 tokens, with higher rates above that line. In these mock runs LiteLLM reported 10 prompt and 20 completion tokens, which is why the first cost is $0.00022.

Treat Prices as Estimates

The price map is LiteLLM's estimate of list prices. Check the provider's own pricing page before you set budgets, and use register_model to override a price you negotiated.

On the proxy, the same calculation feeds per-key, per-team and per-user spend once a database is attached. Since v1.104.0, a spent budget returns HTTP 422 instead of 429, per the release notes, so clients stop retrying it as a rate limit.

Run the LiteLLM Proxy Locally

The proxy is where LiteLLM turns into a gateway. This setup puts a local Ollama model and a hosted model behind one endpoint, with a fallback between them.

Install and Configure

Shell
pip install "litellm[proxy]==1.111.0" "openai==3.60.0"

Save this as config.yaml. The os.environ/ prefix tells LiteLLM to read the value from an environment variable instead of the file.

YAML
model_list:
  - model_name: local-gemma
    litellm_params:
      model: ollama_chat/gemma4:e2b
      api_base: http://localhost:11434
  - model_name: gpt-6.1-sol
    litellm_params:
      model: openai/gpt-6.1-sol
      api_key: os.environ/OPENAI_API_KEY

router_settings:
  fallbacks: [{"gpt-6.1-sol": ["local-gemma"]}]

Set a Master Key or the Proxy Will Not Start

Since v1.104.0, released on 3 October 2026, the proxy refuses to boot with an unset, empty or publicly known master key. The master key docs explain why: without a key the proxy accepts every request, and the old example key was copied from tutorials everywhere.

Generate a random key the way LiteLLM's own error message suggests, then start the proxy:

Shell
export LITELLM_MASTER_KEY="sk-$(openssl rand -hex 32)"
litellm --config config.yaml --port 4000

Without that variable, 1.111.0 exits with "LiteLLM proxy refused to start: no master key is set, so every request would be accepted without authentication."

Call It with the OpenAI SDK

Any OpenAI client works. Use the master key (or a virtual key, once you add a database) as the API key and the proxy as the base URL.

Python
import os

from openai import OpenAI

client = OpenAI(api_key=os.environ["LITELLM_MASTER_KEY"], base_url="http://localhost:4000")

for model in ["local-gemma", "gpt-6.1-sol"]:
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": "Reply with exactly: pong"}],
    )
    print(model, "->", response.model, "|", response.choices[0].message.content)
Text
local-gemma -> local-gemma | pong
gpt-6.1-sol -> ollama_chat/gemma4:e2b | pong

In this test OPENAI_API_KEY held a placeholder, so the gpt-6.1-sol call failed and the proxy answered from local-gemma. That is the real-error test the docs recommend, and the client never saw the failure.

Confirm the Fallback from Response Headers

The proxy reports what it did in x-litellm-* response headers, which makes fallbacks visible in logs and tests.

Shell
curl -s -i http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-6.1-sol", "messages": [{"role": "user", "content": "Reply with exactly: pong"}]}' \
  | grep -i -E "^x-litellm-(model-group|attempted-fallbacks|version)"
Text
x-litellm-version: 1.111.0
x-litellm-model-group: local-gemma
x-litellm-attempted-fallbacks: 1
LiteLLM documentation Getting Started page

LiteLLM Pricing: Open Source vs Enterprise

The open-source gateway is free to self-host, with no license fee. The free tier already includes virtual keys, users and teams, spend tracking, budgets and rate limits, fallbacks, request logging and Prometheus metrics.

Enterprise adds SSO and SCIM, OIDC and JWT auth, audit logs, secret managers with key rotation, org and team admins, a multi-region control plane and support SLAs. LiteLLM says Enterprise is priced by annual gateway request capacity, deployment architecture and support needs, "never per token," and offers a 30-day trial key.

Your real cost of the open-source version is operations. Spend tracking and the Admin UI need Postgres, and the Router docs use Redis to share cooldown and usage state in production, both of which you run.

LiteLLM pricing page with the $0 Open Source plan and Enterprise

Common LiteLLM Mistakes to Avoid

Installing an Unpinned litellm in CI

pip install litellm in a Dockerfile or CI job takes whatever was uploaded a minute ago. Pin an exact version, commit a lockfile, and add a cooldown so a bad release has time to be caught before it reaches you.

Copying the Old Master Key from a 2025 Tutorial

Older guides start the proxy with a sample master key copied from LiteLLM's own docs. On v1.104.0 and later that publicly known value is rejected at boot, because anyone who could reach the proxy could guess it, as the master key docs explain. Generate a random key and keep it in an environment variable.

Using mock_testing_fallbacks to Test the Proxy

The flag still works on a direct Router, so tests pass locally, but the proxy strips it. Test proxy fallbacks with a real failure, such as a placeholder key in a staging config, and check x-litellm-attempted-fallbacks.

Trusting the Price Map as Your Invoice

completion_cost() multiplies tokens by LiteLLM's community-maintained prices, and the map changes as models ship. Pin the bundled map with LITELLM_LOCAL_MODEL_COST_MAP=True when you need stable numbers, and reconcile against the provider's billing.

Installing litellm and litellm-core Together

The two packages contain the same Python files. The core docs warn that installing both in one environment makes import litellm fail, even when the versions match.

LiteLLM in Practice: A University Chatbot Gateway

At a PyData conference, Alina of Sioneers shared lessons from production LiteLLM projects through a private university chatbot scenario. The requirements were models that could be swapped later and the option to self-host.

She picked the proxy over the SDK because it can issue API keys, so student projects could get their own key and use any library that accepts a custom OpenAI URL. When costs in the scenario ran higher than planned because of power users, the fix was to attach Postgres and pass a user ID with each request, so LiteLLM records spend per user.

Her caveats are worth keeping. Some newer features did not behave as she expected from the docs, and she measured about 200 milliseconds of added latency, which was acceptable for a chatbot. LiteLLM's README cites an 8 ms P95 at 1,000 requests per second in its own benchmarks, so measure on your own hardware and network.

Frequently Asked Questions

Sources

Related Articles