Sub topic 8
Match requests to recordings
This chapter assumes you can write pytest tests, you know the ChatClient seam from earlier chapters, and you have seen the basic RecordingClient that saves replies to a JSON file. Here you decide what counts as "the same request" when a replay looks up a saved reply.
What matching means
A recording is a set of request and reply pairs. During replay, your code sends a request and the replay layer must pick the saved reply that belongs to it. Matching is the rule that makes that choice.
The rule can be wrong in two ways:
- Too loose. Different requests match the same recording. A test passes even though your code now sends a different prompt, so the test no longer checks anything.
- Too strict. Requests that are equivalent for your purposes fail to match. Tests break on a changed timestamp or a reordered JSON key, and people start re-recording out of habit.
Good matching sits between the two. It compares every part of the request that changes what the model would answer, and nothing else.
Decide what is part of the request
The first RecordingClient hashed only the prompt string. That works while the prompt is the only input. A real call has more inputs that change the reply:
- the model name
- sampling settings such as temperature and maximum output tokens
- the system prompt
- tool definitions, if you pass any
- response format settings, such as a JSON schema
If two of these differ but the key ignores them, a recording made with one model can be replayed for another. Your test then claims to cover code that it never exercised.
A simple fix is to build the key from a dictionary of everything that matters and serialize it in canonical form. Canonical form means the same data always produces the same bytes. Sorted keys and fixed separators give you that.
import hashlib
import json
def request_key(prompt: str, *, model: str, temperature: float = 0.0) -> str:
payload = {"prompt": prompt, "model": model, "temperature": temperature}
canonical = json.dumps(
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()Without sort_keys=True, two dictionaries with the same contents can serialize differently and produce different hashes. This is a common source of misses that look random.
Normalize volatile parts
Some request content changes on every run without changing the meaning of the request. Typical examples are the current time, a generated request ID, and a temporary file path. If these appear in the prompt, a strict key will never match twice.
You have two options:
- Make the input deterministic. Pass a fixed clock or a seeded ID generator into the code under test. This is the better option because the prompt your test sends is the prompt that was recorded.
- Normalize before keying. Replace volatile text with a placeholder before you compute the key. Use this when you cannot control the source, for example with a library that stamps the prompt itself.
import re
TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")
REQUEST_ID = re.compile(r"req_[0-9a-f]{8,}")
def normalize(prompt: str) -> str:
prompt = TIMESTAMP.sub("<TIMESTAMP>", prompt)
return REQUEST_ID.sub("<REQUEST_ID>", prompt)Keep normalization narrow. Each pattern you add is a place where a real change in the prompt could be hidden. A pattern like \d+ would erase the invoice totals your test is supposed to check.
A matching recorder that explains misses
A miss in replay mode is a test failure, and the message should help you fix it. The most useful message shows what was sent and the closest recorded prompt, so you can see the difference. This version also stores the normalized request next to each reply. That makes the recording file readable in code review.
import difflib
import json
import os
class MatchingRecordingClient:
"""Replays saved replies keyed by the full request.
Calls the real client only when one is supplied and the request is new.
"""
def __init__(self, path, model, real_client=None):
self.path = path
self.model = model
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:
normalized = normalize(prompt)
key = request_key(normalized, model=self.model)
if key in self.entries:
return self.entries[key]["reply"]
if self.real_client is None:
recorded = [e["request"]["prompt"] for e in self.entries.values()]
close = difflib.get_close_matches(normalized, recorded, n=1, cutoff=0.0)
hint = (
f"Closest recorded prompt:\n{close[0]}"
if close
else "The recording file is empty."
)
raise LookupError(
f"No recording for this request.\nSent:\n{normalized}\n{hint}"
)
reply = self.real_client.complete(prompt)
self.entries[key] = {
"request": {"model": self.model, "prompt": normalized},
"reply": reply,
}
with open(self.path, "w", encoding="utf-8") as f:
json.dump(self.entries, f, indent=2, sort_keys=True)
return replyThe next test records once with a stand-in for the real client, then replays with a prompt that differs only in its timestamp.
def test_timestamp_difference_still_matches(tmp_path):
path = tmp_path / "recording.json"
class Real:
def complete(self, prompt):
return '{"total": 1}'
MatchingRecordingClient(path, "m", Real()).complete("At 2026-01-01T00:00:00Z total?")
replay = MatchingRecordingClient(path, "m")
assert replay.complete("At 2027-05-05T10:00:00Z total?") == '{"total": 1}'
def test_changed_wording_is_a_miss(tmp_path):
import pytest
path = tmp_path / "recording.json"
class Real:
def complete(self, prompt):
return "ok"
MatchingRecordingClient(path, "m", Real()).complete("Summarize this.")
replay = MatchingRecordingClient(path, "m")
with pytest.raises(LookupError, match="Closest recorded prompt"):
replay.complete("Summarise this.")The second test is the behavior you want. A one-letter change in the prompt is a real change in what you send, so the replay fails loudly and shows the nearest recording.
The matching flow
Matching with vcrpy
The vcrpy library records HTTP traffic instead of client calls, so it matches HTTP requests. You choose which parts of the request must be equal with match_on. The available parts include method, scheme, host, port, path, query, uri, body, headers, and raw_body.
The default list is method, scheme, host, port, path, and query. It does not include the body. Every LLM call goes to the same endpoint with a POST, so under the default rule all your prompts match the first recording. This is the most common vcrpy mistake in LLM tests. Always add body.
Matching on the raw body has its own problem. Two JSON bodies with the same content but a different key order are not byte-equal. If your SDK or its version changes the order, every cassette misses. A custom matcher can compare the parsed JSON instead.
import json
import vcr
def json_body_matcher(r1, r2):
assert json.loads(r1.body) == json.loads(r2.body), "request bodies differ"
my_vcr = vcr.VCR(
cassette_library_dir="tests/cassettes",
record_mode="none",
filter_headers=["authorization", "x-api-key"],
match_on=["method", "uri", "json_body"],
)
my_vcr.register_matcher("json_body", json_body_matcher)A matcher takes two requests. It passes if it returns normally and fails if it raises AssertionError. The message you give the assertion appears in the output when a request does not match, which makes mismatches easier to diagnose. You can use the same technique to ignore a field. Delete the volatile key from both parsed bodies before comparing them.
Choosing how strict to be
| Matching rule | Catches | Misses or breaks on | Use when |
|---|---|---|---|
| Prompt text only | Prompt changes | Model or setting changes | A throwaway prototype |
| Prompt, model, settings | Any input change you control | Volatile text in the prompt | Most client-level recordings |
| Normalized prompt, model, settings | Real changes, ignoring noise | Over-broad normalization hiding real changes | Prompts with timestamps or IDs you cannot control |
| HTTP method and URI only | Endpoint changes | Prompt changes (the test checks nothing about the prompt) | Almost never for LLM calls |
| HTTP body, parsed as JSON | Any payload change | SDK upgrades that add or rename fields | HTTP-level recordings |
Gotchas
- Repeated identical requests. If your code makes the same request twice and expects different replies, such as a retry, a key-based lookup returns the same reply both times. Use a scripted fake for that case. The retry test from the previous chapter needs a bad reply and then a good one, and a recording cannot express that.
- Sampling settings. If temperature is above zero, the recorded reply is one sample from many possible replies. Replay makes the test deterministic, but it does not tell you the code handles other samples. Keep replayed tests at the settings you record with.
- SDK upgrades. An SDK that adds a default field to the request body changes the body match without any change in your code. A body-based miss right after a dependency update points to this cause.
- Order of matching. In some replay tools, each recording can be used only once unless you allow repeats. Check your tool's setting if a second identical call fails after the first succeeds.
- Wrong fix for a miss. When a replay misses, first read the diff. Re-record only if the new request is correct. Re-recording to silence a miss caused by an accidental prompt change hides the bug the test found.
Exercise
Your vcrpy tests use match_on=["method", "uri"] and record_mode="none". You rewrite the prompt in your code, and all tests still pass. Why, and what is the smallest fix?
Show answer
Every LLM call is a POST to the same URI, so the method and URI match the recorded request no matter what the prompt says. The replay returns the old reply and never compares the new prompt. Add body to match_on, or use a JSON body matcher so key order does not cause misses. After that change the tests fail until you re-record with the new prompt, which is the correct result.
Exercise
A prompt contains a line such as Generated at 2026-03-04T09:15:00Z. Replay misses on every run. Name two ways to fix this and say which you prefer.
Show answer
Either inject a fixed clock so the code always writes the same timestamp, or normalize the timestamp to a placeholder before computing the key. Prefer the fixed clock, because then the recorded prompt is exactly the prompt the code sends and nothing is hidden by a regular expression. Use normalization only when you cannot control the source of the timestamp.