AILabStore
All guides

Models

Model routing and fallbacks

Send each request to the right model, retry safely, and fall back to another provider when one is slow or unavailable.

7 min read · Updated November 1, 2026

With every provider behind one endpoint, choosing a model becomes a runtime decision instead of an integration project. This guide shows how to route requests by task, retry transient errors, and fall back across providers so your app keeps working when one model is overloaded.

Why route at all?

No single model is best at everything. A typical application has a mix of work:

Task Good fit Why
Classification, extraction, short replies anthropic/claude-haiku-5.5, google/gemini-2.5-flash-lite Fast and inexpensive
Everyday chat and coding anthropic/claude-sonnet-5.5, openai/gpt-5-mini Strong quality at moderate cost
Hard reasoning, long agentic tasks anthropic/claude-opus-5.5, openai/gpt-5 Highest capability
Very long documents google/gemini-2.5-pro, meta/llama-4-scout Large context windows
Live web answers perplexity/sonar-pro Search-grounded citations

Sending everything to the most capable model wastes money; sending everything to the cheapest model hurts quality. Routing gets you both.

Static routing by task

The simplest router is a lookup table kept in configuration:

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.ailabstore.cc/v1", api_key=os.environ["AILABSTORE_API_KEY"])

ROUTES = {
    "classify":  "anthropic/claude-haiku-5.5",
    "chat":      "anthropic/claude-sonnet-5.5",
    "reason":    "anthropic/claude-opus-5.5",
    "long_doc":  "google/gemini-2.5-pro",
}

def complete(task: str, messages: list[dict], **kwargs):
    return client.chat.completions.create(model=ROUTES[task], messages=messages, **kwargs)

Keeping the table outside your code lets you swap models after evaluating them, without a deploy.

Dynamic routing with a classifier

For open-ended input, let a small, cheap model decide where a request should go:

ROUTER_PROMPT = """Classify the user's request as one of: simple, standard, complex.
simple = greetings, lookups, short rewrites.
standard = typical questions, summaries, small code changes.
complex = multi-step reasoning, architecture, long analysis.
Reply with one word."""

TIER_MODEL = {
    "simple": "anthropic/claude-haiku-5.5",
    "standard": "anthropic/claude-sonnet-5.5",
    "complex": "anthropic/claude-opus-5.5",
}

def route(user_message: str) -> str:
    r = client.chat.completions.create(
        model="anthropic/claude-haiku-5.5",
        messages=[{"role": "system", "content": ROUTER_PROMPT},
                  {"role": "user", "content": user_message}],
        max_tokens=3,
        temperature=0,
    )
    tier = r.choices[0].message.content.strip().lower()
    return TIER_MODEL.get(tier, "anthropic/claude-sonnet-5.5")

The router call costs a fraction of a cent and can cut spend substantially on mixed traffic. Measure quality on a sample of real requests before rolling it out.

Retries with exponential backoff

Rate limits (429) and temporary upstream errors (500, 502, 503, 504) are normal at scale. Retry them with backoff and jitter; do not retry 400, 401 or 403, which will fail again.

The OpenAI SDKs already retry twice by default. You can tune it:

client = OpenAI(
    base_url="https://api.ailabstore.cc/v1",
    api_key=os.environ["AILABSTORE_API_KEY"],
    max_retries=4,
    timeout=60,
)
const client = new OpenAI({
  baseURL: "https://api.ailabstore.cc/v1",
  apiKey: process.env.AILABSTORE_API_KEY,
  maxRetries: 4,
  timeout: 60_000,
});

Cross-provider fallbacks

When a model keeps failing, try an equivalent model from a different provider. Because every model shares the same API shape, a fallback chain is just a list:

from openai import APIStatusError, APIConnectionError, APITimeoutError

FALLBACKS = [
    "anthropic/claude-sonnet-5.5",
    "openai/gpt-5-mini",
    "google/gemini-2.5-flash",
]

RETRYABLE = {408, 429, 500, 502, 503, 504}

def complete_with_fallback(messages, **kwargs):
    last_error = None
    for model in FALLBACKS:
        try:
            return client.with_options(max_retries=1).chat.completions.create(
                model=model, messages=messages, **kwargs
            )
        except (APIConnectionError, APITimeoutError) as e:
            last_error = e
        except APIStatusError as e:
            if e.status_code not in RETRYABLE:
                raise
            last_error = e
    raise last_error

The same idea in TypeScript:

const FALLBACKS = ["anthropic/claude-sonnet-5.5", "openai/gpt-5-mini", "google/gemini-2.5-flash"];

export async function completeWithFallback(
  messages: OpenAI.Chat.ChatCompletionMessageParam[],
) {
  let lastError: unknown;
  for (const model of FALLBACKS) {
    try {
      return await client.chat.completions.create({ model, messages }, { maxRetries: 1 });
    } catch (err) {
      if (err instanceof OpenAI.APIError && err.status && err.status < 500 && err.status !== 429) {
        throw err; // client error: do not fall back
      }
      lastError = err;
    }
  }
  throw lastError;
}

Choosing fallback models

  • Pick models with similar capability, or users will notice quality drops.
  • Make sure every model in the chain supports the features you use: tool calling, JSON output, vision, and a large enough context window.
  • Keep prompts provider-neutral. Avoid relying on one vendor's formatting quirks.
  • Log which model served each request so you can spot when fallbacks are happening often.

Timeouts and hedging

For latency-sensitive features, set a short timeout on the primary model and fall back quickly. For the most critical paths you can hedge: send the request to two models at once and use whichever answers first. Hedging doubles cost for those requests, so reserve it for small, important calls.

Managed routing on Pro

The Pro package includes server-side routing and fallbacks. Contact [email protected] with the fallback chains and route rules you want, and we apply them to your account so they work across all your keys without changing application code. Client-side routing as shown above works on every package and is a good way to prototype rules before you hand them over.

Checklist

  1. Start with a static route table per task.
  2. Evaluate candidate models on 50 to 100 real examples.
  3. Add retries with backoff for 429 and 5xx.
  4. Add a fallback chain of equivalent models from different providers.
  5. Log the serving model, latency and token usage for every request.