Sub topic 1
Why Live LLM Calls Make Bad Unit Tests
A unit test that calls a live language model fails for reasons that have nothing to do with your code. This chapter explains those reasons one at a time. The rest of the tutorial builds the tools that replace the live call.
Prerequisites
This chapter assumes you can:
- Write and run unit tests with pytest or a similar framework.
- Read basic Python: classes, functions, and exceptions.
- Call an LLM API and parse a JSON reply.
- Pass a dependency into a function as an argument (dependency injection).
You don't need any testing library beyond pytest. The one runnable example below uses only the standard library.
What a unit test promises
A good unit test gives you four things:
- Determinism. The same code and the same input give the same result on every run.
- Speed. The test runs in milliseconds, so you run it after every edit.
- Isolation. It fails only when your code is wrong, not when the network or another team's service is wrong.
- Low cost. Running it 500 times a day costs nothing.
A live LLM call breaks all four. The sections below take them in turn.
Nondeterministic output
A language model produces text by sampling the next token from a probability distribution. Unless the sampling is forced to be greedy, two calls with the same prompt can return different text. Even when your prompt asks for JSON, the model might:
- Return
{"total": 42.5}one time and{"total": "42.50"}the next. - Wrap the JSON in a sentence such as "Here is the JSON you asked for:".
- Add a Markdown code fence around the object.
- Change key order or whitespace.
A test that asserts on the exact reply passes on some runs and fails on others. Nothing in your code changed. This is a flaky test: one whose result varies without any change to the code or the test.
Flaky tests do more damage than failing tests. A deterministic failure points at a bug. A flaky failure teaches the team to rerun the pipeline and ignore red builds. Once people do that, real failures get ignored too.
Seeing it happen
The script below simulates a model with a fixed list of plausible replies and picks one at random. It is a stand-in, so you can run it without an API key. It runs the same "test" 200 times.
import json
import random
class SimulatedModel:
"""Same prompt in, varying text out, like a live model."""
REPLIES = [
'{"total": 42.5}',
'{"total": 42.5}',
'{"total": "42.50"}',
'Here is the JSON: {"total": 42.5}',
'```json\n{"total": 42.5}\n```',
]
def complete(self, prompt: str) -> str:
return random.choice(self.REPLIES)
def extract_total(client, invoice_text: str) -> float:
reply = client.complete(
f"Return JSON with a 'total' field for this invoice:\n{invoice_text}"
)
return float(json.loads(reply)["total"])
def run_test_once(client) -> bool:
try:
return extract_total(client, "Total: $42.50") == 42.5
except (json.JSONDecodeError, KeyError, ValueError):
return False
if __name__ == "__main__":
client = SimulatedModel()
runs = 200
passed = sum(run_test_once(client) for _ in range(runs))
print(f"passed {passed} of {runs} runs")Run it several times. The count changes each time, and it never reaches 200. The function under test is the same on every run. Only the model's reply changes, and the model is not the thing you meant to test.
Why temperature 0 doesn't fix it
A common first response is to set temperature=0 and add a fixed seed where the API offers one. This lowers the variation but does not remove it, for three reasons:
- Not every API guarantees determinism. Some providers describe seeds as best-effort. Floating-point arithmetic on parallel hardware can produce tiny differences that flip a close token choice.
- The model behind the name changes. An alias such as a "latest" model name can point to new weights next month. Your pinned temperature is the same, but the model is not.
- Infrastructure changes. Provider-side batching, quantization, or routing changes can alter output without any version change you can see.
Low temperature is still worth using in production. It just can't be the thing your test suite depends on for correctness.
Latency
A live call takes from hundreds of milliseconds to tens of seconds, depending on the model, the prompt length, and the reply length. A fast unit test takes a few milliseconds. The gap matters at suite scale:
| Suite | Tests | Time per test | Total |
|---|---|---|---|
| Pure Python unit tests | 500 | 5 ms | 2.5 seconds |
| Same tests, each with a live call | 500 | 2 seconds | about 17 minutes |
At 17 minutes, developers stop running the suite before each commit. They run it only in CI, which moves feedback from seconds to a long wait. Running tests in parallel helps, but it runs straight into rate limits (see below).
Cost
Each live call costs money, billed per token. One call is cheap. A suite that runs on every push from every developer is not. Multiply the calls per run by the runs per day. Include the retries your code makes and the longer prompts you add over time. Your test bill grows as your prompts grow, even if the number of tests stays the same.
There is also a safety cost. A test suite that holds a real API key can leak it through logs, CI configuration, or pull requests from forks. A suite with no key to leak removes that risk.
Failures that aren't yours
A live test depends on a chain of systems you don't control: your network, DNS, the provider's API gateway, and the model servers. Any link can fail:
- Rate limits. The provider returns HTTP 429 when you send too many requests. A parallel test run triggers this easily.
- Outages and timeouts. A 500 or 503 response, or a hung connection, fails the test.
- Expired or missing credentials. A fork's CI job has no secrets, so every test fails.
- Quota exhaustion. The monthly budget runs out and every test starts failing at once.
In each case the test fails, but your code is correct. You can't tell this from a real bug without opening the log. This breaks the isolation promise: the test result no longer tells you about your code.
The reverse problem is quieter. Your code's error handling for these failures, such as backing off on 429 or giving up after a timeout, is the code you most need to test. A live call almost never produces those failures on demand. You can't write a reliable test for a rare event by waiting for it to happen.
Drift
Drift is a change in the model's behavior over time while your code stays the same. Providers retire model versions, update aliases, and adjust safety filters. A prompt that returned clean JSON in March might return prose in June.
Live unit tests can catch drift, but they catch it in the worst way. The failure shows up as a red build on an unrelated pull request, mixed in with random flakiness. Nobody can tell whether the cause is drift, a flake, or a real bug. Drift is real and worth detecting. It needs its own deliberate check, which a later chapter covers, and not the unit test suite.
Why retries and loose assertions don't rescue the test
Two fixes come up often, and both fail:
- Rerun failed tests automatically. This hides flakiness and multiplies cost and latency. It also hides real bugs that only show up some of the time, which are the hardest bugs to find.
- Loosen the assertion to something like
assert "42" in reply. A loose assertion passes for wrong answers too. A reply of "I can't find a total, but the invoice number is 42" passes. You have traded false failures for false passes, and false passes are worse because they give you confidence you haven't earned.
Neither fix restores the properties a unit test needs. The fix is to remove the live model from the test, not to tolerate it.
What to do instead
Your code has two kinds of behavior, and they need different tests:
- Your logic: building the prompt, parsing the reply, validating fields, retrying, handling errors. This is ordinary code. It should be tested deterministically and fast.
- The model's behavior: whether it answers well. This is not a unit-test question. It is checked separately with a small number of live tests and with evaluations, covered in the final chapter.
To test your logic, you give it a stand-in for the model. The next chapters build this in steps:
- Put a narrow interface (a seam) around the model client.
- Replace the real client with a scripted fake that returns canned replies.
- Inject errors and malformed output to test failure paths.
- Record real responses once and replay them offline.
Summary
- A unit test needs determinism, speed, isolation, and low cost. A live model call gives you none of them.
- Output varies between calls. Lowering the temperature reduces this but can't be relied on.
- Calls take seconds, cost money per token, and depend on the network, rate limits, credentials, and quotas.
- Model behavior drifts over time, and in a live suite drift looks like random failure.
- Retrying and loosening assertions hide the problem. Replacing the model call with a stand-in solves it.
Exercise
A teammate's test calls a live model, asserts "total" in reply, and is wrapped in a decorator that reruns it up to 3 times on failure. It is green on most builds. Name two problems this test still has, and say what you would change.
Show answer
Any two of these. (1) The assertion is loose, so a wrong reply that happens to contain the word "total" passes, which gives false confidence. (2) The reruns hide flakiness and can triple the latency and cost on bad runs. (3) The test still depends on the network, credentials, and rate limits, so it can fail for reasons unrelated to your code. (4) It never tests your error handling for 429 or malformed JSON, because those can't be produced on demand. The change: put the model client behind a narrow interface, pass in a scripted fake that returns a known reply, and assert on the exact parsed result. Keep at most a few live checks in a separate suite.
Exercise
Run the SimulatedModel script five times. The pass count differs between runs. Which of the four unit-test properties does that show is broken, and which property would you restore first by replacing SimulatedModel with an object that always returns '{"total": 42.5}'?
Show answer
The variation shows that determinism is broken. Replacing the model with an object that always returns the same string restores determinism first, and as a side effect restores speed, isolation, and zero cost. The pass count would then be 200 of 200 on every run, because the only remaining thing under test is your own parsing code.