Sub topic 12
What the Abstraction Cannot Hide
This chapter assumes you have built the neutral request and response types, a ChatProvider protocol, at least one adapter, and the fallback function from earlier chapters. You should also be comfortable reading Python and have called a hosted chat completion API.
A provider interface hides the shape of a request. It does not hide what the model does with that request. Code that treats two providers as interchangeable because they share a type signature will pass its tests and still behave differently in production. This chapter lists the differences that survive the abstraction and gives you ways to handle each one.
Why the leak happens
The interface fixes the inputs and outputs of complete. It says nothing about these things:
- The text a model produces for the same prompt.
- Which options a provider honors, and which it ignores or rejects.
- How a provider counts tokens, bills, and limits traffic.
- What a provider does with content it considers unsafe.
An adapter can translate field names. It cannot make two different models think alike. The goal of this chapter is to find where that gap shows up and to decide, for each case, whether to expose it, approximate it, or refuse it.
The dotted lines show the leaks. Behavior, features, and limits reach the application whether or not the interface mentions them.
Model behavior
The same prompt produces different output on different models. Four differences cause most of the trouble.
- Instruction following. One model obeys a formatting rule such as "reply with only a number" reliably. Another adds a sentence of explanation. Parsing code that works for the first breaks on the second.
- System prompt weight. Providers place the system message differently, and models weigh it differently. A prompt tuned to resist user overrides on one model may be easier to override on another.
- Default style. Length, tone, and use of Markdown vary. Output shown directly to users looks different after a switch.
- Sampling. A
temperatureof 0.7 does not mean the same thing across models. Some providers also have different valid ranges, and some reasoning models reject the parameter.
Treat a provider switch as a change to your prompts, not only to your configuration. Keep a small set of representative inputs with checks on the output, and run it against each provider you support.
from dataclasses import dataclass
@dataclass
class Message:
role: str
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
CASES = [
("Reply with only the number: what is 2 + 3?", lambda t: t.strip() == "5"),
("Reply with only the word yes or no: is the sky blue?",
lambda t: t.strip().lower().rstrip(".") in {"yes", "no"}),
]
def run_behavior_suite(provider, model: str) -> list[tuple[str, bool]]:
results = []
for prompt, check in CASES:
request = ChatRequest(
model=model,
messages=[Message("user", prompt)],
temperature=0.0,
)
reply = provider.complete(request)
results.append((prompt, check(reply.text)))
return results
class StubProvider:
def complete(self, request: ChatRequest) -> ChatResponse:
return ChatResponse(text="5", model=request.model)
for prompt, passed in run_behavior_suite(StubProvider(), "stub"):
print(("PASS" if passed else "FAIL"), prompt)With the stub, the first case passes and the second fails, because the stub always answers "5". Run against a real adapter, the suite shows which provider breaks which formatting rule. Run it against real APIs on a schedule, not in your unit tests, since results can vary and calls cost money.
Feature support
Providers support different features, and the gaps appear in three forms.
| Gap | Example | Typical result if ignored |
|---|---|---|
| Parameter not supported | `temperature` on a reasoning model | The API returns a validation error |
| Capability not supported | Image input, tool calls, JSON mode | An error, or silently ignored input |
| Limit differs | Context window, maximum output tokens | Truncation or a "too long" error |
The dangerous case is the silent one. If an adapter drops a field it does not understand, the caller believes the option applied. An adapter should fail loudly when it cannot honor a request.
class UnsupportedFeature(Exception):
pass
class ModelCapabilities:
def __init__(self, max_context: int, supports_temperature: bool):
self.max_context = max_context
self.supports_temperature = supports_temperature
CAPABILITIES = {
"small-model": ModelCapabilities(max_context=8_000, supports_temperature=True),
"reasoning-model": ModelCapabilities(max_context=128_000, supports_temperature=False),
}
def check_request(request: ChatRequest) -> None:
caps = CAPABILITIES.get(request.model)
if caps is None:
raise UnsupportedFeature(f"No capability data for model {request.model!r}")
if request.temperature is not None and not caps.supports_temperature:
raise UnsupportedFeature(f"{request.model} does not accept temperature")
approx_tokens = sum(len(m.content) for m in request.messages) // 4
if approx_tokens + request.max_tokens > caps.max_context:
raise UnsupportedFeature(f"Request may exceed {caps.max_context} tokens")
check_request(ChatRequest("small-model", [Message("user", "hi")], temperature=0.2))
try:
check_request(ChatRequest("reasoning-model", [Message("user", "hi")], temperature=0.2))
except UnsupportedFeature as err:
print("Rejected:", err)The model names and numbers in the table are illustrative. Real values change often, so load them from configuration or from provider documentation, not from constants buried in code. The four-characters-per-token estimate is rough and varies by language and tokenizer. Use it only as a cheap pre-check, not as a guarantee.
Tokens, cost, and rate limits
Token counts are not comparable across providers. Each provider uses its own tokenizer, so the same text yields different counts. This has three consequences.
- A budget of 1,000 output tokens allows different amounts of text on different models.
input_tokensandoutput_tokensinChatResponseare accurate for billing on the provider that reported them. Summing them across providers gives a usable cost trend only if you also record which provider produced each count.- Some providers do not report usage on every response, which is why the neutral type allows
None.
Rate limits differ in unit and scope. One provider limits requests per minute, another limits tokens per minute, and some limit per model or per account. Your fallback logic from the retry chapter treats a rate-limit error as retryable. That is correct, but it hides a cost: falling back from a cheap model to an expensive one on every rate limit can multiply your bill during a traffic spike. Record the provider and model on every response, and alert on unexpected shifts in the fallback rate.
from collections import Counter
usage_by_provider: Counter = Counter()
def record_usage(provider_name: str, response: ChatResponse) -> None:
usage_by_provider[(provider_name, "input")] += response.input_tokens or 0
usage_by_provider[(provider_name, "output")] += response.output_tokens or 0
record_usage("a", ChatResponse("x", "m1", input_tokens=10, output_tokens=5))
record_usage("b", ChatResponse("y", "m2", input_tokens=12, output_tokens=None))
print(dict(usage_by_provider))Safety filters and refusals
Providers apply different content policies. A prompt that one model answers may be refused by another, and the refusal can arrive in three different ways: as a normal reply that says "I can't help with that", as a special finish reason, or as an HTTP error. Only the second and third are visible to code.
If your application relies on a particular answer, a refusal on the fallback provider is a failure that your error handling will not see. Normalize a content-filter finish reason into a field on the response, and decide in advance what the caller does with it.
Streaming, tool calls, and structured output
The earlier chapters covered how to normalize these. Some differences remain after normalization.
- Streaming. Normalized chunks hide when usage data arrives. One provider reports token counts in the last chunk, another does not report them while streaming. Your cost tracking for streamed calls may be less complete than for non-streamed calls.
- Tool calls. Providers differ in whether a model can request several tools in one turn, and how reliably it produces valid arguments. Always validate tool arguments against your own schema before running anything, whichever provider produced them.
- Structured output. A provider with enforced JSON schemas guarantees valid structure. A provider with only a "JSON mode" guarantees valid JSON but not your schema. Validate every structured reply in your own code, and treat a failure as a retryable condition.
import json
def parse_structured(text: str, required: set[str]) -> dict:
try:
data = json.loads(text)
except json.JSONDecodeError as err:
raise ValueError(f"Reply is not valid JSON: {err}") from err
if not isinstance(data, dict):
raise ValueError("Reply is not a JSON object")
missing = required - data.keys()
if missing:
raise ValueError(f"Missing fields: {sorted(missing)}")
return data
print(parse_structured('{"name": "Ada", "age": 36}', {"name", "age"}))
try:
parse_structured('{"name": "Ada"}', {"name", "age"})
except ValueError as err:
print("Invalid:", err)This check runs after the adapter and behaves the same for every provider, which is what makes it a good place to put the guarantee.
Deciding what to expose
Once you accept that differences remain, you have three design options for each one.
- Lowest common denominator. The interface only offers features every provider supports. This is simple and portable, and it gives up useful features.
- Optional features with capability checks. The interface offers a feature, and callers or adapters check support before use. This is the approach used in this chapter. It costs more code and needs maintained capability data.
- Provider-specific escape hatch. The request carries an
extradictionary passed through to one adapter. Callers can use special features, but each use ties that call site to a provider again.
Choose by how often the feature matters. A feature used on a few call sites can go through the escape hatch with a comment explaining the coupling. A feature used everywhere belongs in the neutral types.
Common mistakes
- Assuming a passing type check means equal behavior.
- Testing only with a fake provider and never against a real one. The fake proves your wiring, not your prompts.
- Falling back to a model with a smaller context window, so long inputs fail only on the fallback path, which is rarely exercised.
- Comparing token counts across providers as if they measured the same thing.
- Keeping capability data in code and forgetting to update it when a provider releases a new model.
Exercises
Exercise
Your adapter for provider B ignores the temperature field because the target model does not accept it. A caller sets temperature=0.0 to get repeatable output. What is wrong with ignoring the field, and what should the adapter do instead?
Show answer
The caller believes the option applied and will rely on repeatability that the model does not provide, and nothing in the response signals the problem. The adapter should raise an error such as UnsupportedFeature, or at minimum record a warning on the response that the option was not applied, so the caller can decide how to proceed.
Exercise
A fallback chain goes from a model with a 128,000-token context window to one with an 8,000-token window. The system works in testing but fails in production on long documents. Why, and how do you find it earlier?
Show answer
Tests used short inputs, so the primary model always succeeded and the fallback was never given a long input. In production, the primary fails with a retryable error and the smaller model then rejects the long input. Run a pre-check against the capabilities of every provider in the chain, and include a long-input case in tests that force the fallback path.
Exercise
A team compares monthly cost by summing input_tokens and output_tokens across two providers and finding that provider A looks 20% cheaper. Name two reasons this comparison can mislead.
Show answer
Each provider uses its own tokenizer, so the same text produces different token counts, and per-token prices differ too, so token totals alone do not give cost. Some responses also report no usage (the field is None), especially for streamed calls, so the totals may undercount one provider. Compare cost per task using each provider's price and the usage it reported, and record which provider produced each count.