VynarisEarly beta
Get my API key

How to Set Up LLM Fallback (Python and LiteLLM)

Set up LLM fallback by failing over only on timeouts, 429, 5xx and 529, capping SDK retries and logging the serving model. Python and LiteLLM code.

TL;DR: An LLM fallback sends a request to the next model in an ordered chain when the current one fails with a transient error: a timeout, connection error, 408, 409, 429, 500, 502, 503, 504 or Anthropic's 529. Never fail over on 400, 401, 403 or 404, because those are bugs the next provider will hide. Cap the SDK's built-in retries first: both official SDKs retry twice by default, so a three-model chain can make 9 attempts before your user sees an error.

To set up LLM fallback, you need three things: an ordered chain of models on at least two providers, a function that decides which errors are worth failing over on, and a log line that records which model actually served each request. In plain Python that is about 40 lines with the official openai and anthropic SDKs. In LiteLLM it is a fallbacks entry in config.yaml. Both are below, with list prices checked on 2026-11-12, and the cost of each fallback worked out per 1,000 requests.

A request tries the primary model, classifies the error, then moves down the chain
Non-transient errors (400, 401, 403, 404) stop the chain and raise.

What you need before you start

You need these pieces in place before the first step:

The chain in this guide, with list prices per 1M tokens from the OpenAI pricing page and the Anthropic pricing page on 2026-11-12:

PositionModel IDInput / 1MOutput / 1MWhy it is here
Primarygpt-6.1-sol$2.00$10.00Quality model for normal traffic
Fallback 1claude-sonnet-5-5$2.00$10.00Same tier, different provider, 1M context
Fallback 2claude-haiku-5-5$0.10$0.50Cheap last resort (prompts up to 100,000 tokens)

Which errors should trigger a fallback?

Fail over on errors that say "the provider cannot serve this right now", and raise on errors that say "this request is wrong". The table maps the documented codes from the OpenAI error codes guide and the Anthropic errors page to an action.

Error codes sorted into fail over, fail over without retrying, and raise
Only the last row stops the chain.
ErrorProvider wordingFail over?Why
Timeout / connection errorAPITimeoutError, APIConnectionErrorYesThe provider never answered
429 rate limitOpenAI "Rate limit reached for requests", "Slow down"; Anthropic rate_limit_errorYes, after at most one retryAnother provider has its own limits
429 spend or quotaOpenAI organization_spend_limit_exceeded, "Credit balance exhausted"; Anthropic tier spend capYes, skip retriesOpenAI: retrying these "won't restore API access"
500 / 502 / 504OpenAI "The server had an error"; Anthropic api_error, timeout_errorYesTransient provider fault
503OpenAI server_is_overloadedYesModel capacity, not your request
529Anthropic overloaded_errorYesAnthropic-specific overload code
400invalid_request_errorNo (one exception below)The next model gets the same bad request
401 / 403 / 404auth, permission, not foundNoA broken key or model ID should page you, not hide

Three details most fallback tutorials miss:

  1. OpenAI moved some overload errors from 429 to 503. Its docs say Python raises RateLimitError for 429 and InternalServerError for 503, and that video overload "now returns 503 where it previously returned 429". Handle both.
  2. Anthropic returns 400, not 429, when you hit a spend limit you set yourself. Its errors page says the API "also returns a 400 when usage reaches an organization or workspace spend limit you set". If you want that to fail over, check the message, not only the status.
  3. A spend-cap 429 never recovers by waiting. Anthropic notes that a tier spend-cap 429 "has no retry-after header and keeps failing until access resumes". Retrying it just adds latency.

The one 400 worth rerouting is a context-length error: send it to a model with a bigger window, not to a sibling with the same limit. Claude Sonnet 5.5 includes a 1M-token context window at standard pricing, which makes it a natural target.

Step 1: Cap the SDK retries and set a real timeout

Both official SDKs retry for you. The openai package retries "2 times by default" on connection errors, 408, 409, 429 and 500+, and waits up to 10 minutes per request before timing out (openai-python README). The Anthropic SDK also retries twice by default and honours retry-after. Left alone, those defaults sit underneath your chain and multiply it.

import logging
import anthropic
import openai

log = logging.getLogger("llm")

# One quick retry per provider, then let the chain take over.
oa = openai.OpenAI(max_retries=1, timeout=30.0)
an = anthropic.Anthropic(max_retries=1, timeout=30.0)

Set the timeout from your primary model's p99 latency, not its median. Too tight and you fail over on healthy requests; we priced that trap in model fallback chains and outage cost.

Step 2: Write the fail-over rule

Put the table above into one function. APITimeoutError is a subclass of APIConnectionError in both SDKs, so one check covers both.

FAILOVER_STATUS = {408, 409, 429, 500, 502, 503, 504, 529}
SPEND_HINTS = ("spend limit", "spend_limit", "credit balance", "usage limit", "quota")

def should_fail_over(err: Exception) -> bool:
    if isinstance(err, (openai.APIConnectionError, anthropic.APIConnectionError)):
        return True  # network errors and timeouts
    status = getattr(err, "status_code", None)
    if status in FAILOVER_STATUS:
        return True
    # Anthropic returns 400 for a spend limit you configured yourself
    return status == 400 and any(h in str(err).lower() for h in SPEND_HINTS)

Step 3: Call each provider with its native SDK

How do I fall back from OpenAI to Anthropic in code? Use each provider's own SDK and translate the message list. Anthropic does offer an OpenAI-compatible endpoint at https://api.anthropic.com/v1/, but its own docs call it "primarily intended to test and compare model capabilities" and "not considered a long-term or production-ready solution"; it silently ignores fields such as seed and the strict flag on tools (Anthropic OpenAI SDK compatibility). Your fallback is the path that runs during an incident, so make it the well-tested one.

def call_openai(model, messages, max_tokens):
    r = oa.chat.completions.create(
        model=model, messages=messages, max_completion_tokens=max_tokens
    )
    return r.choices[0].message.content, r.usage.prompt_tokens, r.usage.completion_tokens

def call_anthropic(model, messages, max_tokens):
    system = "\n".join(m["content"] for m in messages if m["role"] == "system")
    chat = [m for m in messages if m["role"] != "system"]
    extra = {"system": system} if system else {}
    r = an.messages.create(model=model, max_tokens=max_tokens, messages=chat, **extra)
    text = "".join(b.text for b in r.content if b.type == "text")
    return text, r.usage.input_tokens, r.usage.output_tokens

Step 4: Walk the chain and log who answered

The loop tries each link in order, raises immediately on a non-transient error, and records the serving model plus token counts. That log line is what lets you see when fallback quietly becomes your normal traffic.

CHAIN = [
    ("openai", "gpt-6.1-sol"),
    ("anthropic", "claude-sonnet-5-5"),
    ("anthropic", "claude-haiku-5-5"),
]
CALLERS = {"openai": call_openai, "anthropic": call_anthropic}

def complete(messages, max_tokens=1024):
    errors = []
    for provider, model in CHAIN:
        try:
            text, tokens_in, tokens_out = CALLERS[provider](model, messages, max_tokens)
            log.info("served_by=%s/%s in=%d out=%d failovers=%d",
                     provider, model, tokens_in, tokens_out, len(errors))
            return text
        except Exception as err:
            if not should_fail_over(err):
                raise
            log.warning("failover from %s/%s: %s", provider, model, err)
            errors.append(f"{provider}/{model}: {err}")
    raise RuntimeError("all models in the chain failed: " + " | ".join(errors))

Streaming needs one more rule. The openai README states that stream consumption "is not automatically retried, because replaying a request could duplicate output already delivered", and Anthropic warns that a streaming error can arrive after a 200. Fail over only if no tokens have reached the user yet; after that, return an error rather than splice two models' answers together.

Step 5: Or do the same in LiteLLM

If several services call models, put the chain in a gateway instead of copying complete() into each one. In LiteLLM, fallbacks run "if a call fails after num_retries", in list order, and there are three kinds: fallbacks for general errors, context_window_fallbacks and content_policy_fallbacks (LiteLLM reliability docs).

model_list:
  - model_name: primary
    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-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: last-resort
    litellm_params:
      model: anthropic/claude-haiku-5-5
      api_key: os.environ/ANTHROPIC_API_KEY

litellm_settings:
  num_retries: 1          # per model group, before falling back
  request_timeout: 30     # seconds
  fallbacks: [{"primary": ["backup", "last-resort"]}]
  context_window_fallbacks: [{"primary": ["backup"]}]

router_settings:
  allowed_fails: 3        # cool a deployment down after 3 failures
  cooldown_time: 30       # seconds out of rotation

Start it with litellm --config config.yaml and point any OpenAI client at http://0.0.0.0:4000. The cooldown is the circuit breaker: after allowed_fails, LiteLLM stops sending traffic to that deployment for cooldown_time seconds instead of paying a timeout on every request. For the trade-offs between running this yourself and paying a hosted gateway, see LiteLLM vs OpenRouter vs managed gateways.

LangChain LLM fallback | Make your AI app unbreakable (DigitalOcean)

DigitalOcean walks through a sequential fallback class in a LangChain app: a list of models tried in order, a warning logged on each failure, an exception when all fail, and a mock subclass that forces the first model to fail so you can watch the fallback happen.

  • 1:56 Two models defined, a 70B primary and an 8B fallback
  • 2:21 Running the mock flag: first model fails, 8B model answers
  • 3:32 The fallback class takes an ordered list of models
  • 3:55 The invoke loop: try, log a warning, continue, raise if all fail
  • 4:20 Mocking a failure by overriding the model factory

Step 6: Prove it fails over before production needs it

Test with a real transport failure, not a bad model name. A wrong model ID returns 404, and the rule above correctly refuses to fail over on it.

# Point the primary at a closed port: connection refused triggers failover.
oa = openai.OpenAI(base_url="http://127.0.0.1:9/v1", max_retries=0, timeout=2.0)
print(complete([{"role": "user", "content": "Reply with the word ok."}]))
# Expect: a "failover from openai/gpt-6.1-sol" warning, then served_by=anthropic/claude-sonnet-5-5

For LiteLLM, note that since Proxy v1.85.0 the mock_testing_fallbacks flag is stripped from proxy requests; it only works on direct litellm.Router calls. To test the proxy, break the primary's api_base in a staging config, send a normal request and check the x-litellm-model-id response header to see which deployment answered.

curl -s -D - http://0.0.0.0:4000/chat/completions \
  -H "Authorization: Bearer $LITELLM_API_KEY" -H "Content-Type: application/json" \
  -d '{"model": "primary", "messages": [{"role": "user", "content": "ping"}]}' \
  | grep -i x-litellm-model-id

How do retries and fallbacks interact?

Retries repeat the same model; fallbacks move to the next one, and the attempts multiply. Worst-case attempts for a chain are links x (1 + retries per link).

SetupAttempts before final errorWorst-case wait at 20 s timeout
3 links, SDK defaults (2 retries)3 x 3 = 9180 s
3 links, max_retries=13 x 2 = 6120 s
3 links, max_retries=0360 s
LiteLLM num_retries: 3 + SDK default 2 inside your app3 x 4 = 12 at the proxy, times your client's retriesminutes

Pick one layer to own retries. If you run LiteLLM, set your application client to max_retries=0 so the proxy's count is the real count.

Does a fallback model change cost per request?

Yes: the request is billed at the fallback model's price, plus whatever the failed attempt consumed. A 429, 503 or 529 is returned before generation, so it carries no token usage; a timeout mid-stream can still bill the input and any streamed output. Using our 3,000-in, 600-out shape:

Served byDerivationCost per 1,000 requests
gpt-6.1-sol3,000 x $2/1M + 600 x $10/1M = $0.0120$12.00
claude-sonnet-5-5Same list price; Anthropic says its newer tokenizer produces about 30% more tokens, so $12.00 x 1.3about $15.60
claude-haiku-5-53,000 x $0.10/1M + 600 x $0.50/1M = $0.0006, x 1.3about $0.78

At a 2% fast-failure rate, falling back to Sonnet 5.5 costs $12.00 + 0.02 x $15.60 = $12.31 per 1,000 requests, 2.6% more than primary-only. Falling back to Haiku 5.5 costs $12.00 + 0.02 x $0.78 = $12.02, 0.13% more. Equal list prices do not mean equal bills: the tokenizer difference makes the "same-price" fallback the expensive one. Run your own token counts through the LLM cost calculator before choosing the order, and see LLM routing examples for chains that also route on cost.

Common errors and their fixes

If you would rather not maintain the chain, the price tables and the retry settings in every service, Vynaris is an OpenAI-compatible endpoint (https://api.vynaris.com/v1) that bills provider list price plus 3% on the first $500 a month and 1% after, and shows the model that actually served each request in the response headers. The DIY code above works without it. For the concept behind both, read what an LLM gateway is.

FAQ

What is the difference between LLM fallback and LLM failover?

They are used interchangeably. Some teams say failover for switching providers (OpenAI to Anthropic) and fallback for switching models (Sonnet to Haiku); the code and configuration are the same ordered chain.

Should I retry before falling back?

Retry once on 429 and 5xx, because many are momentary, then fall back. Skip the retry for spend, credit and quota errors: OpenAI states that retrying them "won't restore API access".

Can I fall back to a different model on the same provider?

Yes, and it helps for a model-specific overload such as an OpenAI 503 server_is_overloaded. It does not help when your organisation hit a provider-wide rate or spend limit, so keep at least one link on a second provider.

How do I fall back when the prompt is too long?

Treat a context-length 400 as its own case and route it to a model with a larger window, such as Claude Sonnet 5.5 with its 1M-token context. In LiteLLM that is context_window_fallbacks.

Does a fallback break prompt caching?

Yes. The fallback provider has never seen your cached prefix, so the first requests pay full input price. We priced that effect in model fallback chains and outage cost.