Skip to contentOceanToken

9 min read

OpenAI API Fallback to Another LLM

Build an OpenAI API fallback to another LLM in Python: which errors should switch models, which should not, backoff, streaming failures, and a working function.

By OceanToken Team

OpenAI API Fallback to Another LLM

Editor's note: A lot of fallback code switches models on every exception. That hides real bugs, because a malformed request fails the same way on every model, and it misses the one case where switching is the right answer. A good chain is mostly a classifier: decide what each error means first, and only then decide whether a different model can fix it.

Short answer: For an OpenAI API fallback to another LLM, keep several model ids on one OpenAI-compatible base URL and loop through them yourself. Switch models on overload, server errors and timeouts; wait and retry on your own rate limit; stop on request, key and balance errors. The SDK's max_retries only resends the same request to the same model.

Diagram: What happens to a failed request, from gateway to your code

01 · What max_retries does, and what it does not

The OpenAI Python SDK already retries. Its README says certain errors are retried twice by default with a short exponential backoff: connection errors, 408, 409, 429 and every 5xx. max_retries sets the count, and 0 turns retries off. A request also times out after 10 minutes by default, and that timeout is retried too.

What it retries is the same request. The body is resent unchanged, so the model id is unchanged. If the model itself is overloaded, two more attempts against it, a second apart, rarely help, and with the default timeout a slow model can hold a user for a long time before your code even sees the error. The SDK has no notion of a second model. That part is yours to write.

So the first decision is who owns retries. Mixing both layers multiplies attempts: three SDK attempts inside each of your five loop attempts is fifteen calls. The OceanToken error docs  take the simple route and set max_retries=0, letting one loop do all the retrying. We do the same below, and we set an explicit timeout.

02 · Which errors should switch models

Here is the error table this guide is built on, using the gateway's documented error codes (checked November 19, 2026). Branch on code, not on the message text.

Diagram: Switch models, retry, or stop?

Status and code What it means Action
429 provider_overloaded Every channel of this model is at capacity Switch to the next model
5xx provider_error The model failed after the gateway's own retry and failover Switch to the next model
504 timeout A non-streamed request ran past 240 seconds Stream instead, or switch
408 timeout A stream received nothing for 120 seconds Switch to the next model
429 rate_limited Your key's own per-minute limit Wait for Retry-After if sent, otherwise back off; switching does not help
503 temporarily_unavailable The gateway could not check your balance just now Retry the same request after a pause
400 invalid_request A missing field, an unaccepted value, a prompt too long Fix the request; switch only to a model with more context when the prompt is too long
400 insufficient_credits, key_budget_exceeded, request_exceeds_balance No balance, the key's own limit is used up, or the balance cannot cover this request; nothing ran Stop and alert
400 content_filtered A safety check refused it Change the input; do not switch
401, 403 Key or permission problem Stop and alert
Connection error The network dropped Retry the same model with backoff

Two rows break common habits. First, a 429 is not always "the model is busy". rate_limited is your key's limit, and it applies whatever model you call, so cycling through models just burns attempts faster. Second, running out of money is a 400, not a 429 as on OpenAI. A loop that treats every 429 as retryable will not spin on an empty balance here, but a loop that switches models on every 400 will burn through your whole chain on a request that can never succeed.

For the single-model version of the 429 problem, see our fix for DeepSeek API 429 errors.

03 · Let the gateway try first

Before writing your own chain, know what has already happened by the time an error reaches you. The OceanToken retries and failover page  says a failed request is retried and, where the model has more than one channel, moved to another channel serving the same model. Failover never changes the model; you get an answer from the model you asked for, at its price. The errors in the table above are what is left after that. Only some models have more than one channel today (the current Claude and GPT models and several image and video models); the others get one retry and nowhere to switch, which is why a model-level fallback matters for chains like the one below.

The same page describes a fallbacks field: a list of model ids to try, in order, if the requested model fails on all of its channels. It works on /v1/chat/completions and /v1/responses. Because it is not part of the OpenAI SDK's signature, it goes in extra_body:

response = client.chat.completions.create(
    model="deepseek/deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Summarize this ticket in one line."}],
    extra_body={"fallbacks": ["qwen/qwen3.8-flash", "minimax/minimax-m3"]},
)
print(response.model)  # the model that actually answered

Server-side fallbacks are tried for any error the model returns, including a prompt too long for its context. Key, balance and rate-limit errors come back without trying them. You are billed at the price of the model that answered: the x-oceantoken-model header names it, and so does model in a non-streaming response. Use this when you want one request, not a loop. Use a client-side chain, below, when you need different parameters per model, your own logging per attempt, or the same code to work on any OpenAI-compatible endpoint.

04 · An OpenAI API fallback to another LLM, as a Python function

This function walks a chain of models, retries the same model only for errors a retry can fix, and moves on only for errors another model can fix. Each model carries its own settings, because the same parameters do not fit every model.

import os, random, time
from openai import OpenAI, APIConnectionError, APIStatusError, APITimeoutError

client = OpenAI(
    base_url=os.getenv("LLM_BASE_URL", "https://api.oceantoken.ai/v1"),
    api_key=os.environ["OCEANTOKEN_API_KEY"],
    max_retries=0,   # this function owns retries
    timeout=120,     # fail fast enough to try the next model
)

CHAIN = [
    {"model": "deepseek/deepseek-v4.1-flash", "max_tokens": 4000},
    {"model": "qwen/qwen3.8-flash", "max_tokens": 4000},
    {"model": "minimax/minimax-m3", "max_tokens": 4000},
]
SWITCH = {"provider_overloaded", "provider_error", "timeout"}
SAME_MODEL = {"rate_limited", "temporarily_unavailable"}

def code_of(err):
    body = err.body if isinstance(err.body, dict) else {}
    return (body.get("error") or body).get("code")

def complete(messages, chain=CHAIN, tries_per_model=2):
    last = None
    for step in chain:
        for attempt in range(tries_per_model):
            try:
                resp = client.chat.completions.create(messages=messages, **step)
                print("answered by", resp.model)   # log the model that answered
                return resp
            except (APIConnectionError, APITimeoutError) as e:
                last = e                           # network or client timeout
            except APIStatusError as e:
                last, code = e, code_of(e)
                if code in SAME_MODEL:             # key limit or gateway check: same model
                    if attempt == tries_per_model - 1:
                        raise
                    wait = e.response.headers.get("retry-after")
                    if wait:
                        time.sleep(float(wait)); continue
                elif code in SWITCH or (e.status_code >= 500 and e.status_code != 501):
                    break                          # another model may succeed
                else:
                    raise                          # request, key or balance: stop
            time.sleep(min(30, 2 ** attempt) + random.random())
    raise last

A 120-second client timeout gives up on non-streamed requests the gateway would still finish (its window is 240 seconds); stream long answers, or raise the timeout to 240 if you do not stream.

The ids in CHAIN are examples from one catalog, chosen because they sit in a similar capability tier; compare current rates on /deepseek-api and /qwen-api, and look at the GPT family on /gpt-api if you want a stronger last resort.

Order matters more than membership. Put a model after another only if it can take the same prompt: DeepSeek V4.1 Flash 1017 is listed with about 1.05M tokens of context, while MiniMax M3 lists 524,288, so M3 goes last, and a prompt larger than that should skip it. A fallback that cannot fit the prompt turns a temporary outage into a hard 400. The function raises on any 400, including a prompt that is too long, so pick the chain before the call: measure the prompt and drop the models it will not fit.

05 · When a stream fails halfway

Streaming makes fallback harder, because part of the answer may already be on the user's screen. The docs split it in two. Before the first token, failover works as usual and the stream just starts later. After the answer has started, the gateway may finish it on another channel of the same model or end the stream with a final data: chunk carrying the error object, depending on the endpoint.

Treat a stream as complete only when it ends with a finish_reason. If it does not, restart the whole answer on the next model and replace what you showed; do not try to continue one model's half-answer with another, since the second model has no idea where the first was heading. Expect to pay for the broken attempt: a stream cut off after output started is billed for its prompt and the output streamed so far, reasoning included. That cost is one reason to keep the chain short.

06 · What else changes when the model changes

The model id is the obvious edit. The quiet ones are the settings you kept from the first model: a max_tokens above the next model's output limit, a reasoning switch the next model does not take, a temperature the next model ignores. On this endpoint a parameter a model does not list is left out before the request reaches it, so none of these raise errors. That is why each step in CHAIN carries its own settings. Our guide to OpenAI-compatible API differences covers the parameter differences in detail.

Then log which model answered, every time. A fallback that quietly serves a third of your traffic from the backup model changes your quality, latency and cost, and you only find out if resp.model is in your logs.

How to test this on your workload

We have not run a failure benchmark for this article. Force each failure on purpose before you trust the chain:

  1. Put an unknown model id first in the chain and confirm the function stops with 400 model_not_found instead of moving on.
  2. Set the client timeout to one second and confirm a timeout moves to the next model.
  3. Give a test key a very small credit limit, use it up, and confirm key_budget_exceeded stops the chain.
  4. Send a burst of requests from one key and check that rate_limited waits rather than switches.
  5. Kill the network mid-stream and confirm your code restarts the answer on the next model.
  6. Send your longest real prompt and confirm every model in the chain accepts it.

Our take: Keep the chain to two or three models of the same tier, ordered by context limit, and switch only on provider_overloaded, 5xx and timeouts. If your code only ever talks to one compatible endpoint, try the server-side fallbacks field first and keep the client loop for cases that need per-model settings. Either way, log the model that answered, or you will not know your fallback is carrying production.

Running it on OceanToken

On OceanToken, every model in the chain above answers on one OpenAI-compatible base URL, https://api.oceantoken.ai/v1, with one key and one prepaid balance, so a fallback is a different model id, not a second account and SDK. Same-model failover across channels happens before an error reaches you, the fallbacks field adds your own backup models in one request, and an attempt that fails before producing output is not billed. See the current rates on /deepseek-api, /qwen-api and /gpt-api.

FAQ

Does the OpenAI SDK fall back to another model? No. max_retries resends the same request to the same model; switching models is your code's job or the endpoint's.

Should I retry with a different model on 429? Only when the 429 says the model is overloaded (provider_overloaded). A rate_limited 429 is your key's limit, so wait for Retry-After if it is sent, or back off on your own if it is not.

Should a 400 trigger a fallback? Almost never. The exception is a prompt too long for the model's context, where only a model with a larger limit can help.

How do I know which model answered? The x-oceantoken-model header names it, and so does model in a non-streaming response.

Am I charged for failed attempts? On OceanToken, not for attempts that fail before any output. A stream that breaks after output started is billed for what was processed.

Sources

  1. openai-python README: retries, timeouts and errors  (checked 2026-11-19)
  2. OceanToken docs: Errors  (checked 2026-11-19)
  3. OceanToken docs: Retries and failover  (checked 2026-11-19)
  4. OceanToken docs: MiniMax M3  (checked 2026-11-19)
  5. OceanToken: MiniMax M3 model page (checked 2026-11-19)

Get your OceanToken API key

  1. Create an OceanToken account and an API key.
  2. Copy the snippet below, paste your key, and run it.
  3. Check the current rate on /deepseek-api.
curl https://api.oceantoken.ai/v1/chat/completions \
  -H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "deepseek/deepseek-v4.1-flash", "messages": [{"role": "user", "content": "Write a haiku about the ocean."}], "fallbacks": ["qwen/qwen3.8-flash"]}'

Get API Key 

  • LLM API
  • Tutorial
  1. 11 min read

    Veo 3.1 Reference Images API Guide

    How to send reference images to Veo 3.1 through the API: input_references vs first frame, which tiers take them, two-shot Python script and a consistency test.

    • Veo
    • AI video
    • Tutorial
  2. 12 min read

    LLM Function Calling API Across Models

    Write one LLM function calling API loop that works across GPT, Claude, Gemini, Qwen, GLM and DeepSeek: tool_choice, streaming and the silent no-call trap.

    • LLM API
    • Tutorial
  3. 10 min read

    LLM Image Input API: Screenshots and Scans

    Send screenshots, photos and scans to a chat model with one LLM image input API: URL vs base64 data URL, per-model image limits, the 400 error and token costs.

    • LLM API
    • Tutorial