Sub topic 13
When to use an existing gateway or library
This chapter assumes you have built the neutral types, the ChatProvider interface, and at least one adapter from the earlier chapters. It also assumes you know what an HTTP proxy is. Writing every adapter yourself is not always the right call. Here you decide when to adopt something that already exists.
Two kinds of existing tools
A multi-provider library runs inside your process. You call one function, and the library translates the call for each provider's API. LiteLLM and the model classes in LangChain work this way.
A gateway is a separate service. Your code sends requests to it over HTTP, usually in the OpenAI chat format, and it forwards them to the real providers. Hosted routers such as OpenRouter and self-hosted proxies such as the LiteLLM proxy fit this description. Many gateways also add keys, budgets, logging, and caching.
Check each tool's current documentation before you commit. Supported providers and features change quickly.
What you gain and what you give up
| Concern | Writing your own adapters | Library or gateway |
|---|---|---|
| Time to first working provider | Hours per provider | Minutes |
| Coverage of new providers and models | You add each one | Often added by maintainers |
| Control over error mapping and retries | Full | Partial, set by the tool |
| New dependencies and failure points | None | A package, or a network hop |
| Central logging, budgets, key management | You build it | Often built in |
| Access to provider-specific features | Whatever you code | Only what the tool passes through |
A gateway also becomes a single point of failure and sees all your prompts. Those two facts matter for privacy reviews and for availability planning.
A decision path
Keep your own interface on top
Adopting a tool does not mean dropping ChatProvider. Wrap the tool in one adapter. Your application code then depends on your types, not on the tool's, and you can replace the tool later.
This adapter talks to any gateway that speaks the OpenAI chat format. It uses the openai Python package and assumes Message, ChatRequest, ChatResponse, and ProviderError from earlier chapters are in scope.
import os
import openai
from openai import OpenAI
class GatewayAdapter:
def __init__(self):
self.client = OpenAI(
base_url=os.environ["GATEWAY_URL"],
api_key=os.environ["GATEWAY_KEY"],
)
def complete(self, request: ChatRequest) -> ChatResponse:
kwargs = {
"model": request.model,
"messages": [
{"role": m.role, "content": m.content}
for m in request.messages
],
"max_tokens": request.max_tokens,
}
if request.temperature is not None:
kwargs["temperature"] = request.temperature
try:
resp = self.client.chat.completions.create(**kwargs)
except (openai.RateLimitError, openai.APIConnectionError,
openai.APITimeoutError) as err:
raise ProviderError(str(err), retryable=True) from err
except openai.APIStatusError as err:
raise ProviderError(
str(err), retryable=err.status_code >= 500
) from err
usage = resp.usage
return ChatResponse(
text=resp.choices[0].message.content or "",
model=resp.model,
input_tokens=usage.prompt_tokens if usage else None,
output_tokens=usage.completion_tokens if usage else None,
)The error mapping stays in your code. This keeps complete_with_fallback working unchanged, whatever sits behind the adapter. Register the adapter in REGISTRY as "gateway" and select it by configuration like any other provider.
Common mistakes
- Letting the tool's response objects leak into application code. This recreates the coupling you set out to remove.
- Assuming the gateway's retry behavior matches yours. If both retry, one failure can multiply into many requests.
- Adopting a large framework only to get provider switching. A small library or gateway is usually enough.
Exercise
Your team calls two providers and has no shared key management needs. A colleague proposes deploying a self-hosted gateway. Name two costs of that choice and one situation in which it would become the better option.
Show answer
Costs: an extra service to run and secure, and an added network hop that is a new failure point and sees every prompt. It becomes better when many teams or services need shared keys, budgets, central logging, or when the number of providers grows enough that maintaining your own adapters costs more than operating the gateway.