Sub topic 3
Put a narrow seam around the model client
This chapter assumes you can write pytest tests, read Python classes and exceptions, and have called an LLM API and parsed its JSON reply. It also assumes you know the basic idea of dependency injection, which means passing a dependency to a function as an argument instead of creating it inside.
By the end you will have one small interface that the rest of your code uses to talk to a model. Every later technique in this tutorial, scripted fakes and recorded replays, plugs into that interface.
What a seam is
A seam is a place where you can change behavior without editing the code around it. In LLM code, the useful seam sits between your logic (prompt building, parsing, retries, validation) and the vendor SDK that makes the network call.
Your logic is the part you wrote and want to test. The SDK call is the part that is slow, costs money, and returns different text on each run. The seam lets tests replace the second part and keep the first.
The problem with calling the SDK directly
Here is the shape that makes tests hard:
import json
from openai import OpenAI
def extract_total(invoice_text: str) -> float:
client = OpenAI()
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": f"Return JSON with a 'total' field for this invoice:\n{invoice_text}",
}
],
)
data = json.loads(resp.choices[0].message.content)
return float(data["total"])This function builds its own client, so a test cannot pass anything else in. Running it needs an API key and network access. The only way to test it without those is to patch the SDK's internals, for example OpenAI or chat.completions.create. Such a patch must copy the SDK's response shape exactly, and it breaks when you upgrade the SDK or switch vendors. The test ends up checking your knowledge of SDK internals, not your logic.
The function also mixes three jobs: building the prompt, calling the model, and parsing the reply. Only the middle job needs the network.
Define the seam
Start with the smallest interface that your code needs. For a function that sends one prompt and reads one text reply, that is one method.
from typing import Protocol
class LLMError(Exception):
"""Any failure of the model call that is not worth retrying."""
class LLMTransientError(LLMError):
"""A failure that may succeed if tried again: rate limit, timeout, dropped connection."""
class ChatClient(Protocol):
def complete(self, prompt: str) -> str: ...A Protocol describes a shape. Any object with a complete(prompt) -> str method satisfies it, with no inheritance needed. That is the property tests rely on: a test double only has to have the method.
The two exception classes belong to the seam too. They are explained below.
Now the application code depends only on ChatClient:
import json
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"])The function no longer knows which vendor, model, or API key is in use. It takes the client as an argument, which is dependency injection in its simplest form.
Write the adapter
The adapter is the only class that imports the vendor SDK. It translates between your interface and the SDK's types.
import openai
class OpenAIChatClient:
def __init__(
self,
sdk_client=None,
model: str = "gpt-4o-mini",
temperature: float = 0.0,
timeout: float = 30.0,
):
self._sdk = sdk_client or openai.OpenAI(timeout=timeout)
self._model = model
self._temperature = temperature
def complete(self, prompt: str) -> str:
try:
resp = self._sdk.chat.completions.create(
model=self._model,
temperature=self._temperature,
messages=[{"role": "user", "content": prompt}],
)
except (
openai.RateLimitError,
openai.APITimeoutError,
openai.APIConnectionError,
) as exc:
raise LLMTransientError(str(exc)) from exc
except openai.APIError as exc:
raise LLMError(str(exc)) from exc
content = resp.choices[0].message.content
if content is None:
raise LLMError("model returned no text content")
return contentFour decisions in this class are worth noting.
- Settings live in the adapter. The model name, temperature, and timeout are constructor arguments. Application code does not pass them on each call, so a change of model touches one place.
- The adapter returns plain
str. No SDK response object leaves this class. If it did, every caller and every test double would have to imitate that object. - SDK exceptions become your exceptions. The order of the
exceptclauses matters.RateLimitError,APITimeoutError, andAPIConnectionErrorare all subclasses ofopenai.APIError, so the specific clauses must come first. - A missing reply becomes an error. The SDK can return
Nonefor the message content, for example when the model answers with a tool call. Turning that into a clearLLMErrorat the seam keepsNonefrom reachingjson.loadsand failing with a confusingTypeError.
Your application code and tests now see only LLMError and LLMTransientError. A retry loop can catch LLMTransientError without importing any vendor module. Because your own tests can raise those same exceptions from a fake, you can exercise error handling without any network.
Wire it up in one place
Create the real client where the program starts, and pass it down.
def main() -> None:
client = OpenAIChatClient()
total = extract_total(client, "Widget x2 ... Total: $42.50")
print(total)
if __name__ == "__main__":
main()Build the real client in main or in your web framework's startup code, not inside business functions. If a function calls OpenAIChatClient() itself, you have rebuilt the problem from the first example.
A first test through the seam
The next chapter builds a full scripted fake. Here a five-line stub is enough to show that the seam works:
class StubClient:
def __init__(self, reply: str):
self._reply = reply
def complete(self, prompt: str) -> str:
return self._reply
def test_extract_total_reads_the_total_field():
assert extract_total(StubClient('{"total": 42.5}'), "any invoice") == 42.5This test runs in microseconds, needs no key, and gives the same result every time. It would still pass if you swapped OpenAI for another vendor, because nothing in it mentions a vendor.
Test the adapter without the network
The adapter has logic of its own: error translation and the None check. Because it accepts an sdk_client argument, you can test it with a fake SDK object.
from types import SimpleNamespace
import pytest
class FakeSDK:
def __init__(self, content):
message = SimpleNamespace(content=content)
response = SimpleNamespace(choices=[SimpleNamespace(message=message)])
self.chat = SimpleNamespace(
completions=SimpleNamespace(create=lambda **kwargs: response)
)
def test_adapter_returns_plain_text():
client = OpenAIChatClient(sdk_client=FakeSDK("hello"))
assert client.complete("hi") == "hello"
def test_adapter_rejects_missing_content():
client = OpenAIChatClient(sdk_client=FakeSDK(None))
with pytest.raises(LLMError):
client.complete("hi")This is the one place where you imitate the SDK's response shape. Keeping it to a single small class limits the cost of an SDK upgrade to one file. A live smoke test, covered in the last chapter, is what confirms that the imitation still matches the real SDK.
How wide should the seam be?
A narrow seam is easy to fake. A wide one gives callers more power. Choose the narrowest shape that your code really needs.
| Seam shape | Example signature | Good for | Cost |
|---|---|---|---|
| Prompt in, text out | `complete(prompt: str) -> str` | Single-turn tasks such as extraction and classification | Cannot express system prompts or multi-turn history |
| Message list in, text out | `complete(messages: list[dict]) -> str` | Chat with history and a system prompt | Callers must build the message format, and fakes see more structure |
| Message list in, result object out | `complete(messages) -> Reply` | Needs token counts, stop reasons, or tool calls | You must define `Reply` yourself and keep it independent of the SDK |
Start with the first row. Move to the next row when real code demands it, such as a second method or a richer return type. Do not add parameters in case they are useful later. Each one is another thing every fake must accept.
If you later need token usage for cost logging, return your own small dataclass with text and total_tokens fields. Do not return the SDK's response object. The test doubles in later chapters stay simple only if your types stay yours.
Common mistakes
- Patching the SDK instead of injecting a client.
unittest.mock.patch("openai.OpenAI")works, but it ties every test to SDK internals and hides the dependency. Pass the client as an argument. - Constructing the client at import time. A module-level
client = OpenAI()runs on import, so merely importing the module in a test can fail when no key is set. Build clients inmainor in a factory. - Leaking SDK types. If a caller reads
resp.choices[0], your seam has a hole. Check that nothing outside the adapter imports the vendor package. - A fat interface. A
ChatClientwith ten methods and optional parameters for every vendor feature forces every fake to implement all of them. Split by need, and add a separate narrow protocol for a feature such as embeddings. - Putting retries inside the adapter. Retries are your policy and you want to test them. Keep them in application code, where a fake can trigger them. The adapter only classifies failures as transient or not.
Exercise
Exercise
A teammate writes def summarize(text): client = OpenAIChatClient(); return client.complete(f"Summarize: {text}"). The module already has a ChatClient protocol. Name the problem this causes for tests and show the smallest change that fixes it.
Show answer
The function creates its own real client, so a test cannot replace it. Running the test would need an API key and network access, and the output would vary. The fix is to take the client as a parameter: def summarize(client: ChatClient, text: str) -> str: return client.complete(f"Summarize: {text}"). The real client is then built once at program start and passed in, and tests pass any object with a complete method.
Exercise
The adapter's complete method catches openai.APIError before openai.RateLimitError. What goes wrong, and how would a test show it?
Show answer
RateLimitError is a subclass of APIError, so the broad clause catches every rate-limit error first. The code then raises LLMError where it should raise LLMTransientError, and a retry loop that only retries transient errors would never retry. A test would give the adapter a fake SDK whose create raises openai.RateLimitError and assert that pytest.raises(LLMTransientError) passes. With the wrong order the assertion fails.