Sub topic 6
Deterministic checks for format, schema, and constraints
This chapter assumes you can write basic Python, have called an LLM through an API, and have read the earlier chapters on the evaluation harness and reference-based metrics. Deterministic checks are plain code that inspects an output and returns pass or fail. They are cheap and repeatable, and they give the same verdict every time you run them.
Why run them first
Many failures are mechanical. The model wraps JSON in prose, drops a required field, or exceeds a length limit. A judge model or a human should not spend effort on these. A deterministic check catches them for free and tells you exactly which rule broke.
Three layers of checks
- Format. Can the output be parsed at all? For JSON, call
json.loads. - Schema. Does the parsed value have the right fields and types?
- Constraints. Do the values obey task rules, such as length limits, allowed values, or banned phrases?
A worked example
Suppose an application extracts a support ticket from an email and must return JSON with a category, a priority from 1 to 5, and a summary of at most 120 characters. The checker below returns a list of reasons rather than a bare boolean, so you can count failures by type.
import json
ALLOWED_CATEGORIES = {"billing", "bug", "feature", "other"}
def check_ticket(output: str) -> list[str]:
"""Return a list of failure reasons. An empty list means pass."""
try:
data = json.loads(output)
except json.JSONDecodeError:
return ["not_valid_json"]
if not isinstance(data, dict):
return ["not_an_object"]
failures = []
for field in ("category", "priority", "summary"):
if field not in data:
failures.append(f"missing_{field}")
if failures:
return failures
if data["category"] not in ALLOWED_CATEGORIES:
failures.append("bad_category")
priority = data["priority"]
# bool is a subclass of int in Python, so exclude it explicitly.
if isinstance(priority, bool) or not isinstance(priority, int):
failures.append("priority_not_int")
elif not 1 <= priority <= 5:
failures.append("priority_out_of_range")
if not isinstance(data["summary"], str):
failures.append("summary_not_str")
elif len(data["summary"]) > 120:
failures.append("summary_too_long")
return failures
samples = [
'{"category": "bug", "priority": 2, "summary": "App crashes on login"}',
'Here is the JSON: {"category": "bug"}',
'{"category": "refund", "priority": 9, "summary": "Wants money back"}',
]
for s in samples:
print(check_ticket(s))
# []
# ['not_valid_json']
# ['bad_category', 'priority_out_of_range']To plug this into the harness from earlier, wrap it as a scorer: lambda output, expected: check_ticket(output) == []. Keep the full reason list in the per-case results so error analysis can group failures by type.
Common errors
- Checking only that it parses. Valid JSON with the wrong fields still breaks downstream code.
- Type traps. In Python,
Truepasses anisinstance(x, int)test, and"3"is a string, not a number. Decide whether your application accepts either. - Fragile string rules. A banned-word check that matches substrings will flag "class" for containing "ass". Use word boundaries in regular expressions.
- Treating a pass as quality. A well-formed answer can still be wrong. These checks establish a floor, not correctness.
Exercise
A model returns {"category": "bug", "priority": true, "summary": "Crash"}. Why does a check using only isinstance(priority, int) accept it, and how does the example above avoid this?
Show answer
In Python, bool is a subclass of int, so True passes the isinstance test. The example rejects it by testing isinstance(priority, bool) first and reporting priority_not_int.
Exercise
Why does check_ticket return a list of reason strings instead of True or False?
Show answer
Reasons let you count failures by type across the dataset, such as how many outputs had invalid JSON versus a bad category. That shows which problem to fix first.