Tutorials & Guides
How to Build a Multi-Model Fallback Wrapper in Python to Bypass LLM Downtime
Don't let raw API errors, rate limits, and service outages break your production application. Learn how to write a self-healing fallback wrapper in Python.
Updated 10/31/2026
Why Single-Model Dependencies Are a Production Risk
If you are building production-grade AI applications, relying on a single upstream model provider is a recipe for disaster. APIs fail. They experience brownouts. They return rate limit errors when traffic spikes. And sometimes, they just time out entirely.
Nothing makes a production system tick like having an absolute, bulletproof contingency plan. If your primary LLM throws a 529 or a rate-limit error, your application should not crash and burn. Instead, it should seamlessly degrade to a backup provider, keeping the user experience intact without them ever realising a system hiccup occurred behind the scenes.
In this tutorial, we will write a custom, lightweight Python fallback wrapper that catches common API exceptions from /platforms/openai, /platforms/claude, and /platforms/gemini, automatically routing traffic to secondary and tertiary models dynamically.
Set up your AI once so you repeat yourself less.
Tickd is independent and not affiliated with any AI company.
Understanding the Fallback Hierarchy
When designing a fallback system, you must categorise your models by capability and latency. It is usually best to set up your hierarchy like this:
- Primary Model: Your top-performing engine (e.g., Claude 3.5 Sonnet). Excellent reasoning, but prone to occasional rate limits or higher costs.
- Secondary Model: A highly capable alternative (e.g., GPT-4o). Almost matching reasoning capabilities, but running on a completely different cloud infrastructure.
- Tertiary / Eco Model: A fast, incredibly cheap alternative (e.g., Gemini 1.5 Flash). Excellent for ensuring the pipeline completes the task, even if complex formatting or reasoning takes a slight hit.
Step 1: Setting Up the Dependencies
First, let's install the official SDKs for our target models:
`bash
pip install openai anthropic google-generativeai
`
Next, store your API keys in your .env file or environment variables:
`bash
export OPENAI_API_KEY="your_openai_key"
export ANTHROPIC_API_KEY="your_anthropic_key"
export GEMINI_API_KEY="your_gemini_key"
`
Step 2: Defining a Unified Interface
Because every provider uses slightly different paradigms for sending messages and receiving responses, we need a standard structure. We will create a clean abstraction class to uniform model inputs and outputs.
`python
from typing import Dict, List, Optional
import os
import openai
import anthropic
import google.generativeai as genai
class LLMResponse:
def __init__(self, content: str, model_used: str, provider: str):
self.content = content
self.model_used = model_used
self.provider = provider
`
Step 3: Writing the Fallback Core Logic
Now, let's create our main fallback client wrapper. We will implement individual call handlers for each client, wrap them in a generic generate function, and write sequential retry logic.
`python
import logging
logging.basicConfig(level=logging.INFO) logger = logging.getLogger("FallbackRouter")
class ResilientLLMClient: def __init__(self): # Initialise underlying SDK clients self.openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")) self.anthropic_client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) # Configure Gemini genai.configure(api_key=os.getenv("GEMINI_API_KEY")) self.gemini_model_name = "gemini-1.5-flash"
def _call_claude(self, prompt: str, model: str) -> str: message = self.anthropic_client.messages.create( model=model, max_tokens=1024, messages=[{"role": "user", "content": prompt}] ) return message.content[0].text
def _call_openai(self, prompt: str, model: str) -> str: response = self.openai_client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}] ) return response.choices[0].message.content
def _call_gemini(self, prompt: str, model: str) -> str: model_instance = genai.GenerativeModel(model) response = model_instance.generate_content(prompt) return response.text
def generate(self, prompt: str) -> LLMResponse: # Order of execution: Claude -> OpenAI -> Gemini pipeline = [ {"provider": "anthropic", "model": "claude-3-5-sonnet-20241022", "handler": self._call_claude}, {"provider": "openai", "model": "gpt-4o", "handler": self._call_openai}, {"provider": "gemini", "model": "gemini-1.5-flash", "handler": self._call_gemini} ]
for step in pipeline:
provider = step["provider"]
model = step["model"]
handler = step["handler"]
try:
logger.info(f"Attempting generation with {provider}/{model}...")
result_text = handler(prompt, model)
logger.info(f"Success using {provider}/{model}!")
return LLMResponse(content=result_text, model_used=model, provider=provider)
except Exception as e:
logger.warning(f"Failed using {provider}/{model}. Error: {str(e)}")
# Keep looping to try the next model in our sequence
continue
raise RuntimeError("All upstream LLM models failed to respond. Operational failure.")
`
Step 4: Adding Exponential Backoff to Prevent Double Faults
If you hit a rate limit error, instantly firing another request to the fallback engine can sometimes trigger security or abuse alerts. It is cleaner to integrate a small delay before switching providers. Let's write an updated generate method with a backoff strategy:
`python
import time
... inside ResilientLLMClient class ...
def generate_with_backoff(self, prompt: str, retry_delay: float = 0.5) -> LLMResponse: pipeline = [ {"provider": "anthropic", "model": "claude-3-5-sonnet-20241022", "handler": self._call_claude}, {"provider": "openai", "model": "gpt-4o", "handler": self._call_openai}, {"provider": "gemini", "model": "gemini-1.5-flash", "handler": self._call_gemini} ]
for idx, step in enumerate(pipeline):
provider = step["provider"]
model = step["model"]
handler = step["handler"]
try:
return handler(prompt, model)
except Exception as e:
logger.error(f"Step {idx+1} failed ({provider}/{model}): {e}")
if idx < len(pipeline) - 1:
logger.info(f"Sleeping for {retry_delay}s before falling back...")
time.sleep(retry_delay)
raise RuntimeError("Critical: All models exhausted.")
`
Troubleshooting Failure States
While fallback layers keep your systems robust, they can hide silent failures. If you are experiencing unexpected degradation of output quality because your application is constantly dropping to Gemini Flash without you knowing, implement a webhook/alert to Slack or Discord on any non-primary execution.
For diagnostic steps concerning specific SDK client initiation errors or rate-limit code schemas, read our troubleshooting guides for /platforms/openai/articles and /platforms/claude/articles to learn how to capture raw HTTP headers and identify rate limits early. You can also explore how to use /platforms/gemini as your primary configuration for high-concurrency loops.
Keep going
Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.