Sub topic 7
Record real responses and replay them offline
This chapter assumes you can write pytest tests and have read the earlier chapters on the client seam and the scripted fake. You should know that application code receives a ChatClient object with a complete(prompt) method.
Why record at all
A scripted fake is something you write by hand. You decide what the model "says", so the fake can only be as realistic as your guess. A recording is different. You call the real model once, save what it returned, and replay that reply in every later test run. The test stays offline, free, and deterministic, but the reply has the shape and quirks of real output.
Recording is useful when the reply is long or messy, such as a summary, a nested JSON document, or a reply with unexpected whitespace. Writing that by hand is tedious and easy to get wrong.
A minimal record and replay client
This client sits behind the same seam as your fake. It stores each reply under a SHA-256 hash of the prompt.
import hashlib
import json
import os
class RecordingClient:
"""Replays saved replies; calls the real client only for prompts not yet recorded."""
def __init__(self, path, real_client=None):
self.path = path
self.real_client = real_client
self.entries = {}
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
self.entries = json.load(f)
def complete(self, prompt: str) -> str:
key = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
if key not in self.entries:
if self.real_client is None:
raise LookupError(
"No recorded reply for this prompt. Re-record with a real client."
)
self.entries[key] = self.real_client.complete(prompt)
with open(self.path, "w", encoding="utf-8") as f:
json.dump(self.entries, f, indent=2, sort_keys=True)
return self.entries[key]Two design choices matter here:
- Replay is the default. Without a
real_client, the class never touches the network. A missing recording is an error, not a silent live call. - The key is the prompt. If you edit your prompt template, the hash changes and the test fails loudly. You then re-record on purpose, instead of reusing a reply that answered a different question.
Using it in a test
In a normal test run, pass only the path. To record, pass a real client once and commit the resulting file.
def test_extract_total_from_recording(tmp_path):
path = tmp_path / "replies.json"
class OneShot:
def complete(self, prompt: str) -> str:
return '{"total": 42.5}'
# Record: the "real" client is called and its reply is saved.
recorder = RecordingClient(str(path), real_client=OneShot())
assert extract_total(recorder, "Total: $42.50") == 42.5
# Replay: no real client, so any network call would raise.
replayer = RecordingClient(str(path))
assert extract_total(replayer, "Total: $42.50") == 42.5In a real project, the recording file lives in your repository, for example tests/recordings/invoice.json. The OneShot stand-in above is replaced by your SDK wrapper during a manual record session.
Recording at the HTTP level with vcrpy
If your code calls the vendor SDK directly, with no seam, you can record HTTP traffic instead. The vcrpy library stores each request and response in a file called a cassette.
import vcr
my_vcr = vcr.VCR(
cassette_library_dir="tests/cassettes",
record_mode="none",
filter_headers=["authorization", "x-api-key"],
match_on=["method", "uri", "body"],
)
@my_vcr.use_cassette("summarize.yaml")
def test_summarize_replays_recorded_http():
... # call code that uses the real SDK; HTTP traffic is replayed from the cassetteThree settings do the work:
record_mode="none"forbids new network calls, so a missing cassette entry fails the test.filter_headersremoves credentials before they are written to disk.match_onlists which parts of a request must equal the recording.
Common errors
- A live call slips into CI. Use
record_mode="none", or leave outreal_client, in the default test configuration. Record only in a separate, manual step. - Matching on the whole body is too strict. A timestamp or request ID inside the prompt changes the key on every run. Remove such values from the prompt, or match on fewer fields.
- Treating a recording as truth about the model. It shows what the model said once. It does not show what it will say tomorrow. Later chapters cover drift.
Exercise
You change one word in your prompt template and RecordingClient raises LookupError in the test suite. Is this a bug in the client? What should you do?
Show answer
No, it is the intended behavior. The prompt hash changed, so no saved reply matches. Re-record once with a real client, read the new reply and the file diff, and commit the updated recording.