Adapter and Facade in Python: One Interface Over Three LLM Providers
Three stand-in SDKs in OpenAI, Claude and Gemini style, each with its own request, response and token names. A ChatModel Protocol and three adapters give one Reply shape (13 tokens in for all three), and a HelpDeskAI facade falls back to OpenAI when Claude returns 529 overloaded.
What you will learn
- Write the shape the app wants first: a Reply dataclass, a ProviderError and a ChatModel Protocol
- Build one adapter per SDK that translates the request, the response and the errors
- Put a facade in front that holds provider order, fallback and a usage log
- Explain the difference between adapter, facade, decorator and proxy, and the costs
Before you start
- Python classes and dataclasses
- Strategy and Factory in Python
Two pictures first. Your laptop has one plug, and every country has its own socket. A travel adapter sits in between: your plug on one side, the local socket on the other. That's the Adapter pattern; it converts one shape into another. Now a hotel. You want a taxi, a late checkout and breakfast in your room. You don't go and find three departments. You talk to one front desk and it calls them for you. That's the Facade pattern: one simple door in front of many parts.
So an adapter converts, and a facade simplifies. We'll use both to put three LLM providers behind one small interface. The project uses three stand-in SDKs, so it runs with no keys and no network. The stand-in counts one word as one token.
Three SDKs, three shapes
The Help Desk wants one thing: the answer to "Where is order 1002?". With three SDKs that's three different calls, from before.py:
"""Without adapters: the app must speak three SDKs."""
from vendors import fake_anthropic, fake_gemini
from vendors import fake_openai
SYSTEM = "You are the Help Desk. Answer in one line."
Q = "Where is order 1002?"
oa = fake_openai.OpenAI(api_key="stand-in")
r1 = oa.chat.completions.create(
model="gpt-model",
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": Q}])
print("openai:", r1.choices[0].message.content,
r1.usage.prompt_tokens, r1.usage.completion_tokens)
an = fake_anthropic.Anthropic(api_key="stand-in")
r2 = an.messages.create(
model="claude-model", max_tokens=300, system=SYSTEM,
messages=[{"role": "user", "content": Q}])
print("claude:", r2.content[0].text,
r2.usage.input_tokens, r2.usage.output_tokens)
ge = fake_gemini.Client(api_key="stand-in")
r3 = ge.models.generate_content(
model="gemini-model", contents=Q,
config={"system_instruction": SYSTEM})
print("gemini:", r3.text,
r3.usage_metadata.prompt_token_count,
r3.usage_metadata.candidates_token_count)
openai: Order 1002 is packed, ships tomorrow. 13 6
claude: Your order 1002 is packed, ships tomorrow. 13 7
gemini: Order 1002: packed, ships tomorrow. 13 5
The OpenAI style puts the system prompt inside the messages list and the text at choices[0].message.content. The Claude style takes the system prompt as its own argument, needs max_tokens, and puts the text at content[0].text. The Gemini style puts the system prompt in a config dict and the text is simply .text. Even the token counts have three names.
Write the shape you want first
Turn it around. Before any adapter, write the shape the app wants, llm/port.py:
"""The one shape the app knows. No vendor in sight."""
from dataclasses import dataclass
from typing import Protocol
@dataclass
class Reply:
provider: str
text: str
tokens_in: int
tokens_out: int
class ProviderError(Exception):
"""One error type, whatever the vendor raised."""
class ChatModel(Protocol):
name: str
def complete(self, system: str,
question: str) -> Reply: ...
One Reply with four fields and not one vendor word. One error, ProviderError. One contract, ChatModel, a Protocol with one method. A Protocol checks the shape, not the family, so any class with a matching complete fits without a base class. The app depends on this file and nothing else.
One adapter per SDK
llm/adapters.py:
"""Adapters: each turns a vendor SDK into ChatModel."""
from llm.port import ProviderError, Reply
from vendors import fake_anthropic, fake_gemini
from vendors import fake_openai
class OpenAIAdapter:
name = "openai"
def __init__(self, key: str = "stand-in") -> None:
self.client = fake_openai.OpenAI(api_key=key)
def complete(self, system: str,
question: str) -> Reply:
messages = [
{"role": "system", "content": system},
{"role": "user", "content": question},
]
try:
r = self.client.chat.completions.create(
model="gpt-model", messages=messages)
except fake_openai.RateLimitError as e:
raise ProviderError(f"openai: {e}") from e
return Reply(self.name,
r.choices[0].message.content,
r.usage.prompt_tokens,
r.usage.completion_tokens)
class ClaudeAdapter:
name = "claude"
def __init__(self, key: str = "stand-in") -> None:
self.client = fake_anthropic.Anthropic(
api_key=key)
def complete(self, system: str,
question: str) -> Reply:
try:
r = self.client.messages.create(
model="claude-model", max_tokens=300,
system=system,
messages=[{"role": "user",
"content": question}])
except fake_anthropic.APIStatusError as e:
raise ProviderError(f"claude: {e}") from e
text = "".join(b.text for b in r.content
if b.type == "text")
return Reply(self.name, text,
r.usage.input_tokens,
r.usage.output_tokens)
class GeminiAdapter:
name = "gemini"
def __init__(self, key: str = "stand-in") -> None:
self.client = fake_gemini.Client(api_key=key)
def complete(self, system: str,
question: str) -> Reply:
try:
r = self.client.models.generate_content(
model="gemini-model", contents=question,
config={"system_instruction": system})
except fake_gemini.ServerError as e:
raise ProviderError(f"gemini: {e}") from e
meta = r.usage_metadata
return Reply(self.name, r.text,
meta.prompt_token_count,
meta.candidates_token_count)
ADAPTERS = {
"openai": OpenAIAdapter,
"claude": ClaudeAdapter,
"gemini": GeminiAdapter,
}
- Each adapter owns its vendor client. Nobody else in the app sees it.
- It translates the request into that SDK's format: a messages list, a
system=argument withmax_tokens, or a config dict. - It translates the errors. Three vendor errors with three names become one
ProviderError, andfrom ekeeps the original attached. - It translates the response into a
Reply. The Claude one joins the text blocks into one string.
ADAPTERS at the end is the same dict registry from Strategy and Factory: a name goes in, an adapter class comes out.
One loop, one shape
"""With adapters: one loop, one shape, three vendors."""
from llm.adapters import ADAPTERS
from llm.facade import SYSTEM
for name, Adapter in ADAPTERS.items():
reply = Adapter().complete(SYSTEM,
"Where is order 1002?")
print(type(reply).__name__, reply.provider,
reply.tokens_in, reply.tokens_out, reply.text)
Reply openai 13 6 Order 1002 is packed, ships tomorrow.
Reply claude 13 7 Your order 1002 is packed, ships tomorrow.
Reply gemini 13 5 Order 1002: packed, ships tomorrow.
Different wording, because they're different models, but an identical shape. A fourth provider is one new class plus one new line in the dictionary.
The facade the controller talks to
The adapters fix the shape. But the controller still has jobs it shouldn't care about: which provider goes first, what happens when one fails, and what gets logged. That's the facade, llm/facade.py:
"""The facade: one door from controller to LLMs."""
from llm.adapters import ADAPTERS
from llm.port import ChatModel, ProviderError
SYSTEM = "You are the Help Desk. Answer in one line."
SORRY = "Sorry, please try again in a minute."
class HelpDeskAI:
def __init__(self, models: list[ChatModel]) -> None:
self.models = models
self.log: list[str] = []
@classmethod
def build(cls, order: list[str]) -> "HelpDeskAI":
return cls([ADAPTERS[name]() for name in order])
def answer(self, question: str) -> str:
for model in self.models:
try:
reply = model.complete(SYSTEM, question)
except ProviderError as e:
self.log.append(f"skip {e}")
continue
self.log.append(f"used {reply.provider} "
f"{reply.tokens_in} in, "
f"{reply.tokens_out} out")
return reply.text
self.log.append("all providers failed")
return SORRY
build uses the registry to make the adapters in the given order. answer adds the system prompt and tries each model in turn. A ProviderError isn't a crash: the facade logs a skip line and moves on. When one answers, it logs who answered and the tokens, and returns only the text. If they all fail, the user gets one calm sentence.
One line in the controller
"""The controller: HTTP in, one call, JSON out."""
from llm.facade import HelpDeskAI
desk = HelpDeskAI.build(["claude", "openai", "gemini"])
def ask(question: str) -> dict:
return {"answer": desk.answer(question)}
No SDK import, no if, no retry code. main.py asks twice, the second time with the Claude stand-in switched off:
"""Ask the controller twice: Claude up, then down."""
from controller import ask, desk
from vendors import fake_anthropic
print(ask("Where is order 1002?"))
fake_anthropic.DOWN = True
print(ask("Where is order 1002?"))
for line in desk.log:
print(line)
{'answer': 'Your order 1002 is packed, ships tomorrow.'}
{'answer': 'Order 1002 is packed, ships tomorrow.'}
used claude 13 in, 7 out
skip claude: 529 overloaded
used openai 13 in, 6 out
Claude answers the first time. During the fake outage, the answer still comes back, in the OpenAI wording, and the log tells the whole story. The controller's code didn't change at all. (A production fallback chain needs more than this, such as timeouts and data-region checks; see fallback models for an LLM app.)
Adapter or Facade
| Pattern | Wraps | Interface |
|---|---|---|
| Adapter | One thing (one SDK), one to one | Changes it into the one you expect |
| Facade | Many things (adapters, order, log), many to one | Simplifies it to one smaller door |
| Decorator | One object | Keeps it, adds behaviour |
| Proxy | One object | Keeps it, controls access |
The last two rows are from decorators vs the Decorator pattern vs Proxy. In this project the first two stack: the facade talks to ChatModel, and the adapters make every vendor look like ChatModel.
What it costs
- The lowest common denominator.
Replyonly holds what all three vendors share. A feature only one vendor has, like Claude's cache-control flag, has no place in it. The fix is a small optional options field, or a second protocol for that one feature, not stuffing everything into the shared one. - The facade can grow into a god class. Prompts, retries, billing and caching, all in one file. Keep it to orchestration and push the real work into the adapters or other services.
- Errors lose detail. One
ProviderErroris great for the controller, but when you debug you still need the vendor's original error, which is why the adapters raise itfrom e.
How to say it in an interview
"How would you make an app independent of its LLM provider?" Start with the contract: one small Protocol with a complete method that returns my own Reply type. Then one adapter per SDK that translates the request, the response and the errors, so vendor types never leak out. Then a facade that holds the provider order, the fallback and the usage log, so the controller makes one call. Close with the trade-off: the shared interface is the lowest common denominator, so I'd add an escape hatch for vendor-only features.
Recap
- The adapter converts: one vendor's dialect becomes your own shape.
- The facade simplifies: the controller gets one door, with order, fallback and log behind it.
- The Protocol is the contract both sides agree on.
- Your code talks to the shape you own, never to the SDK.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
