Sub topic 6
Deterministic checks for format, schema, and constraints
This chapter assumes you can write basic Python, have called an LLM through an SDK, and have built the small evaluation harness from the previous chapter. It also assumes you know the mean and proportion of a set of scores.
Why deterministic checks come first
A deterministic check is a function that gives the same verdict every time for the same output. It uses code, not a model or a person, to decide pass or fail. Typical targets are:
- Format: the output is valid JSON, has no markdown fences, or fits a length limit.
- Schema: required fields exist and have the right types and allowed values.
- Constraints: the output contains or avoids certain strings, stays under a word count, or cites only allowed sources.
These checks are cheap, fast, and exact. They never disagree with themselves, so a change in score always comes from a change in the application. Run them before any LLM judge or human review. If the output is not valid JSON, there is no reason to pay a judge to rate its content.
Deterministic checks have a limit. They verify structure, not meaning. A reply with {"sentiment": "positive"} passes a schema check even when the review was negative. Treat these checks as a gate that catches a defined class of failures, and add other scorers for correctness.
Designing a check
A good check returns more than a boolean. It returns a pass flag and a short reason code. Reason codes let you count failure types later, which feeds error analysis.
from dataclasses import dataclass
@dataclass
class CheckResult:
passed: bool
reason: str = "ok"Keep each check small and single-purpose. One function per rule makes failures easy to name and lets you reuse rules across tasks.
Checking that output parses
Models often wrap JSON in prose or markdown fences. Decide up front whether that counts as a failure. If your production code strips fences before parsing, the evaluation should strip them too. If production code calls json.loads directly, the evaluation must not be more forgiving than production.
import json
def check_parses(output: str) -> CheckResult:
try:
json.loads(output)
except json.JSONDecodeError:
return CheckResult(False, "invalid_json")
return CheckResult(True)A common error is to measure with a lenient parser and then ship with a strict one. The eval then reports a pass rate your users never see.
Checking a schema
A schema states which fields must exist, their types, and their allowed values. You can hand-write the checks, or use a library such as jsonschema or Pydantic. The example below uses jsonschema, which you can install with pip install jsonschema.
import json
from jsonschema import Draft202012Validator
TICKET_SCHEMA = {
"type": "object",
"properties": {
"category": {"enum": ["billing", "bug", "feature", "other"]},
"priority": {"type": "integer", "minimum": 1, "maximum": 4},
"summary": {"type": "string", "minLength": 1, "maxLength": 120},
},
"required": ["category", "priority", "summary"],
"additionalProperties": False,
}
validator = Draft202012Validator(TICKET_SCHEMA)
def check_schema(output: str) -> CheckResult:
try:
data = json.loads(output)
except json.JSONDecodeError:
return CheckResult(False, "invalid_json")
errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
if errors:
first = errors[0]
path = ".".join(str(p) for p in first.path) or "root"
return CheckResult(False, f"schema:{path}:{first.validator}")
return CheckResult(True)Three details matter here.
additionalProperties: Falserejects extra fields. Without it, a model that invents aconfidencefield still passes.- In Python,
Trueis an instance ofint, butjsonschematreats JSON booleans as distinct from integers, so"priority": truefails theintegertype as it should. Hand-writtenisinstance(x, int)checks do not make this distinction and will acceptTrue. - The reason string includes the field path and the failed keyword, such as
schema:priority:maximum. That is specific enough to count.
Checking constraints
Constraints are rules that the schema cannot express, or that apply to free text. Examples are banned phrases, required disclaimers, length limits, and consistency between fields.
import re
BANNED = [r"\bas an ai\b", r"\bi cannot\b"]
def check_length(text: str, max_words: int = 80) -> CheckResult:
if len(text.split()) > max_words:
return CheckResult(False, "too_long")
return CheckResult(True)
def check_banned_phrases(text: str) -> CheckResult:
for pattern in BANNED:
if re.search(pattern, text, flags=re.IGNORECASE):
return CheckResult(False, f"banned:{pattern}")
return CheckResult(True)
def check_citations(text: str, allowed_ids: set[str]) -> CheckResult:
cited = set(re.findall(r"\[(doc-\d+)\]", text))
if not cited:
return CheckResult(False, "no_citation")
if not cited <= allowed_ids:
return CheckResult(False, "unknown_citation")
return CheckResult(True)check_citations is useful in retrieval-augmented systems. It cannot show that a citation supports the claim, but it does catch fabricated source IDs, which is a common failure.
Cross-field consistency
Some rules involve several fields. For example, a refund response with "action": "refund" must also have a positive amount.
def check_refund_consistency(data: dict) -> CheckResult:
if data.get("action") == "refund":
amount = data.get("amount")
if not isinstance(amount, (int, float)) or isinstance(amount, bool) or amount <= 0:
return CheckResult(False, "refund_without_amount")
return CheckResult(True)Here the bool test is needed because Python treats True as the number 1.
Combining checks in the harness
Compose checks into one scorer that stops at the first failure. This matches the gate diagram above and gives each case a single reason.
def run_checks(output: str, checks) -> CheckResult:
for check in checks:
result = check(output)
if not result.passed:
return result
return CheckResult(True)
def make_scorer(checks):
def scorer(output: str, expected) -> bool:
return run_checks(output, checks).passed
return scorerThis scorer has the same signature as the one used by run_eval in the earlier chapter, so it plugs in with no change. The expected argument is unused because these checks do not compare against a reference. If you want reason codes in the results, extend the harness so each result stores run_checks(...).reason next to passed.
Then summarize failures by reason:
from collections import Counter
def failure_breakdown(outputs, checks):
counts = Counter()
for out in outputs:
result = run_checks(out, checks)
if not result.passed:
counts[result.reason] += 1
return countsA breakdown such as {"invalid_json": 14, "schema:priority:maximum": 3} tells you where to work. A single pass rate does not.
Common errors
| Error | Effect | Fix |
|---|---|---|
| Eval parser is more lenient than production | Pass rate is inflated | Share the parsing code between eval and production |
| Regex checks without tests | False passes or false failures | Write unit tests with known good and bad strings |
| Checking only the happy path | Edge cases such as empty output go unseen | Include empty, very long, and non-English cases in the dataset |
| Treating a pass as correctness | Wrong but well-formed answers score 100% | Pair checks with a content scorer |
| Overly strict string rules | Valid paraphrases fail | Check for required facts or fields, not exact wording |
| Substring matching on negation | "not refundable" matches a check for "refundable" | Check structured fields, not prose, where you can |
Test your checks
A check is code, and it can be wrong. Keep a small table of strings that must pass and strings that must fail, and run it as a normal unit test.
def test_check_parses():
assert check_parses('{"a": 1}').passed
assert not check_parses("Here is the JSON: {}").passed
assert not check_parses("").passedAn empty string, a string with only whitespace, and a truncated JSON object are the cases most often forgotten.
When to prefer structured output features
Many APIs can constrain generation to a schema, which makes parse and schema failures rare. This does not remove the need for these checks. Constrained decoding guarantees shape, not truth, and it can still produce wrong values, empty strings, or refusals in a field. Keep the checks as a safety net, and track the rate of violations over time. A rising rate after a model or prompt change is an early warning.
Exercises
Exercise
A model returns {"category": "bug", "priority": "2", "summary": "Crash on save"} for the ticket schema above. Does check_schema pass it, and what reason code does it return?
Show answer
It fails. The priority field is the string "2", but the schema requires an integer. The reason code is schema:priority:type.
Exercise
Your eval reports 98% valid JSON, but users report many parse errors in production. Name one likely cause and one fix.
Show answer
A likely cause is that the eval strips markdown fences or extracts JSON from prose, while production calls json.loads directly. The fix is to use the same parsing function in both places, so the eval measures what production sees.
Exercise
Write a check that fails when a response contains more than three sentences, using only the standard library. State one weakness of your approach.
Show answer
One answer is def check_sentences(text): n = len([s for s in re.split(r"[.!?]+", text) if s.strip()]); return CheckResult(n <= 3, "ok" if n <= 3 else "too_many_sentences"). A weakness is that splitting on punctuation miscounts abbreviations such as "Dr." and decimals such as "3.5", so the check needs tests for those cases.