Sub topic 1
Why one interface: the cost of calling providers directly
Most applications start with a single call to a hosted model. That call is easy to write and works well on day one. This chapter explains why the same call becomes expensive to change as it spreads through a codebase, and what a single application-level interface does about that. Later chapters build the interface step by step.
Prerequisites
This chapter assumes you can:
- Read and write Python. The examples use Python 3.10 or later, because they use
X | Nonetype syntax. - Work with HTTP APIs and JSON, including headers, status codes, and request and response bodies.
- Call at least one hosted LLM API in the chat completion style, where you send a list of messages and get a reply.
- Read interfaces, abstract classes, or
typing.Protocoldefinitions.
You don't need accounts with several providers. The examples use stand-in objects, so they run without network access or API keys.
What goes wrong with direct calls
A direct call means your application code imports a provider's SDK (software development kit, the vendor's client library) and uses its request and response shapes everywhere. For one provider and one call site, this is the simplest design, and you should not apply the ideas below to it.
The trouble starts when the same pattern repeats. A typical codebase grows like this:
- A first feature calls the SDK in a request handler.
- A second feature copies the call and changes the prompt.
- A background job adds its own call, with its own retry loop.
- Someone adds token counting for cost tracking, reading the SDK's usage fields.
- Tests are written by patching the SDK client in each module.
After a few months, knowledge of one vendor's API is spread across many files. Changing providers is no longer a configuration change. It is a code search.
A concrete example of coupling
The following code reads the reply text and token usage from two provider-shaped responses. The SimpleNamespace objects imitate the response shapes of two widely used chat APIs so that the script runs offline. One API returns the text in choices[0].message.content and reports prompt_tokens. The other returns a list of content blocks and reports input_tokens.
from types import SimpleNamespace
# Stand-ins shaped like two vendors' responses.
openai_style = SimpleNamespace(
choices=[SimpleNamespace(message=SimpleNamespace(content="Hello"))],
usage=SimpleNamespace(prompt_tokens=12, completion_tokens=3),
)
anthropic_style = SimpleNamespace(
content=[SimpleNamespace(type="text", text="Hello")],
usage=SimpleNamespace(input_tokens=12, output_tokens=3),
)
def reply_text(response, vendor: str) -> str:
if vendor == "openai":
return response.choices[0].message.content
if vendor == "anthropic":
return "".join(b.text for b in response.content if b.type == "text")
raise ValueError(f"unknown vendor: {vendor}")
def tokens_used(response, vendor: str) -> tuple[int, int]:
if vendor == "openai":
return response.usage.prompt_tokens, response.usage.completion_tokens
if vendor == "anthropic":
return response.usage.input_tokens, response.usage.output_tokens
raise ValueError(f"unknown vendor: {vendor}")
assert reply_text(openai_style, "openai") == "Hello"
assert reply_text(anthropic_style, "anthropic") == "Hello"
assert tokens_used(openai_style, "openai") == (12, 3)
assert tokens_used(anthropic_style, "anthropic") == (12, 3)
print("both shapes handled")Two functions and two vendors already produce two if chains. Each new vendor adds a branch to every function like these. Each new piece of data you read, such as the stop reason or a request ID, adds another function. The vendor name also has to travel with every response, which is itself a form of coupling.
This is the mild case, because it only covers reading responses. The request side is worse. The two APIs differ in where the system prompt goes, whether max_tokens is required, and how tools are described. The next chapter covers those differences in detail.
Where the coupling spreads
Provider-specific knowledge tends to leak into five places.
- Request building. Code constructs vendor-shaped payloads, including model names, message lists, and parameter names.
- Response parsing. Code digs into nested fields to find text, usage, and stop reasons.
- Error handling. Code catches vendor-specific exception classes and reads vendor-specific status codes and messages.
- Streaming. Code consumes vendor-specific event types to assemble partial output.
- Tests. Tests patch a vendor client or record vendor-shaped fixtures.
The last item is easy to miss. If tests reproduce vendor response shapes, they break when you change providers, even if the behavior you care about is unchanged. They also give false confidence, because they test your mock more than your logic.
What the coupling costs
The cost is not the first integration. It is every change after it.
| Situation | With direct calls | With one interface |
|---|---|---|
| Moving to a cheaper or newer provider | Edit every call site, parser, and error handler | Add or change one adapter, then change configuration |
| Provider outage or rate limit | Each caller writes its own retry logic, or none | One fallback policy applies to all callers |
| Comparing two providers on your own prompts | Duplicate code paths for each | Run the same calling code with two adapters |
| Unit tests | Patch SDK internals in many modules | Pass a fake object that implements the interface |
| SDK upgrade with breaking changes | Fixes spread across the codebase | Fixes stay inside one adapter |
| Cost and usage reporting | Per-vendor field names in every report | One usage type with one set of field names |
The table shows two distinct benefits. Some are about change: swapping providers, upgrading SDKs, and comparing models. Others are about consistency: retries, error handling, and usage reporting that behave the same everywhere. Consistency matters even if you never switch providers, because without a shared layer each caller invents its own policy.
The idea: one surface, many adapters
The fix is to define a small interface that your application owns. Application code talks only to that interface. For each provider, an adapter translates between your neutral types and that provider's API. Only adapters import vendor SDKs.
Before, the number of connections grows with modules multiplied by vendors. After, it grows with modules plus vendors. Adding a module touches the interface only. Adding a vendor touches one adapter only.
Here is a small preview of the shape. You will design the real types and the interface properly in later chapters, so treat this as a sketch.
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
@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: ...
class EchoProvider:
"""A stand-in provider that repeats the last user message."""
def complete(self, request: ChatRequest) -> ChatResponse:
last = request.messages[-1].content
return ChatResponse(text=f"echo: {last}", model=request.model)
def greet(provider: ChatProvider, name: str) -> str:
request = ChatRequest(
model="any",
messages=[Message("user", f"Say hello to {name}")],
)
return provider.complete(request).text
print(greet(EchoProvider(), "Ada"))The function greet knows nothing about any vendor. It depends on ChatProvider, which is a structural type: any object with a matching complete method qualifies, with no inheritance needed. Replacing EchoProvider with a real adapter requires no edit to greet.
Common mistakes when introducing the interface
Teams that adopt this pattern tend to make the same errors.
- Abstracting too early. If you have one provider and no plans to change, a thin wrapper may be enough. Add the full layer when a second provider, a fallback requirement, or testing pain appears.
- Copying one vendor's shape. If the neutral types mirror vendor A's fields exactly, vendor B's adapter becomes awkward, and vendor A's quirks leak through. Design from what your application needs.
- Using the lowest common denominator by default. Exposing only features every provider supports is safe but wastes capabilities. Decide deliberately which features are in the interface and which are optional.
- Assuming the interface makes models interchangeable. The interface unifies the call, not the behavior. The same prompt can produce different quality, length, and formatting on different models.
- Letting vendor types escape. If an adapter returns a raw vendor object inside
ChatResponse, callers will start depending on it, and the isolation is gone.
The last two points matter most. They decide whether the abstraction saves you work or only moves it. A later chapter covers what an abstraction cannot hide.
What the rest of the tutorial builds
The remaining chapters take the sketch above and make it real, in this order:
- How the provider APIs differ in request shape, streaming, tool calls, and errors.
- Neutral request and response types, and the provider interface.
- Adapters for two providers.
- Provider selection from configuration.
- Testing with a fake provider.
- Normalized errors, streaming, and tool calls.
- Retry and fallback rules.
- The limits of the abstraction, and when an existing gateway library is the better choice.
You now have the reason for all of it. Vendor-specific code spreads, the spread makes change expensive, and an interface that your application owns keeps that knowledge in a few small adapters.
Exercise
A team has 12 modules that each call vendor A directly. They want to add vendor B as a fallback. Using the Before and After diagram's reasoning, how many module-to-vendor connections must they maintain with direct calls, and how many connections exist after introducing one interface with two adapters? Name one benefit besides switching that the interface gives them.
Show answer
With direct calls, each of the 12 modules may need to talk to both vendors, so up to 12 x 2 = 24 module-to-vendor connections. With the interface, there are 12 module-to-interface connections plus 2 interface-to-adapter connections, which is 14. Other benefits include one shared retry and fallback policy, one usage-reporting type, tests that use a fake object instead of patched SDK clients, and SDK upgrade fixes confined to one adapter.