Sub topic 5
Writing adapters for two providers
This chapter assumes you have the neutral Message, ChatRequest, ChatResponse types and the ChatProvider protocol from the earlier chapters. The examples import them from a module called llm_types. You also need Python 3.10 or later and the httpx package.
What an adapter does
An adapter is a class that satisfies ChatProvider. It does three jobs:
- Translate a
ChatRequestinto the provider's JSON body and headers. - Send the HTTP call.
- Translate the provider's JSON back into a
ChatResponse.
Keep the translation in separate methods from the network call. You can then test the translation without a network.
The OpenAI adapter
The OpenAI chat completions endpoint accepts the system, user and assistant roles directly in messages. This is close to the neutral shape.
import os
import httpx
from llm_types import ChatRequest, ChatResponse
class OpenAIAdapter:
URL = "https://api.openai.com/v1/chat/completions"
def __init__(self, api_key: str | None = None, client: httpx.Client | None = None):
self.api_key = api_key or os.environ["OPENAI_API_KEY"]
self.client = client or httpx.Client(timeout=30)
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:
usage = data.get("usage", {})
return ChatResponse(
text=data["choices"][0]["message"]["content"] or "",
model=data["model"],
input_tokens=usage.get("prompt_tokens"),
output_tokens=usage.get("completion_tokens"),
)
def complete(self, request: ChatRequest) -> ChatResponse:
resp = self.client.post(
self.URL,
headers={"Authorization": f"Bearer {self.api_key}"},
json=self.build_payload(request),
)
resp.raise_for_status()
return self.parse_response(resp.json())The Anthropic adapter
The Anthropic Messages API differs in three ways that the adapter must handle:
- The system prompt is a top-level
systemfield, not a message. max_tokensis required.- The reply is a list of content blocks, not one string.
class AnthropicAdapter:
URL = "https://api.anthropic.com/v1/messages"
def __init__(self, api_key: str | None = None, client: httpx.Client | None = None):
self.api_key = api_key or os.environ["ANTHROPIC_API_KEY"]
self.client = client or httpx.Client(timeout=30)
def build_payload(self, request: ChatRequest) -> dict:
system = "\n\n".join(m.content for m in request.messages if m.role == "system")
payload = {
"model": request.model,
"max_tokens": request.max_tokens,
"messages": [
{"role": m.role, "content": m.content}
for m in request.messages
if m.role != "system"
],
}
if system:
payload["system"] = system
if request.temperature is not None:
payload["temperature"] = request.temperature
return payload
def parse_response(self, data: dict) -> ChatResponse:
text = "".join(b["text"] for b in data["content"] if b["type"] == "text")
usage = data.get("usage", {})
return ChatResponse(
text=text,
model=data["model"],
input_tokens=usage.get("input_tokens"),
output_tokens=usage.get("output_tokens"),
)
def complete(self, request: ChatRequest) -> ChatResponse:
resp = self.client.post(
self.URL,
headers={
"x-api-key": self.api_key,
"anthropic-version": "2023-06-01",
},
json=self.build_payload(request),
)
resp.raise_for_status()
return self.parse_response(resp.json())Test the translation offline
Because build_payload and parse_response are pure functions, you can check them with sample data and no API key.
from llm_types import Message, ChatRequest
adapter = AnthropicAdapter(api_key="test")
request = ChatRequest(
model="any",
messages=[Message("system", "Be brief."), Message("user", "Hi")],
)
payload = adapter.build_payload(request)
assert payload["system"] == "Be brief."
assert payload["messages"] == [{"role": "user", "content": "Hi"}]
reply = adapter.parse_response({
"model": "any",
"content": [{"type": "text", "text": "Hello"}],
"usage": {"input_tokens": 5, "output_tokens": 1},
})
assert reply.text == "Hello" and reply.output_tokens == 1Common mistakes
- Sending the system message inside Anthropic's
messageslist. The API rejects it. - Reading only
content[0]from an Anthropic reply. Join all text blocks. - Letting provider-specific names such as
prompt_tokensleak into the neutral types. - Using
raise_for_status()as your only error handling. It exposeshttpxerrors to callers. The error normalization chapter replaces it.
Exercise
A ChatRequest has two system messages followed by one user message. What does AnthropicAdapter.build_payload put in "system" and in "messages"?
Show answer
"system" holds the two system texts joined by a blank line ("\n\n"). "messages" holds only the single user message, because system-role messages are filtered out of the list.