Sub topic 3
Put a narrow seam around the model client
This chapter assumes you can write pytest tests, read basic Python classes and exceptions, and have called an LLM API and parsed a JSON reply. It also assumes you know dependency injection, which means passing a dependency to a function as an argument instead of creating it inside the function.
What a seam is
A seam is a place where you can swap one piece of behavior for another without editing the code around it. For LLM code, the most useful seam sits between your application logic and the model client.
Without a seam, the application code creates an SDK client itself, builds a request, and reads fields from the vendor's response object. Every test then needs the network, an API key, and a model that returns different text on each run. With a seam, the application code asks for a reply through a small interface, and tests supply their own object behind that interface.
Keep the seam narrow
A narrow seam exposes only what your application needs. If your code sends one prompt and reads back one string, the interface should have one method that takes a string and returns a string.
A narrow seam has three benefits:
- A test double only has to implement one method, so it stays short.
- Vendor details such as response classes, model names, and token settings stay in one adapter, not spread through your code.
- Changing providers means writing one new adapter. The application code and its tests stay the same.
A wide seam does the opposite. If your code accepts the whole SDK client, a fake must imitate nested objects such as client.chat.completions.create(...).choices[0].message.content. Those fakes are long and fragile, and they break when the SDK changes.
Define the seam with a Protocol
Python's typing.Protocol describes an interface by shape. Any object with a matching complete method satisfies it, with no inheritance needed.
import json
from typing import Protocol
class ChatClient(Protocol):
def complete(self, prompt: str) -> str: ...
def extract_total(client: ChatClient, invoice_text: str) -> float:
reply = client.complete(
f"Return JSON with a 'total' field for this invoice:\n{invoice_text}"
)
data = json.loads(reply)
return float(data["total"])extract_total receives the client as an argument. It never imports an SDK and never reads an API key. It builds a prompt, calls complete, and parses the string it gets back.
Write one adapter for the real SDK
The production code needs one small class that satisfies the protocol and talks to the real service. The example below uses the OpenAI Python SDK. Other vendors work the same way: you change the adapter and leave the rest alone.
from openai import OpenAI
class OpenAIChatClient:
def __init__(self, model: str = "gpt-4o-mini"):
self._client = OpenAI() # reads OPENAI_API_KEY from the environment
self._model = model
def complete(self, prompt: str) -> str:
response = self._client.chat.completions.create(
model=self._model,
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content or ""All vendor-specific knowledge lives in this class. You test it rarely, and only with the techniques in later chapters on recorded responses and live smoke tests. Most of your tests exercise the code on the application side of the seam.
Common errors
- Leaking vendor types. If
completereturns a response object instead of a string, every caller and every test depends on the SDK again. Convert to your own types inside the adapter. - Creating the client inside the function. A line such as
client = OpenAI()insideextract_totalremoves the seam. Pass the client in. - Making the interface too wide. Add methods only when the application needs them. Streaming and tool calls come later in this tutorial, and they can get their own narrow additions.
- Hiding retries in the adapter. Retry logic that you want to test belongs on the application side of the seam, where a fake can trigger it.
Exercise
A function takes an openai.OpenAI object and calls client.chat.completions.create(...) directly. Name two problems this causes for tests, and describe the change that fixes them.
Show answer
Tests need the network and an API key, or they must build a fake that imitates the SDK's nested response objects, which breaks when the SDK changes. The fix is to define a one-method interface such as ChatClient.complete(prompt) -> str, move the SDK call into an adapter class, and pass a ChatClient into the function so tests can supply a simple fake.