Sub topic 3
Designing Provider-Neutral Request and Response Types
This chapter assumes you can read Python dataclasses and type hints, know what a chat completion request looks like as JSON, and have called at least one hosted LLM API. The previous chapter compared how provider APIs differ. This chapter turns that comparison into a small set of types that application code can depend on.
What the neutral types are for
Every call site in your application builds a request and reads a response. If those objects are an SDK's own classes, the SDK leaks into every file that touches a model. Neutral types are the replacement: plain data classes that you own, and that describe what your application needs to say to a model and hear back.
They have one job. They carry data across the boundary between application code and an adapter. Adapters, which later chapters cover, translate between these types and each provider's wire format. The types themselves contain no network code, no SDK imports and no provider names.
I need the diagram in the required form, so here it is.
The baseline types
These are the types the rest of the tutorial builds on.
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: ...The types are short on purpose. Each field is there because every provider you are likely to use supports it. Each design choice below has a reason, and each reason matters when you extend the types.
Design rules
Include only what every provider can express
The test for a field is simple: can each adapter map it to something real? Roles, text content, a model name, an output limit and a sampling temperature pass that test. Provider-specific controls such as logit bias, safety settings, or reasoning-effort parameters do not. If you add them to the neutral type, either some adapters must ignore them silently, or the type quietly becomes one provider's API under a general name.
A field that only some providers support is not automatically excluded. It needs an explicit rule for what happens when an adapter cannot honor it. Later sections cover the options.
Use `None` to mean "use the provider default"
temperature is float | None. A value of None tells the adapter to leave the parameter out of the payload. This matters because default temperatures differ between providers, and so do the valid ranges. If you defaulted to 0.7 in the neutral type, you would send a number the application author never chose, and you would send it to providers where 0.7 means something different.
Use None for any optional tuning knob. Use a concrete default only when the value is a safety limit rather than a tuning choice.
Always set `max_tokens`
max_tokens is an int with a default of 512, not an optional field. Some providers require an output limit on every request, and others make it optional. Making it required in the neutral type means the adapter never has to invent a number. Choosing the default is an application decision, and it belongs in one visible place.
Note that the meaning also differs slightly between providers. Some count only generated tokens, and some count reasoning tokens against the same limit. The type cannot hide that, and a later chapter returns to it.
Keep roles as the common subset
Three roles (system, user and assistant) work across providers. The places they differ are in how they are sent:
- Some APIs take system instructions as a message with role
system. - Others take them as a separate top-level parameter and reject a
systemmessage inside the list. - Newer APIs on some providers use a role such as
developerfor the same purpose.
The neutral type keeps system as an ordinary role in the list, and the adapter does the rearranging. That is the right place for the difference, because only the adapter knows its provider's rules. Application code should not need to know.
Report usage as optional
input_tokens and output_tokens are int | None. Providers name these differently (prompt_tokens and completion_tokens in one family, input_tokens and output_tokens in another), and some responses, notably streamed ones, omit them. Choosing one pair of names and making the values optional lets adapters report what they have. It also forces callers that do cost accounting to handle the missing case instead of treating a missing count as zero.
Return only what callers use
ChatResponse has the generated text, the model that answered and the token counts. The model field is the model the provider reports, which can differ from the one requested when a provider resolves an alias to a dated version. Logging it helps when behavior changes without a code change.
Do not copy the whole provider response into the neutral type. A response type that mirrors a provider's JSON re-creates the coupling you are trying to remove.
Field-by-field mapping
The table shows how each neutral field typically maps. The provider columns describe common patterns, not exact API contracts, so check your provider's current documentation when you write an adapter.
| Neutral field | Pattern A: system role inside messages | Pattern B: separate system parameter | Adapter duty |
|---|---|---|---|
| `model` | Sent as `model` | Sent as `model` | Usually pass through. Translate aliases if you define them. |
| `messages` with role `system` | Kept in the list | Removed from the list and sent as a top-level value | Split and join system text. |
| `max_tokens` | Optional, may use a different parameter name | Required | Always send it, under the right name. |
| `temperature` | Optional, range may differ | Optional, range may differ | Omit when `None`. Validate or clamp the range. |
| `input_tokens` | Read from a usage object with one set of names | Read from a usage object with another set of names | Rename and convert. Use `None` if absent. |
Making the types safer
Plain dataclasses accept anything. A typo such as role="User" passes silently and fails later, inside a provider's HTTP error, far from the cause. Validate at construction time, so the error points at the line that built the bad request.
from dataclasses import dataclass
VALID_ROLES = {"system", "user", "assistant"}
@dataclass(frozen=True)
class Message:
role: str
content: str
def __post_init__(self) -> None:
if self.role not in VALID_ROLES:
raise ValueError(f"Invalid role: {self.role!r}")
@dataclass(frozen=True)
class ChatRequest:
model: str
messages: tuple[Message, ...]
max_tokens: int = 512
temperature: float | None = None
def __post_init__(self) -> None:
if not self.messages:
raise ValueError("messages must not be empty")
if self.max_tokens <= 0:
raise ValueError("max_tokens must be positive")
if self.temperature is not None and not 0.0 <= self.temperature <= 2.0:
raise ValueError("temperature must be between 0 and 2")
try:
Message("User", "hello")
except ValueError as err:
print(err) # Invalid role: 'User'
request = ChatRequest(model="any", messages=(Message("user", "hello"),))
print(request.max_tokens) # 512Two changes are worth noting. First, frozen=True makes the objects immutable, so an adapter cannot modify a request that a retry or a fallback will send to the next provider. Second, messages became a tuple, because a frozen dataclass holding a mutable list is only shallowly immutable. If you prefer lists, copy them inside the adapter before editing.
The temperature range of 0 to 2 is a choice. It is the widest range among common providers. An adapter whose provider accepts only 0 to 1 must decide whether to clamp or raise. Raising is safer, because clamping changes the behavior the caller asked for without telling them.
Handling features only some providers support
Sooner or later you will want something the common subset lacks, such as image input or a stop sequence. There are three ways to handle it, and each costs something.
- Add it to the neutral type and require every adapter to honor it. This is clean, but it limits you to features all your providers share.
- Add it as optional, and let adapters that cannot honor it raise a clear error. Callers learn immediately that the feature is unavailable on that provider. This is usually the best default.
- Add a generic
extradictionary that adapters pass through. This is flexible, but call sites that set provider-specific keys are coupled to that provider again, and the neutral type no longer protects you.
Prefer option 2 for features you expect to use, and use option 3 only as a short-term escape hatch, with a comment naming the provider it targets.
Changing the types later
The neutral types become a contract. Many call sites, tests and adapters depend on them, so changes should be cautious.
- Adding an optional field with a default is safe. Existing code does not notice.
- Adding a required field breaks every constructor call.
- Renaming or removing a field breaks every adapter and call site.
- Changing the meaning of a field, such as switching
max_tokensfrom total tokens to output tokens, breaks callers without any error, which makes it the most dangerous change.
When in doubt, add a new optional field and leave the old one in place until all users have moved.
Common mistakes
- Copying one provider's schema. The types end up named neutral but shaped like one API, and the other adapters need awkward workarounds.
- Defaulting every tuning parameter. Callers cannot tell "I chose this" from "nobody chose this," and providers receive values nobody picked.
- Using
0for missing token counts. Cost reports then understate usage, and nothing flags the gap. - Exposing raw provider objects in the response. One call site reads a provider-specific field, and the abstraction leaks from that point on.
- Mutable shared requests. A fallback path that edits the request changes what the next attempt sees.
Exercise
A teammate adds top_k: int = 40 to ChatRequest because one provider supports it. Give two problems with this choice, and a better design.
Show answer
First, providers that do not support top_k have no meaning for it, so their adapters must either ignore it silently or raise, and the default of 40 would be sent to the providers that do support it, which overrides that provider's own default without anyone choosing it. Second, any call site that sets it is tied to one provider's behavior, so switching providers changes results. A better design is top_k: int | None = None, where None means "use the provider default," plus a rule that an adapter without support raises a clear error when the value is set. If only one provider ever needs it, keep it out of the neutral type and handle it in that adapter's configuration.
Exercise
Why does the validated ChatRequest store messages as a tuple in a frozen dataclass, rather than a list?
Show answer
A frozen dataclass prevents reassigning fields, but a list stored in a field can still be changed in place. A tuple cannot be changed, so a request is fully immutable. This prevents an adapter, retry or fallback path from altering a request that another attempt will reuse.