Sub topic 8
Match requests to recordings
This chapter assumes you can write pytest tests, you have a client seam like the ChatClient protocol from earlier chapters, and you know what a recorded reply file is. Here you decide when a request counts as "the same" as a recorded one.
Why matching matters
A replay client receives a request and must pick a stored reply. The rule it uses to pick is the matching rule. Two failures are possible:
- Too strict. Anything that varies between runs, such as a timestamp, a random ID, or dict ordering, causes a miss. The test fails even though the code is correct.
- Too loose. Different requests map to the same reply. The test passes with a reply that was recorded for another prompt, so it no longer checks what you think it checks.
LLM traffic makes the loose failure easy to hit. Every call goes to the same HTTP method and URL, so only the body tells requests apart.
Exact matching with a hash
The RecordingClient from the previous chapter hashes the whole prompt with SHA-256. Any one-character change gives a different key, so a changed prompt fails loudly instead of reusing a stale reply. This is a good default because a miss tells you the prompt changed.
Normalize before you hash
If your prompt contains a value that changes every run, exact matching misses every time. Remove or fix that value before computing the key. Do not loosen the matcher.
import hashlib
import re
_TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")
def normalize(prompt: str) -> str:
prompt = _TIMESTAMP.sub("<TIMESTAMP>", prompt)
return "\n".join(line.rstrip() for line in prompt.strip().splitlines())
def prompt_key(prompt: str) -> str:
return hashlib.sha256(normalize(prompt).encode("utf-8")).hexdigest()
a = prompt_key("Summarize at 2026-11-28T06:37:17Z:\nhello ")
b = prompt_key("Summarize at 2027-01-02T10:00:00Z:\nhello")
c = prompt_key("Summarize at 2027-01-02T10:00:00Z:\ngoodbye")
assert a == b
assert a != cThe timestamp and trailing whitespace are ignored, but a change in the real content still produces a new key. Normalize only what you know is noise. Each rule you add makes the matcher looser.
A better fix is often to inject the clock into your code so the prompt is stable in tests. Normalization is for cases where you cannot change the prompt builder.
Matching HTTP recordings with vcrpy
With vcrpy, match_on lists the request parts that must equal the recording. The default is method, scheme, host, port, path, and query, which does not include the body. With an LLM API, the default can send every request the same reply. Add body.
Raw body comparison compares bytes, so two JSON bodies with the same content but different key order will not match. A custom matcher can compare parsed JSON instead:
import json
import vcr
def json_body(r1, r2):
assert json.loads(r1.body) == json.loads(r2.body)
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)A custom matcher passes when it returns without raising AssertionError. Register it before you use a cassette that names it in match_on.
Choosing a matching rule
| Rule | Misses when | Risk |
|---|---|---|
| Whole-prompt hash | Anything in the prompt changes | Too strict, but fails loudly |
| Normalized hash | Meaningful content changes | Low, if you normalize only noise |
| Method and URI only | Never | Wrong reply returned silently |
| Parsed JSON body | Content or parameters change | Low |
Include model name and parameters such as temperature in the match. The same prompt sent with a different model is a different request.
Handle misses on purpose
A miss means the request no longer matches what was recorded. Treat it as information. Look at what changed in the prompt. If the change is intended, re-record. If it is not, you found a bug in your prompt builder. Never fix a miss by loosening the matcher until the error stops.
Exercise
Your prompt builder adds the current time to every prompt, and your replay tests now fail with "No recorded reply for this prompt" on every run. Name two ways to fix it, and say which you prefer.
Show answer
Either normalize the timestamp out of the key (as in normalize), or inject a fixed clock into the prompt builder so the prompt is identical in tests. Injecting the clock is better because it keeps the matcher strict and removes the noise at its source.