Sub topic 13
When to Use an Existing Gateway or Library
This chapter assumes you have read the earlier chapters. You should be comfortable with the neutral request and response types, the ChatProvider protocol, adapters, error normalization, and fallback. It does not repeat them. Its question is whether to keep maintaining your own layer or adopt one that already exists.
What you have built, and what it costs to keep
The layer from the earlier chapters is small. It has neutral types, a protocol, one adapter per provider, a registry, and a fallback function. At a few hundred lines it is easy to read and easy to test. It also leaves out a lot of work that someone must do eventually:
- Each adapter must track changes to a provider's API, such as new parameters, renamed fields, new stop reasons, and deprecated models.
- Streaming, tool calls, and structured output each need their own normalization in every adapter.
- Errors must be mapped one provider at a time, and providers add new error shapes without notice.
- Cost tracking, rate limiting, caching, and logging are not in the interface at all.
Every new provider you support adds more of this work. The decision in this chapter is about who does that work: your team, or a project that spreads it across many users.
The three kinds of existing tools
Existing tools fall into three groups. They solve overlapping problems in different places.
| Kind | Where it runs | What it gives you | Typical cost |
|---|---|---|---|
| Client library | Inside your process | One call signature, many providers, normalized responses and errors | A dependency to upgrade; its abstractions can leak |
| Self-hosted gateway | A separate service you operate | A single HTTP endpoint, central keys, routing, budgets, logging | You run and secure another service |
| Hosted gateway | A third-party service | The same as a self-hosted gateway, without operating it | Another network hop, another vendor, and your prompts pass through it |
A client library replaces your adapters. A gateway replaces them and also moves the work out of your application. A gateway usually exposes an API that looks like one provider's API. Most commonly this is the OpenAI chat completions shape. Your code then talks to the gateway as if it were that provider, and the gateway translates for the others.
What a library or gateway typically handles
Both kinds of tool commonly cover the areas that your earlier chapters covered one by one:
- Translating one request shape into each provider's format.
- Normalizing streamed chunks into one event form.
- Mapping provider errors into a small set of categories.
- Retrying and falling back between providers or models.
A gateway often adds things a library cannot easily offer, because it sits outside your application and sees all traffic:
- Central storage of API keys, so applications never hold provider credentials.
- Per-team or per-key budgets and rate limits.
- A single place for logs, usage reports, and cost figures.
- Shared response caching across services.
- Routing rules that change without redeploying applications.
Check these claims against the specific project you evaluate. Features differ a lot between tools, and they change from release to release.
Decision criteria
Use the questions below to decide. No single answer settles it. Weigh them together.
How many providers and how often do they change?
If you use one provider and a fallback you rarely touch, your own thin layer is probably enough. If you support many providers or add new models often, the maintenance burden of adapters grows quickly, and a shared project is more attractive.
How many applications and teams call models?
One service with one team can live with a library or its own layer. Many services in different languages point toward a gateway. A gateway gives all of them one endpoint and one place to manage keys and budgets, whatever language they are written in.
What do you need beyond switching?
Switching is the smallest need. If you need central budgets, audit logs, or key isolation, those belong in a gateway. Building them into every application is hard to keep consistent.
How sensitive is the data?
A hosted gateway sees every prompt and response. Check its data handling terms against your compliance requirements before sending real data through it. A self-hosted gateway or an in-process library keeps traffic inside your own boundary, except for the final call to the model provider.
How much do you rely on provider-specific features?
Features such as prompt caching controls, extended reasoning settings, or built-in tools vary between providers. The earlier chapter on limits explained that no abstraction hides them fully. A tool that exposes only the common subset can block features you need. Look at whether it lets you pass provider-specific parameters through unchanged.
How much latency and failure risk can you add?
A gateway adds a network hop and a new component that can fail. A library adds neither, but it adds code in your process. Decide where you would rather carry that risk, and whether you can run the gateway with the same availability as your application.
Costs of adopting someone else's layer
Adoption is not free, and these are the usual costs to price in:
- Lagging support. A new provider feature may be missing from the tool for days or weeks. With your own adapter, you can add it the same day.
- Leaky abstractions. The tool's idea of a normalized response may not match yours. Fields you rely on may be absent or filled differently per provider.
- Larger surface area. A broad library brings many dependencies and many code paths you never use. Each one is a place for bugs and security issues.
- Coupling to the tool. You have reduced coupling to providers by creating coupling to the library or gateway. That is a trade, not an escape.
- Operational burden. A self-hosted gateway needs deployment, monitoring, upgrades, and secrets management.
Keep your own interface in front of it
You can adopt a tool and still protect yourself from it. Keep the ChatProvider protocol from the earlier chapters as the only surface your application code uses. Then write one adapter that calls the library or gateway. Application code does not change, and neither do your fakes and tests.
The example below assumes a gateway that accepts the OpenAI chat completions format over HTTP. It uses only the standard library plus urllib. The URL and key come from environment variables, and the model name is whatever the gateway has been configured to route.
import json
import os
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Protocol
@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
class ProviderError(Exception):
def __init__(self, message: str, retryable: bool):
super().__init__(message)
self.retryable = retryable
class ChatProvider(Protocol):
def complete(self, request: ChatRequest) -> ChatResponse: ...
class GatewayAdapter:
"""Adapter for a gateway that speaks the OpenAI chat completions format."""
def __init__(self, base_url: str, api_key: str, timeout: float = 30.0):
self.url = base_url.rstrip("/") + "/chat/completions"
self.api_key = api_key
self.timeout = timeout
def complete(self, request: ChatRequest) -> ChatResponse:
body = {
"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:
body["temperature"] = request.temperature
http_request = urllib.request.Request(
self.url,
data=json.dumps(body).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
},
method="POST",
)
try:
with urllib.request.urlopen(http_request, timeout=self.timeout) as resp:
data = json.load(resp)
except urllib.error.HTTPError as err:
retryable = err.code == 429 or err.code >= 500
raise ProviderError(f"gateway returned HTTP {err.code}", retryable)
except (urllib.error.URLError, TimeoutError) as err:
raise ProviderError(f"gateway unreachable: {err}", retryable=True)
usage = data.get("usage") or {}
return ChatResponse(
text=data["choices"][0]["message"]["content"] or "",
model=data.get("model", request.model),
input_tokens=usage.get("prompt_tokens"),
output_tokens=usage.get("completion_tokens"),
)
def build_gateway_provider() -> ChatProvider:
return GatewayAdapter(
base_url=os.environ["LLM_GATEWAY_URL"],
api_key=os.environ["LLM_GATEWAY_KEY"],
)This adapter is short because the gateway did the translation. Your error normalization is still needed. The gateway may pass through a provider's error, so map HTTP status codes to the retryable flag as before. Register build_gateway_provider in your REGISTRY under a name such as "gateway", and switch to it with LLM_PROVIDER=gateway.
Layered fallback and double retries
When you use a gateway that already retries and falls back, your own complete_with_fallback is now a second layer on top of the first. Two layers can cause problems:
- Retry multiplication. If the gateway retries three times and your code retries three times, one failed request becomes nine upstream attempts. This can worsen an outage and raise cost.
- Hidden fallback. If the gateway silently switches model,
ChatResponse.modelis the only record of what answered. Always pass that field through, and log it. - Unclear ownership. When something goes wrong, you need to know which layer made which decision.
Choose one layer to own retry and fallback. If the gateway owns it, reduce your own policy to a single attempt and treat gateway errors as final. If your code owns it, turn the gateway's retries off.
A migration path
You do not need to decide everything at once. A sequence that keeps risk low:
- Keep your own layer while you use one or two providers.
- When maintenance of adapters becomes a recurring cost, evaluate a library or gateway against your real requests, not only its documentation.
- Write a single adapter for the candidate behind your
ChatProviderprotocol. - Run your existing test suite using fakes. It should pass without change, because it never touched the adapter.
- Route a small share of real traffic through the new adapter, compare responses, errors, latency, and cost, then widen the share.
- Keep your previous adapters for a while as a fallback, then remove the ones you no longer use.
Summary of the decision
| Situation | Reasonable choice |
|---|---|
| One or two providers, one team | Your own thin layer |
| Many providers, one application, one language | A client library behind your protocol |
| Many applications or languages, shared budgets and keys | A gateway, self-hosted or hosted |
| Strict data control | Own layer, library, or self-hosted gateway |
| Heavy use of provider-specific features | Own layer, or a tool with solid pass-through of provider parameters |
Exercise
Your team runs five services in three languages. All of them call models from two providers, and finance wants a monthly spend report per team. Which option fits best, a client library in each service or a gateway, and what should you do about retries if the gateway already retries failed calls?
Show answer
A gateway fits best. Five services in three languages would each need a library port or their own layer, while a gateway gives them one endpoint, and it can hold the keys and report spend per team in one place. For retries, let one layer own them. If the gateway retries and falls back, set the application's own retry policy to a single attempt, so that one failure does not multiply into many upstream calls. Log the model name in the response, since the gateway may have switched models.
Exercise
Why keep the ChatProvider protocol when you adopt a gateway that already exposes an OpenAI-style API?
Show answer
The protocol keeps application code and tests independent of the gateway. If you later change the gateway, leave it, or add a direct provider adapter, you change one adapter and the registry entry, not every call site. Fakes written for the protocol continue to work.