Sub topic 4
Defining the Provider Interface
What this chapter assumes
You can read Python 3.10 or later and know what a Protocol or abstract base class is. You have called a hosted chat completion API at least once. You have also read the previous chapter, which defined the neutral Message, ChatRequest and ChatResponse types. This chapter reuses those types and defines the one object that application code talks to: the provider interface.
What the interface is for
The interface is the only surface your application code may depend on. If a call site imports an OpenAI or Anthropic SDK type, the abstraction has leaked. The interface is also the contract that every adapter, fake and wrapper must satisfy, so it should be small. Each method you add must be implemented for every provider, and a method that only some providers can support makes the abstraction a lie.
The diagram shows the dependency direction. Application code points at the interface. Adapters also point at the interface. Nothing in the application points at an adapter.
The minimal interface
The first block repeats the neutral types so the chapter runs on its own. It adds ProviderError, which later chapters expand. The interface itself is the last class.
from dataclasses import dataclass
from typing import Protocol, runtime_checkable
@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 ProviderError(Exception):
def __init__(self, message: str, retryable: bool):
super().__init__(message)
self.retryable = retryable
@runtime_checkable
class ChatProvider(Protocol):
def complete(self, request: ChatRequest) -> ChatResponse:
"""Send one chat request and return one complete response.
Raises ProviderError for any failure. Never raises vendor exceptions.
"""
...The interface has one method. It takes one request object and returns one response object. Both types are neutral, so no vendor type crosses the boundary in either direction.
Design decisions behind the signature
One request object, not keyword arguments
A signature like complete(model, messages, temperature, top_p, ...) changes every time you add a parameter. With a ChatRequest, adding a field with a default breaks no existing implementation. Callers that don't set the field keep working, and adapters that don't support it can ignore it or reject it deliberately.
Configuration lives in the constructor
API keys, base URLs, timeouts and HTTP clients belong to the adapter's constructor. They do not belong in ChatRequest. They are facts about the connection, not about a single conversation. Keeping them out of the request also keeps secrets out of anything you log, cache or serialize from the request.
The model name is the exception. It is in the request because callers choose it per call. Model names are provider-specific strings, so a request for "gpt-4o" sent to an Anthropic adapter is an error. The configuration chapter covers how to map your own model aliases to provider model names.
Synchronous or asynchronous
Pick one style for the core interface. A synchronous complete is simplest to test and to call from scripts. If your application is built on asyncio, define the interface as async def complete. A provider that offers both needs two protocols, because a coroutine function and a plain function are not interchangeable at the call site.
class AsyncChatProvider(Protocol):
async def complete(self, request: ChatRequest) -> ChatResponse: ...Don't hide a sync call behind an async one with a thread pool unless you mean to. That choice affects latency and cancellation, and it should be visible in your design.
Errors are part of the signature
Python signatures don't declare exceptions, so the contract goes in the docstring and in tests. The rule used here is that adapters raise only ProviderError. A caller who has to catch openai.RateLimitError and anthropic.RateLimitError separately has coupling again. The error normalization chapter shows the mapping. For now, treat "raises only ProviderError" as a requirement of the interface.
Protocol or abstract base class
Python gives you two ways to write the interface.
| Aspect | `typing.Protocol` | `abc.ABC` |
|---|---|---|
| How a class conforms | By having matching methods (structural) | By inheriting from it (nominal) |
| Third-party classes | Can conform without changes | Must be wrapped or subclassed |
| Missing method detected | By a type checker such as mypy or pyright | At instantiation time, by Python |
| Shared helper code | Not available to implementers | Can provide concrete methods |
This tutorial uses Protocol because fakes and test doubles then need no inheritance. If you want shared behavior, such as logging every request, use an ABC or wrap providers in a decorator class. Both choices are legitimate. Choose one and stay with it.
Checking that an implementation conforms
A Protocol is enforced by your type checker, not by Python at runtime. Run mypy or pyright in CI, or conformance mistakes surface only when a call fails.
The @runtime_checkable decorator allows isinstance checks, but those checks are weak. They test only that an attribute named complete exists. They do not test parameters or return types.
class EchoProvider:
"""A trivial implementation used to demonstrate the contract."""
def complete(self, request: ChatRequest) -> ChatResponse:
last = request.messages[-1].content
return ChatResponse(text=last, model=request.model)
class WrongSignature:
def complete(self) -> str:
return "nope"
print(isinstance(EchoProvider(), ChatProvider)) # True
print(isinstance(WrongSignature(), ChatProvider)) # True, despite the wrong signatureThe second True shows why a runtime check is not enough. Write a contract test that calls the provider and checks behavior. Run it against every implementation, including real adapters when you have credentials available.
def check_contract(provider: ChatProvider) -> None:
request = ChatRequest(
model="test-model",
messages=[Message("user", "ping")],
)
response = provider.complete(request)
assert isinstance(response, ChatResponse)
assert isinstance(response.text, str)
assert response.model
assert response.input_tokens is None or response.input_tokens >= 0
check_contract(EchoProvider())
print("EchoProvider satisfies the contract")A real adapter should run the same function with a small, cheap model. When it fails, the cause is almost always in the adapter's translation code, which is the subject of the next chapter.
Keeping the interface small: optional capabilities
Streaming, tool calls and embeddings are not available everywhere, or they behave differently. If you add them to ChatProvider, every implementation must provide them, even when it can only fake them. The usual alternative is a second protocol for each optional capability. Callers check for the capability and choose a path.
from typing import Iterator
@runtime_checkable
class StreamingProvider(ChatProvider, Protocol):
def stream(self, request: ChatRequest) -> Iterator[str]: ...
class WordStreamer(EchoProvider):
def stream(self, request: ChatRequest) -> Iterator[str]:
yield from request.messages[-1].content.split()
def text_chunks(provider: ChatProvider, request: ChatRequest) -> Iterator[str]:
if isinstance(provider, StreamingProvider):
yield from provider.stream(request)
else:
yield provider.complete(request).text
request = ChatRequest(model="test-model", messages=[Message("user", "one two three")])
print(list(text_chunks(WordStreamer(), request))) # ['one', 'two', 'three']
print(list(text_chunks(EchoProvider(), request))) # ['one two three']This design keeps the core contract honest. A provider that cannot stream still satisfies ChatProvider, and callers get a defined fallback. The streaming chapter covers what stream should yield. Chunks of plain text are only a placeholder here.
Contract rules worth writing down
Write these rules in the module docstring or the project documentation, because the type signature alone can't express them:
completeis called with a fully builtChatRequestand does not modify it. Mutating the request would break fallback, which reuses the same request for the next provider.- A response always has non-empty
model. Use the model name the provider reports, falling back to the requested one. - Token counts are
Nonewhen the provider doesn't report them. Never invent a zero. - Only
ProviderErrorleavescomplete. Theretryableflag is set from the provider's failure mode, not guessed by the caller. - Adapters hold no per-conversation state. Each call is independent, and the full message history is in the request.
Rule 1 is easy to break by accident. An adapter that pops a system message off request.messages to build a vendor payload alters the caller's list. Build a new list instead.
Common errors
- Leaking vendor types. A method returns an SDK object or accepts one. Search your application code for imports of vendor packages. They should appear only in adapter modules.
- Putting credentials in the request. The request is likely to be logged. Pass keys to the adapter constructor.
- Relying on
isinstanceas validation. As shown above, it passes for a wrong signature. Use a type checker and a contract test. - Growing the interface per provider. Adding
complete_with_openai_logit_biasto the shared protocol defeats the purpose. Provider-specific options belong in an adapter-level configuration or an explicit extras field, discussed in the chapter on the limits of the abstraction. - Mixing sync and async. Passing an async provider to code that expects the sync protocol returns a coroutine instead of a
ChatResponse. A type checker catches this; at runtime it surfaces as anAttributeErrorfar from the cause.
Exercise
An adapter for a new provider needs to send the system prompt in a separate top-level field instead of in the message list. The adapter's author writes system = request.messages.pop(0) to extract it. Which interface rule does this break, and what should the adapter do instead?
Show answer
It breaks the rule that complete does not modify the request. Popping the message mutates the caller's list, so a later fallback attempt, a retry or the caller's own logging sees a request with the system message missing. The adapter should build a new list, for example system = next((m.content for m in request.messages if m.role == "system"), None) and rest = [m for m in request.messages if m.role != "system"], then use those local values to build the vendor payload.
Exercise
Why does isinstance(WrongSignature(), ChatProvider) return True in the example above, and what two checks would catch the problem?
Show answer
A runtime-checkable Protocol only verifies that an attribute named complete exists, not its parameters or return type. A static type checker such as mypy or pyright would report the mismatched signature when WrongSignature is passed where a ChatProvider is expected. A contract test such as check_contract would also fail, because calling complete(request) raises a TypeError for the unexpected argument.