Sub topic 4
Defining the provider interface
This chapter defines the one surface your application code will depend on: a small interface that every provider adapter implements. It assumes you can read Python, know what a Protocol or abstract class is, and have called a hosted chat completion API at least once. The neutral request and response types from the previous chapter are reused here.
What the interface is for
Without an interface, each call site imports a vendor SDK and builds that vendor's request shape. Changing providers then means editing every call site. An interface moves that knowledge into one place. Application code talks to the interface. Adapters, covered in the next chapter, talk to the vendors.
A good interface is small. Every method you add is a method every adapter must implement and every fake must imitate. Start with the one operation nearly every application needs: send a chat request, get a response.
The neutral types and the Protocol
The request and response types carry only what all providers share. The ChatProvider protocol then states the one method adapters must offer.
from dataclasses import dataclass, field
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: ...A few design choices here are worth noticing.
temperatureisfloat | None.Nonemeans "use the provider's default". Providers have different defaults and different valid ranges, so the neutral type does not invent a value.- Token counts are optional. Some providers report them, and some do not report them in every mode.
Noneis honest. A fake zero would corrupt cost tracking. ChatResponse.modelrecords which model actually answered. This matters later, when fallback may send your request somewhere you did not first choose.
Why a Protocol and not a base class
A Protocol uses structural typing. Any class with a matching complete method satisfies it, with no inheritance. This has practical benefits.
- A test fake does not need to import or extend anything from your adapter package.
- A third-party wrapper you cannot modify can still be used if its method signature matches.
- A type checker such as mypy or pyright reports a mismatch at the point where you pass the object in.
The trade-off is that a Protocol does not enforce anything at runtime. If an adapter has the wrong signature, you learn this from the type checker or from a failing call, not from instantiation. An abstract base class (abc.ABC) raises an error when you create an incomplete subclass. Pick the base class if you want that runtime check. Pick the Protocol if you want looser coupling. This tutorial uses the Protocol.
Using the interface
Application code accepts the interface and never names a vendor.
def summarize(provider: ChatProvider, text: str) -> str:
request = ChatRequest(
model="any",
messages=[Message("user", f"Summarize: {text}")],
)
return provider.complete(request).textsummarize has no idea which vendor answers. The provider is passed in, which also makes it easy to replace in tests.
Common mistakes
- Leaking vendor fields. Adding
top_kor a vendor-specificsafety_settingsfield toChatRequestmakes the neutral type vendor-shaped again. Add a field only when most providers can honor it, or put rare options in a separate, clearly named extras mapping. - Returning raw vendor responses. If
completereturns the SDK's object, callers start reading vendor attributes. Always convert toChatResponseinside the adapter. - Putting the model name in the adapter. The model is a request field, so callers (or configuration) can choose it. Remember that model names are provider-specific, so a config that switches providers must also switch the model.
- Growing the interface early. Streaming, tool calls and embeddings are separate concerns. Add them as separate methods or protocols when you need them, so simple adapters and fakes stay simple.
Exercise
A teammate adds safety_settings: dict | None = None to ChatRequest because one provider supports it. Give one problem this causes and one alternative.
Show answer
Every caller and every other adapter now sees a field that only one vendor understands, so the neutral type is tied to that vendor and other adapters must decide what to do with it (ignore it silently or fail). An alternative is to keep ChatRequest limited to widely shared fields and pass rare options through a separate extras: dict that only the matching adapter reads, or to configure the setting inside that adapter.
Exercise
You choose a Protocol over an abstract base class for ChatProvider. Name one benefit and one cost of that choice.
Show answer
Benefit: a test fake or a wrapper class satisfies the interface without inheriting from anything, so it stays decoupled. Cost: Python does not check the method signature at instantiation, so a wrongly shaped adapter is only caught by a type checker or when the call fails.