Sub topic 2
Writing Adapters for Two Providers
Assume you know Python, HTTP APIs, JSON, and the basic idea of an interface or protocol. This chapter uses a small provider interface so application code does not depend on either provider's request or response format.
Translating provider-specific formats
An adapter translates between your neutral types and one provider's API. The application sends a ChatRequest to the adapter. The adapter builds the provider-specific JSON and converts the response back into a ChatResponse.
from dataclasses import dataclass
from typing import Callable, Protocol
import os
@dataclass
class Message:
role: str
content: str
@dataclass
class ChatRequest:
model: str
messages: list[Message]
max_tokens: int = 512
@dataclass
class ChatResponse:
text: str
model: str
class ChatProvider(Protocol):
def complete(self, request: ChatRequest) -> ChatResponse: ...
Send = Callable[[str, dict], dict]
class OpenAIAdapter:
def __init__(self, send: Send):
self.send = send
def complete(self, request: ChatRequest) -> ChatResponse:
payload = {
"model": request.model,
"messages": [m.__dict__ for m in request.messages],
"max_tokens": request.max_tokens,
}
data = self.send("/v1/chat/completions", payload)
return ChatResponse(
text=data["choices"][0]["message"]["content"],
model=data["model"],
)
class AnthropicAdapter:
def __init__(self, send: Send):
self.send = send
def complete(self, request: ChatRequest) -> ChatResponse:
system = next(
(m.content for m in request.messages if m.role == "system"), None
)
payload = {
"model": request.model,
"messages": [
{"role": m.role, "content": m.content}
for m in request.messages
if m.role != "system"
],
"max_tokens": request.max_tokens,
}
if system:
payload["system"] = system
data = self.send("/v1/messages", payload)
return ChatResponse(data["content"][0]["text"], data["model"])
def provider_from_config(send: Send) -> ChatProvider:
providers = {
"openai": lambda: OpenAIAdapter(send),
"anthropic": lambda: AnthropicAdapter(send),
}
name = os.getenv("LLM_PROVIDER", "openai")
try:
return providers[name]()
except KeyError:
raise ValueError(f"Unsupported provider: {name}")Choosing a provider from configuration
The LLM_PROVIDER environment variable selects the adapter at startup. Calling code still uses provider.complete(request). Changing providers therefore changes configuration rather than every call site.
Testing with a fake provider
A fake provider implements the same interface but performs no network request. It records calls and returns a predictable response.
class FakeProvider:
def __init__(self, reply: str = "test result"):
self.reply = reply
self.calls: list[ChatRequest] = []
def complete(self, request: ChatRequest) -> ChatResponse:
self.calls.append(request)
return ChatResponse(self.reply, request.model)
def summarize(provider: ChatProvider, text: str) -> str:
request = ChatRequest("test-model", [Message("user", f"Summarize: {text}")])
return provider.complete(request).text
fake = FakeProvider()
assert summarize(fake, "long document") == "test result"
assert fake.calls[0].messages[0].role == "user"Exercise
What must change in application code when LLM_PROVIDER changes from openai to anthropic?
Show answer
Nothing. Configuration selects a different adapter, while application code continues using the ChatProvider interface.