Sub topic 1
Why one interface: the cost of calling providers directly
Prerequisites
This chapter assumes you can read and write Python, know the basics of HTTP APIs and JSON, and have called at least one hosted chat-completion API. You should also know what an interface or protocol is. No provider account is needed to follow the examples.
The problem with calling an SDK everywhere
The quickest way to use a model is to install a provider's SDK and call it where you need it. A summarizer, a support bot, and a classifier each import the SDK, build a request in the provider's format, and read the reply in the provider's format.
# Direct coupling: this shape is repeated in every feature.
def summarize(client, text: str) -> str:
response = client.chat.completions.create(
model="provider-a-large",
messages=[{"role": "user", "content": f"Summarize: {text}"}],
max_tokens=256,
)
return response.choices[0].message.contentThis works. The cost shows up later, because the provider's details are now part of your application.
What the coupling costs
Direct calls spread provider details through your code in four ways.
- Switching is a rewrite. Moving to another provider means finding and editing every call site. Request fields, response paths, and error types all differ, so each edit is a small chance for a bug.
- Tests need the network. Code that calls an SDK directly is hard to test without a real call or a mock that copies the SDK's internal shape. Tests become slow, costly, and fragile.
- Failure handling is inconsistent. Each feature catches the provider's own exceptions. One feature retries on a rate limit, another crashes, and none can fall back to a second provider.
- Provider types leak. Objects such as
response.choices[0].message.contentend up in your business logic and sometimes in your database or logs. Later, they are hard to remove.
Pricing, model availability, outages, and data-handling rules all change over time. Being locked to one provider's code shape makes it expensive to react.
The idea: depend on one narrow surface
The fix is to define one small interface that your application owns. Application code talks only to that interface. One adapter per provider translates between your types and the provider's API.
Only the adapters know about SDKs and wire formats. Everything above the interface sees your own request and response types.
A first look at the surface
The rest of this tutorial builds the interface step by step. Here is the shape you are aiming for.
from dataclasses import dataclass
from typing import Protocol
@dataclass
class Message:
role: str # "system", "user" or "assistant"
content: str
@dataclass
class ChatRequest:
model: str
messages: list[Message]
max_tokens: int = 512
temperature: float | None = None
@dataclass
class ChatResponse:
text: str
model: str
input_tokens: int | None = None
output_tokens: int | None = None
class ChatProvider(Protocol):
def complete(self, request: ChatRequest) -> ChatResponse: ...summarize now needs only a ChatProvider. It never learns which vendor sits behind it.
def summarize(provider: ChatProvider, text: str) -> str:
request = ChatRequest(
model="any",
messages=[Message("user", f"Summarize: {text}")],
)
return provider.complete(request).textSwitching providers now means choosing a different adapter at startup. The call sites do not change.
What this does not buy you
An interface hides syntax. It does not make providers identical. Models give different answers to the same prompt, support different features, and enforce different limits. Later chapters cover these gaps, including streaming, tool calls, and where an existing gateway library is the better choice than writing your own.
Summary
Calling provider SDKs directly makes switching costly, testing hard, and error handling uneven. A neutral interface that your application owns, with one adapter per provider, confines those costs to a single layer.
Exercise
A team has the same client.chat.completions.create(...) call in 40 places. Name two concrete problems this causes when they want to add a second provider, and the one change that fixes both.
Show answer
First, every one of the 40 call sites must be edited to build the second provider's request format and read its response format. Second, each site catches the first provider's exceptions, so errors from the second provider are handled inconsistently or not at all. The fix is to define a provider-neutral interface (request type, response type, and a complete method) and move provider-specific code into one adapter per provider, so call sites depend only on the interface.