DEV Community

Cover image for A Fallback LLM Is Just Another Adapter: Wrap Two Providers, Test Failover With Fakes
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

A Fallback LLM Is Just Another Adapter: Wrap Two Providers, Test Failover With Fakes


DeepSeek's API had an outage of almost five hours on October 15. By the company's own notice, it could not operate normally from 8:11 a.m. to 1:04 p.m. Beijing time, and Yicai's report lists the web platform, the app and both V4.1 APIs as hit. If DeepSeek was the only model your product called, every feature that touched it was down for those five hours too.

The usual fix is a second provider. The usual mistake is where the fix goes. You add a try/except in the summarize use case, then another in the classify use case, then a third one in the agent loop, each catching a slightly different set of SDK exceptions. Six months later every feature is also an outage handler, and nobody can say which errors trigger the switch.

There is a smaller design. Failover belongs to how you reach a model, and your feature shouldn't have to know about it. So it lives in an adapter that implements the same port as the real providers, and the core never learns that two vendors exist.

The port the core sees

Start with what the application needs from a model, in its own words. No SDK types, no vendor names:

# app/ports.py
from dataclasses import dataclass
from typing import Protocol

@dataclass(frozen=True)
class Completion:
    text: str
    provider: str
    fallback_reason: str | None = None

class ProviderUnavailable(Exception):
    """Timeout, connection error, 5xx or 429."""

class RequestRejected(Exception):
    """The provider says the request itself is wrong."""

class LLM(Protocol):
    async def complete(self, prompt: str) -> Completion: ...
Enter fullscreen mode Exit fullscreen mode

Two exceptions carry the whole failover policy. ProviderUnavailable means "this vendor can't serve you right now, another one might." RequestRejected means "this request is broken, and sending it somewhere else will not fix it." A malformed payload, an oversized prompt or a bad parameter fails on the second provider for the same reason it failed on the first, so failing over on a 400 adds a second round trip and still ends in an error.

Completion.provider is the record of who answered. You will want it in logs and metrics the first time a user says the answers "felt different this afternoon."

A use case depends on the port and nothing else:

# app/summarize.py
from app.ports import LLM, Completion

class SummarizeTicket:
    def __init__(self, llm: LLM) -> None:
        self._llm = llm

    async def __call__(self, ticket: str) -> Completion:
        return await self._llm.complete(
            f"Summarize this support ticket:\n{ticket}"
        )
Enter fullscreen mode Exit fullscreen mode

No try, no vendor import. That stays true after you add the second provider.

A central hexagon with a single plug socket on its edge, and two different cables, one black and one burnt orange, both ending in the same plug shape
One port, two adapters behind it. The core only ever sees the socket.

Adapters translate SDK errors into the port's errors

Each provider adapter does two jobs: make the call, and map the SDK's exception hierarchy onto the two exceptions above. That mapping is the part worth reading twice, because it is where the policy lives.

The OpenAI Python SDK README maps 429 to RateLimitError, every status at or above 500 to InternalServerError, and network failures to APIConnectionError. Its timeout error, APITimeoutError, subclasses APIConnectionError, so one entry covers both. Every other error response is an APIStatusError. DeepSeek speaks the OpenAI format at https://api.deepseek.com, so one adapter serves both vendors, which is why it takes a name:

# adapters/openai_compat.py
import openai
from openai import AsyncOpenAI

from app.ports import (
    Completion,
    ProviderUnavailable,
    RequestRejected,
)

TRANSIENT = (
    openai.APIConnectionError,  # includes timeouts
    openai.RateLimitError,
    openai.InternalServerError,
)

class OpenAICompatLLM:
    def __init__(
        self, client: AsyncOpenAI, model: str, name: str
    ) -> None:
        self._client = client
        self._model = model
        self.name = name

    async def complete(self, prompt: str) -> Completion:
        try:
            resp = await self._client.chat.completions.create(
                model=self._model,
                messages=[{"role": "user", "content": prompt}],
            )
        except TRANSIENT as exc:
            raise ProviderUnavailable(str(exc)) from exc
        except openai.APIStatusError as exc:
            raise RequestRejected(str(exc)) from exc
        text = resp.choices[0].message.content or ""
        return Completion(text, self.name)
Enter fullscreen mode Exit fullscreen mode

Order matters in those except clauses. RateLimitError and InternalServerError are subclasses of APIStatusError, so the transient tuple has to come first or every 429 would be filed as a rejected request.

The Anthropic adapter has the same shape. The Claude API error reference lists RateLimitError for 429 and InternalServerError for every 5xx, including 504 and 529 overloaded_error, which it describes as the API being "temporarily overloaded":

# adapters/anthropic_llm.py
import anthropic
from anthropic import AsyncAnthropic

from app.ports import (
    Completion,
    ProviderUnavailable,
    RequestRejected,
)

TRANSIENT = (
    anthropic.APIConnectionError,  # includes timeouts
    anthropic.RateLimitError,
    anthropic.InternalServerError,  # 500, 504, 529
)

class AnthropicLLM:
    name = "anthropic"

    def __init__(self, client: AsyncAnthropic, model: str) -> None:
        self._client = client
        self._model = model

    async def complete(self, prompt: str) -> Completion:
        try:
            msg = await self._client.messages.create(
                model=self._model,
                max_tokens=1024,
                messages=[{"role": "user", "content": prompt}],
            )
        except TRANSIENT as exc:
            raise ProviderUnavailable(str(exc)) from exc
        except anthropic.APIStatusError as exc:
            raise RequestRejected(str(exc)) from exc
        text = "".join(
            b.text for b in msg.content if b.type == "text"
        )
        return Completion(text, self.name)
Enter fullscreen mode Exit fullscreen mode

Notice that 401 and 403 land in RequestRejected. That is a choice, and you can make the other one. A revoked key on the primary is something a human should hear about today, and falling back quietly hides it until the secondary's invoice arrives. If you would rather stay up, move AuthenticationError into the transient tuple and alert on fallback_reason.

The 400 rule has one documented wrinkle. Anthropic says the API also returns a 400 when usage reaches a spend limit you set, and a 429 can mean a tier spend cap that "keeps failing until access resumes." The 429 case is exactly when a second vendor helps, and the mapping above already sends it there. The spend-limit 400 is yours to decide; check the error details before you widen the rule for every 400.

FallbackLLM: the same port, two adapters inside

Now the adapter that does the switching. It implements LLM, holds two LLMs, and catches exactly one exception type:

# app/fallback.py
from dataclasses import replace

from app.ports import LLM, Completion, ProviderUnavailable

class FallbackLLM:
    def __init__(self, primary: LLM, secondary: LLM) -> None:
        self._primary = primary
        self._secondary = secondary

    async def complete(self, prompt: str) -> Completion:
        try:
            return await self._primary.complete(prompt)
        except ProviderUnavailable as first:
            answer = await self._secondary.complete(prompt)
            return replace(answer, fallback_reason=str(first))
Enter fullscreen mode Exit fullscreen mode

Three things fall out of those few lines. A RequestRejected from the primary passes straight through, so the secondary is never called for a broken request. A successful fallback returns the secondary's Completion with the primary's failure attached, so a log line shows both who answered and why the first choice didn't. And if the secondary also fails, its exception leaves the except block with the primary's error attached as __context__ by Python's normal exception chaining, so the traceback shows both outages.

It also composes. FallbackLLM(primary, FallbackLLM(secondary, tertiary)) is a three-provider chain with no new code.

Two stacked black server silhouettes, the top one cracked and dimmed, a burnt-orange arrow curving from it down to the lower one that glows steady
Fail over on "can't serve you now." Never on "your request is wrong."

Two fakes cover every branch

Because the core only knows the port, the tests never touch an SDK, a network or an API key. Two fakes are enough: one that answers and one that raises whatever you hand it.

# tests/test_fallback.py
import asyncio

import pytest

from app.fallback import FallbackLLM
from app.ports import (
    Completion,
    ProviderUnavailable,
    RequestRejected,
)

class AnsweringLLM:
    def __init__(self, name: str) -> None:
        self.name = name
        self.calls: list[str] = []

    async def complete(self, prompt: str) -> Completion:
        self.calls.append(prompt)
        return Completion(f"{self.name} says ok", self.name)

class FailingLLM:
    def __init__(self, error: Exception) -> None:
        self.error = error
        self.calls: list[str] = []

    async def complete(self, prompt: str) -> Completion:
        self.calls.append(prompt)
        raise self.error
Enter fullscreen mode Exit fullscreen mode

One fake answers and records the prompt. The other records the prompt and raises whatever error you hand it. The four tests go in the same file:

def test_healthy_primary_never_calls_secondary():
    secondary = AnsweringLLM("secondary")
    llm = FallbackLLM(AnsweringLLM("primary"), secondary)

    answer = asyncio.run(llm.complete("hi"))

    assert answer.provider == "primary"
    assert answer.fallback_reason is None
    assert secondary.calls == []

def test_unavailable_primary_falls_back():
    primary = FailingLLM(ProviderUnavailable("429"))
    llm = FallbackLLM(primary, AnsweringLLM("secondary"))

    answer = asyncio.run(llm.complete("hi"))

    assert answer.provider == "secondary"
    assert answer.fallback_reason == "429"

def test_rejected_request_never_falls_back():
    secondary = AnsweringLLM("secondary")
    primary = FailingLLM(RequestRejected("400"))
    llm = FallbackLLM(primary, secondary)

    with pytest.raises(RequestRejected):
        asyncio.run(llm.complete("hi"))
    assert secondary.calls == []

def test_both_down_keeps_both_errors():
    first = ProviderUnavailable("primary timeout")
    second = ProviderUnavailable("secondary 503")
    llm = FallbackLLM(FailingLLM(first), FailingLLM(second))

    with pytest.raises(ProviderUnavailable) as info:
        asyncio.run(llm.complete("hi"))
    assert info.value is second
    assert info.value.__context__ is first
Enter fullscreen mode Exit fullscreen mode

Four tests, four branches: healthy primary, failover, no failover on a bad request, both providers down. The calls lists are what make the "never" tests honest. Asserting that the secondary was never called is the whole point of the 400 rule, and a fake that records its calls is the cheapest way to prove it.

The tests use asyncio.run so they need no async plugin. To import app from tests/, put the project root on pytest's path with the pythonpath option:

# pytest.ini
[pytest]
pythonpath = .
Enter fullscreen mode Exit fullscreen mode

The adapters' error mapping deserves its own small tests against the real exception classes, but that is a separate, narrower job. FallbackLLM doesn't care how a vendor spells "overloaded."

Wire it in one place, and tune the SDK retries

The composition root is the only file that knows which vendor is primary:

# main.py
import os

from anthropic import AsyncAnthropic
from openai import AsyncOpenAI

from adapters.anthropic_llm import AnthropicLLM
from adapters.openai_compat import OpenAICompatLLM
from app.fallback import FallbackLLM
from app.summarize import SummarizeTicket

def build_summarizer() -> SummarizeTicket:
    deepseek = OpenAICompatLLM(
        AsyncOpenAI(
            base_url="https://api.deepseek.com",
            api_key=os.environ["DEEPSEEK_API_KEY"],
            max_retries=1,
            timeout=30.0,
        ),
        model=os.environ["PRIMARY_MODEL"],
        name="deepseek",
    )
    claude = AnthropicLLM(
        AsyncAnthropic(max_retries=1, timeout=30.0),
        model=os.environ["SECONDARY_MODEL"],
    )
    return SummarizeTicket(FallbackLLM(deepseek, claude))
Enter fullscreen mode Exit fullscreen mode

The max_retries and timeout arguments are not decoration. Both SDKs already retry on their own: the OpenAI SDK retries connection errors, 408, 409, 429 and 5xx twice by default, and the Anthropic SDK does the same, with a default timeout of 10 minutes per request on both. Leave the defaults on the primary and a hung provider can hold a request for three long attempts before FallbackLLM ever sees an error. Pick a timeout that matches your feature's latency budget, keep one retry for blips, and let the fallback handle the rest.

Swapping primary and secondary is now a one-line change in this file. Switching the secondary to a third vendor means writing one adapter and its mapping tests. No use case changes in either case.

What failover does not buy you

A second provider is a different model. Prompts tuned on one can behave differently on the other, structured-output quirks differ, and so do prices. Run your evals against both adapters, not just the primary, or the fallback path is a feature you have never tested with real outputs. The fake-based tests above prove the routing; they say nothing about answer quality.

It also sends your prompts to another company. If your contracts or data-residency rules name one vendor, the secondary is a legal decision before it is a code decision.

And during a long outage, every request still pays the primary's timeout before it falls back. If you expect five-hour outages like October's, add a circuit breaker that skips the primary for a while after repeated ProviderUnavailable errors. FallbackLLM is the natural home for it, behind the same port, and the same two fakes can drive its tests.


If this was useful

The move in this post is the one I keep coming back to in Hexagonal Architecture in Python: decide what the core needs, name it as a port, and push everything vendor-shaped into adapters you can swap and fake. The book isn't about LLMs. It builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice) and measures what each costs you. That same boundary is what kept FallbackLLM to a dozen lines instead of a try/except in every feature. Every listing runs from the free companion repo.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (1)

Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

The two-exception split is the whole design — failing over on a 400 just buys a second round trip to the same error, and most failover code I've seen never makes that distinction. Anchoring it on the DeepSeek outage (five hours, both V4.1 APIs down) makes the case concrete rather than hypothetical. Do you also fail over on latency — a provider that's technically up but degrading — or is that a third exception waiting to happen?