Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • What @ Means in Python: Decorators Built by Hand, Then Shortened
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • SOLID in Python With Protocol and ABCs: Five Small Refactors of One Bloated Ticket Service
  • Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder
  • Adapter and Facade in Python: One Interface Over Three LLM Providers
  • Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Object-Oriented Python

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 with max_tokens, or a config dict.
  • It translates the errors. Three vendor errors with three names become one ProviderError, and from e keeps 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.

Facade on top, adapters underneath controllerone call HelpDeskAIorder, fallback, logfacade: many to one ChatModelProtocol 1. ClaudeAdapteradapter: one to one 2. OpenAIAdapter 3. GeminiAdapter
The facade talks to ChatModel; the adapters make every vendor look like ChatModel.

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

PatternWrapsInterface
AdapterOne thing (one SDK), one to oneChanges it into the one you expect
FacadeMany things (adapters, order, log), many to oneSimplifies it to one smaller door
DecoratorOne objectKeeps it, adds behaviour
ProxyOne objectKeeps 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

  1. The lowest common denominator. Reply only 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.
  2. 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.
  3. Errors lose detail. One ProviderError is great for the controller, but when you debug you still need the vendor's original error, which is why the adapters raise it from 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.

Keep going in Python · 28 of 57

Previous
Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder
Next post
Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Three SDKs, three shapes
  • Write the shape you want first
  • One adapter per SDK
  • One loop, one shape
  • The facade the controller talks to
  • One line in the controller
  • Adapter or Facade
  • What it costs
  • How to say it in an interview
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.