Sub topic 3
Normalizing Provider Differences
Assume you already have provider-neutral ChatRequest and ChatResponse types, a ChatProvider interface, and adapters that call individual APIs. This chapter focuses on differences that remain at the adapter boundary.
Normalizing errors
Providers use different exception types and status codes. Convert them into a small application-level error model. Keep whether an error is retryable, because an invalid request should not trigger another provider call.
from dataclasses import dataclass
from typing import Protocol
@dataclass
class ProviderError(Exception):
message: str
retryable: bool
code: str = "provider_error"
class ChatProvider(Protocol):
def complete(self, request: str) -> str: ...
def complete_with_fallback(
providers: list[ChatProvider], request: str
) -> str:
last_error: ProviderError | None = None
for provider in providers:
try:
return provider.complete(request)
except ProviderError as error:
if not error.retryable:
raise
last_error = error
raise last_error or ProviderError(
"No provider succeeded", retryable=True, code="unavailable"
)An adapter should map rate limits, timeouts, and temporary service failures to retryable=True. It should map authentication failures, malformed requests, and unsupported features to retryable=False.
Streaming responses
Streaming APIs commonly send partial text in different event formats. Adapters should expose one iterator of text chunks. The application can then render or collect chunks without knowing the provider.
Retries and fallback
Retry a transient failure with a short, bounded backoff. Switch providers when the configured policy allows it. Do not retry indefinitely or silently change providers for every error.
Tool calls and structured output
Tool calls, JSON schemas, vision inputs, and reasoning controls differ widely. A common interface can represent shared features, but adapters must reject unsupported options clearly. Validate structured output after receiving it.
Limits of the abstraction
A shared interface cannot hide model quality, token limits, pricing, latency, safety behavior, or exact tool-call semantics. These differences belong in configuration, capability checks, metrics, and documentation.
| Difference | Practical response |
|---|---|
| Context or output limits | Validate before sending |
| Tool-call support | Check adapter capabilities |
| Model behavior | Test each selected model |
Existing gateways and libraries
Use an existing gateway when you need many providers, centralized billing, observability, routing, or managed retries. Write your own small interface when you need strict control, few providers, or provider-specific features. An extra gateway also adds latency, cost, and another failure point.
Exercise
Which errors should normally trigger fallback?
Show answer
Transient errors such as timeouts, rate limits, and temporary service failures. Invalid requests and authentication errors should usually stop immediately.