Sub topic 4
Deterministic checks: format, content, and constraints
This chapter assumes you can write pytest tests and that you have a JSONL golden dataset like the one from the previous chapter. Each case has an id, an input, and fields that describe what a good output looks like.
Why start with deterministic checks
A deterministic check is a plain code assertion on the model's output. The same output always gets the same verdict. These checks cost nothing to run beyond the model call itself. They also never disagree with themselves, and a failure message tells you exactly what broke.
Use them first. Add a judge model only for qualities that code cannot measure, such as tone or factual faithfulness.
The checks fall into three groups:
| Group | Question | Examples |
|---|---|---|
| Format | Can downstream code parse it? | Valid JSON, required keys, correct types |
| Content | Does it say what it must? | Required phrases, forbidden phrases |
| Constraints | Does it respect limits? | Length caps, no leaked secrets, allowed values |
Order the checks as a gate
Run format checks before content checks. If the output is not valid JSON, checking for phrases is pointless and produces noisy secondary failures.
Describe the checks in the dataset
Keep the rules in the data, not in the test code. A new case then needs no new Python. Here is one line of evals/cases.jsonl, wrapped for reading:
{"id": "refund-001", "input": "Customer asks for a refund after 45 days.", "required_keys": ["summary", "action"], "must_contain": ["30 days"], "must_not_contain": ["guarantee"], "max_chars": 300, "forbidden_patterns": ["\\b\\d{3}-\\d{2}-\\d{4}\\b"], "allowed_actions": ["deny", "escalate"]}In the real file, each case sits on a single line.
Write the checker
This function returns a list of failure messages. An empty list means the case passed. Returning messages, rather than failing on the first assert, lets you report every problem in one run.
import json
import re
def check_output(output: str, case: dict) -> list[str]:
# Format: must be a JSON object.
try:
data = json.loads(output)
except json.JSONDecodeError as exc:
return [f"invalid JSON: {exc}"]
if not isinstance(data, dict):
return ["top level is not a JSON object"]
failures = []
missing = set(case.get("required_keys", [])) - set(data)
if missing:
failures.append(f"missing keys: {sorted(missing)}")
# Content: required and forbidden phrases, case-insensitive.
lowered = output.lower()
for phrase in case.get("must_contain", []):
if phrase.lower() not in lowered:
failures.append(f"missing phrase: {phrase!r}")
for phrase in case.get("must_not_contain", []):
if phrase.lower() in lowered:
failures.append(f"forbidden phrase: {phrase!r}")
# Constraints: length, patterns, allowed values.
max_chars = case.get("max_chars")
summary = data.get("summary", "")
if max_chars and isinstance(summary, str) and len(summary) > max_chars:
failures.append(f"summary is {len(summary)} chars, limit {max_chars}")
for pattern in case.get("forbidden_patterns", []):
if re.search(pattern, output):
failures.append(f"matched forbidden pattern: {pattern}")
allowed = case.get("allowed_actions")
if allowed and data.get("action") not in allowed:
failures.append(f"action {data.get('action')!r} not in {allowed}")
return failuresThen connect it to pytest, as in the earlier parametrized test:
import json
from pathlib import Path
import pytest
from app.llm import run_prompt # your own wrapper around the model call
from evals.checks import check_output
CASES = [
json.loads(line)
for line in Path("evals/cases.jsonl").read_text(encoding="utf-8").splitlines()
if line.strip()
]
@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
def test_case(case):
failures = check_output(run_prompt(case["input"]), case)
assert not failures, "; ".join(failures)Common errors
- Brittle exact matches. Asserting
output == "Refund denied."fails when the model adds a comma. Check for key facts or allowed values instead. - Over-strict phrase lists.
must_contain: ["30 days"]fails on "thirty days". Use a regex such as30|thirtywhen several wordings are valid. - Checking only the happy path. Include adversarial cases that try to extract forbidden content. Constraint checks only prove something when the input pushes against them.
- Parsing fenced output. Models sometimes wrap JSON in a Markdown fence. Decide whether that counts as a failure. If your production parser cannot handle it, the test should fail too.
- Substring false positives.
"guarantee"also matches "guaranteed". That is usually intended, but use word boundaries when it is not.
Exercise
A case requires the output to contain "30 days", but after a model upgrade the output says "thirty days" and the test fails. The answer is still correct. Name two ways to fix the check, and say which you prefer.
Show answer
Either replace the phrase with a regex that accepts both wordings, such as 30 days|thirty days, or move the fact into a structured field (for example "window_days": 30) and assert on the value. The structured field is better, because it removes wording from the check and ties the assertion to the data your application uses.
Exercise
Why does check_output return a list of messages instead of raising on the first failed assertion?
Show answer
One run can then report every broken rule for a case, such as a missing key and an over-long summary together. Fixing all problems in a single pass is faster than finding them one at a time.