Sub topic 5
Handling nondeterministic output
This chapter assumes you can write pytest tests, call an LLM API, and read a basic GitHub Actions workflow. It also assumes you have a golden dataset and deterministic checks from the earlier chapters.
The same prompt can produce different text on each call. A test that passes on one run and fails on the next is flaky. A flaky suite trains people to ignore red builds, so the suite must separate random variation from real regressions.
Where the variation comes from
Output varies for several reasons:
- Sampling. With a temperature above 0, the model picks among likely next tokens at random.
- Infrastructure. Even at temperature 0, many hosted models can return slightly different text because of batching and floating-point differences.
- Silent model updates. An alias such as
latestcan point to new weights. The next chapters cover pinning. - Prompt context. Retrieved documents or timestamps that change between runs also change the output.
You cannot remove all of this, so you reduce it where you can and measure the rest.
Step 1: Reduce the variation you control
Set temperature=0 for tests when your provider allows it. Pass a seed if the API supports one. Freeze dynamic inputs such as the current date and retrieved documents inside each case. Treat these settings as best effort, not as a guarantee of identical output.
Step 2: Assert on properties, not exact text
Exact string equality fails on harmless rephrasing. Check properties that any good answer must have: valid JSON, required keys, required phrases, a length limit, or a forbidden phrase. The deterministic checks from the previous chapter already work this way. Avoid snapshot tests of full model output unless the output is truly constrained, such as a single label.
Step 3: Repeat runs and measure a pass rate
For a case that is still unstable, run it several times and count passes. This gives a pass rate per case instead of a single pass or fail.
import json
from app.llm import run_prompt # your own wrapper around the model call
def check_output(case, output):
try:
data = json.loads(output)
except json.JSONDecodeError:
return False
if not set(case["required_keys"]) <= set(data):
return False
return all(p.lower() in output.lower() for p in case.get("must_contain", []))
def run_case(case, n=5):
results = [check_output(case, run_prompt(case["input"])) for _ in range(n)]
return sum(results) / nWith n=5, a case that passes 4 of 5 times scores 0.8. Choose n by cost. Three to five runs is common for unstable cases. Cases that are stable at temperature 0 need only one run.
Step 4: Decide per case with a majority rule
Once you have a rate per case, choose how a case counts toward the suite:
| Rule | A case passes when | Use it for |
|---|---|---|
| All runs pass | Every run passes | Safety and format rules that must never fail |
| Majority | More than half of runs pass | Quality checks with natural variance |
| Rate recorded | The rate feeds the suite score | Tracking trends against a baseline |
A strict rule for a hard requirement keeps a flaky pass from hiding a real safety failure. A looser rule for quality checks stops one unlucky sample from failing the build.
def case_passes(rate, rule="majority"):
if rule == "all":
return rate == 1.0
return rate > 0.5How the pieces fit
Common errors
- Retrying until green. Rerunning a failed test until it passes hides real regressions. Fix the run count in advance and report every run.
- Too few runs. With one run per case, a 70% reliable case passes most of the time. A drop to 40% can go unnoticed.
- Tolerance that is too wide. If the allowed drop is larger than the real change you care about, the gate never fires. The next chapter shows how to size it.
- Mixing hard and soft rules. Applying a majority rule to a safety check lets a failing case pass. Mark each case with its rule in the dataset.
- Ignoring cost. Repeated runs multiply API calls, so apply them only to the cases that need them.
Exercise
A formatting case passes 3 of 5 runs after you edit a prompt. Before the edit, it passed 5 of 5 runs. The case is marked as a hard requirement (valid JSON). Does it pass under the "all runs pass" rule, and what should you do?
Show answer
It fails, because 3 of 5 is not every run. The case went from 100% to 60%, so treat it as a regression caused by the prompt edit. Look at the two failing outputs, fix the prompt so that the JSON is always valid, and rerun the case. Do not widen the rule to majority just to make the build pass.
Exercise
Why is temperature=0 alone not enough to make a test suite deterministic?
Show answer
Hosted models can still return slightly different text at temperature 0, because of batching and floating-point differences. The model alias can also change underneath you. Tests should therefore check properties of the output and use repeated runs for unstable cases.