Sub topic 5
Writing Adapters for Two Providers
This chapter assumes you have the neutral types and the ChatProvider protocol from the earlier chapters. It also assumes you have called a hosted chat API before. The code uses httpx for HTTP (pip install httpx) and talks to the REST endpoints directly. That keeps the translation visible and avoids tying the chapter to an SDK version.
By the end you will have two adapters, one for an OpenAI-style Chat Completions API and one for the Anthropic Messages API. Both satisfy the same protocol.
What an adapter does
An adapter is a class with one public method, complete. It does four jobs:
- Translate a
ChatRequestinto the provider's JSON body and headers. - Send the HTTP request.
- Translate the provider's JSON back into a
ChatResponse. - Convert every failure into a
ProviderErrorwith a correctretryableflag.
Everything provider-specific stays inside the adapter. Application code never sees a provider field name.
Where the two APIs differ
These differences decide what each adapter must do.
| Concern | OpenAI-style Chat Completions | Anthropic Messages |
|---|---|---|
| Endpoint | `/v1/chat/completions` | `/v1/messages` |
| Auth header | `Authorization: Bearer <key>` | `x-api-key: <key>` plus `anthropic-version` |
| System prompt | A message with role `system` | A top-level `system` field |
| `max_tokens` | Optional | Required |
| Reply text | `choices[0].message.content` (a string) | `content`, a list of typed blocks |
| Token usage | `usage.prompt_tokens`, `usage.completion_tokens` | `usage.input_tokens`, `usage.output_tokens` |
The system prompt is the clearest case. The neutral Message type allows the role "system", so the Anthropic adapter must pull those messages out of the list and move them into the system field.
Shared helpers
Both adapters use the same HTTP error handling. Put it in one place. The module below assumes your earlier definitions live in neutral.py: Message, ChatRequest, ChatResponse, ChatProvider and ProviderError.
# adapters.py
import os
import httpx
from neutral import ChatRequest, ChatResponse, ProviderError
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504, 529}
def post_json(
client: httpx.Client, url: str, headers: dict, payload: dict
) -> dict:
try:
response = client.post(url, headers=headers, json=payload)
except httpx.TransportError as exc:
# Timeouts and connection failures are transient.
raise ProviderError(f"network error: {exc}", retryable=True) from exc
if response.status_code >= 400:
retryable = response.status_code in RETRYABLE_STATUS
raise ProviderError(
f"HTTP {response.status_code}: {response.text[:200]}",
retryable=retryable,
)
try:
return response.json()
except ValueError as exc:
raise ProviderError("provider returned invalid JSON", retryable=True) from excThe status rules are the core of the error handling. A 429 (rate limit), 5xx or timeout may succeed on a retry or on another provider. A 400, 401 or 404 will fail the same way anywhere, so those are marked non-retryable. Anthropic's 529 ("overloaded") is in the retryable set. The next chapters build on this flag.
The OpenAI-style adapter
class OpenAIAdapter:
def __init__(
self,
api_key: str | None = None,
base_url: str = "https://api.openai.com/v1",
client: httpx.Client | None = None,
):
self.api_key = api_key or os.environ["OPENAI_API_KEY"]
self.base_url = base_url.rstrip("/")
self.client = client or httpx.Client(timeout=30.0)
def build_payload(self, request: ChatRequest) -> dict:
payload = {
"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:
payload["temperature"] = request.temperature
return payload
def parse_response(self, data: dict) -> ChatResponse:
choices = data.get("choices") or []
if not choices:
raise ProviderError("response contained no choices", retryable=False)
usage = data.get("usage") or {}
return ChatResponse(
text=choices[0]["message"].get("content") or "",
model=data.get("model", ""),
input_tokens=usage.get("prompt_tokens"),
output_tokens=usage.get("completion_tokens"),
)
def complete(self, request: ChatRequest) -> ChatResponse:
data = post_json(
self.client,
f"{self.base_url}/chat/completions",
{"Authorization": f"Bearer {self.api_key}"},
self.build_payload(request),
)
return self.parse_response(data)Three design choices matter here.
- Pure translation methods.
build_payloadandparse_responsedo no I/O. You can test them without a network or a mock. - Injected client. The
clientparameter lets tests pass in a client with a fake transport. - Configurable
base_url. Many servers expose an OpenAI-compatible API, including local runtimes and gateways. The same adapter then covers all of them.
The Anthropic adapter
This adapter does more translation: it extracts system messages, always sends max_tokens, and joins text blocks.
class AnthropicAdapter:
def __init__(
self,
api_key: str | None = None,
base_url: str = "https://api.anthropic.com/v1",
client: httpx.Client | None = None,
):
self.api_key = api_key or os.environ["ANTHROPIC_API_KEY"]
self.base_url = base_url.rstrip("/")
self.client = client or httpx.Client(timeout=30.0)
def build_payload(self, request: ChatRequest) -> dict:
system_parts = [m.content for m in request.messages if m.role == "system"]
turns = [
{"role": m.role, "content": m.content}
for m in request.messages
if m.role != "system"
]
if not turns:
raise ProviderError(
"request needs at least one user or assistant message",
retryable=False,
)
payload = {
"model": request.model,
"messages": turns,
"max_tokens": request.max_tokens,
}
if system_parts:
payload["system"] = "\n\n".join(system_parts)
if request.temperature is not None:
payload["temperature"] = request.temperature
return payload
def parse_response(self, data: dict) -> ChatResponse:
blocks = data.get("content") or []
text = "".join(b.get("text", "") for b in blocks if b.get("type") == "text")
usage = data.get("usage") or {}
return ChatResponse(
text=text,
model=data.get("model", ""),
input_tokens=usage.get("input_tokens"),
output_tokens=usage.get("output_tokens"),
)
def complete(self, request: ChatRequest) -> ChatResponse:
data = post_json(
self.client,
f"{self.base_url}/messages",
{
"x-api-key": self.api_key,
"anthropic-version": "2023-06-01",
},
self.build_payload(request),
)
return self.parse_response(data)The neutral max_tokens has a default of 512, so the required Anthropic field is always filled. The adapter keeps only blocks of type text. Other block types, such as tool-use blocks, are skipped here and handled in a later chapter.
Joining multiple system messages with a blank line is a policy choice. OpenAI would keep them as separate messages, so the two adapters can pass slightly different input to the models. Document choices like this in the adapter.
Test the adapters without a network
The httpx.MockTransport class lets you check the exact JSON each adapter sends and returns. The script below runs as written, given neutral.py and adapters.py.
# test_adapters.py
import json
import httpx
from adapters import AnthropicAdapter, OpenAIAdapter
from neutral import ChatRequest, Message, ProviderError
request = ChatRequest(
model="demo-model",
messages=[Message("system", "Be brief."), Message("user", "Hi")],
)
def anthropic_handler(http_request: httpx.Request) -> httpx.Response:
body = json.loads(http_request.content)
assert body["system"] == "Be brief."
assert body["messages"] == [{"role": "user", "content": "Hi"}]
assert body["max_tokens"] == 512
return httpx.Response(200, json={
"model": "demo-model",
"content": [{"type": "text", "text": "Hello"}],
"usage": {"input_tokens": 9, "output_tokens": 2},
})
def openai_handler(http_request: httpx.Request) -> httpx.Response:
body = json.loads(http_request.content)
assert body["messages"][0] == {"role": "system", "content": "Be brief."}
return httpx.Response(200, json={
"model": "demo-model",
"choices": [{"message": {"role": "assistant", "content": "Hello"}}],
"usage": {"prompt_tokens": 9, "completion_tokens": 2},
})
def make_client(handler) -> httpx.Client:
return httpx.Client(transport=httpx.MockTransport(handler))
a = AnthropicAdapter(api_key="test", client=make_client(anthropic_handler))
o = OpenAIAdapter(api_key="test", client=make_client(openai_handler))
for adapter in (a, o):
response = adapter.complete(request)
assert response.text == "Hello"
assert (response.input_tokens, response.output_tokens) == (9, 2)
rate_limited = OpenAIAdapter(
api_key="test",
client=make_client(lambda r: httpx.Response(429, text="slow down")),
)
try:
rate_limited.complete(request)
except ProviderError as err:
assert err.retryable is True
bad_request = OpenAIAdapter(
api_key="test",
client=make_client(lambda r: httpx.Response(400, text="bad model")),
)
try:
bad_request.complete(request)
except ProviderError as err:
assert err.retryable is False
print("all adapter checks passed")Both adapters return identical ChatResponse values from different wire formats. That is the property the interface exists to provide.
Common mistakes
- Leaking provider fields. Do not add something like
raw_choicestoChatResponseso one caller can read it. The caller is now coupled to one provider. If you need the raw body for debugging, log it inside the adapter. - Reading secrets at import time. Both adapters read the key in
__init__. A missing key then fails when you construct the adapter, not when the module loads. This also keeps unused providers from requiring keys. - Trusting the response shape. Both
parse_responsemethods use.getand check for empty lists. A malformed body then becomes aProviderErrorinstead of aKeyErrorin the middle of application code. - Marking everything retryable. A 400 caused by a bad request body will fail again. Retrying it wastes time and, for paid APIs, money.
- Silent translation. If an adapter drops a field it cannot support, such as a
temperaturethe model rejects, log it. Silent drops make behavior differ between providers without anyone noticing.
Exercises
Exercise
The Anthropic adapter joins system messages with a blank line, while the OpenAI adapter passes them through as separate messages. Name one risk of this difference, and one way to reduce it.
Show answer
The two models may receive different effective input. For example, the OpenAI model sees separate system messages that the Anthropic model sees as one block, so behavior can differ for reasons unrelated to the models. To reduce the risk, normalize before the adapters. For example, merge all system messages into one in a shared function, or reject requests with more than one system message. Then both adapters see the same shape.
Exercise
A provider returns HTTP 503 with a valid JSON error body. What does post_json do, and why is that the right choice for fallback?
Show answer
It raises ProviderError with retryable=True, because 503 is in RETRYABLE_STATUS. A 503 means the service is temporarily unavailable, so the same request may succeed on a retry or on another provider. The fallback logic can then move to the next provider without parsing provider-specific error bodies.