Code-based graders & assertions

In one sentence

Grade LLM outputs with plain code wherever the answer is checkable: exact match, regex, schema validity, right tool and arguments, SQL results, unit tests. Cheap, instant and reproducible, so try them before any LLM judge.

Analogy: A spell-checker versus an editor: the checker can't judge the story, but it is instant, free and never disagrees with itself. Run it first, and pay the editor only for what it can't judge.

Cheap checks run first and short-circuit; only outputs that pass every deterministic gate are worth paying a judge for.

How it works

  • Typical checks: normalized match, regex, schema validation, right tool and arguments, latency and token budgets.
  • Execution grading runs generated SQL and compares result sets, or runs generated code against unit tests.
  • They run in pytest like any test, so they gate every commit in CI.
  • Their limit is nuance: tone, helpfulness and faithfulness still need an LLM judge or humans.
  • Decompose fuzzy criteria into checkable parts, like "cites a retrieved doc id", and leave only the residue to a judge.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your refund agent's eval passes whenever the tool arguments are valid JSON matching the Refund schema, and it scores 99%. Users report refunds for the wrong amount. What's missing?

Go deeper

Full explanation

A code-based grader is a deterministic function that takes the model's output (and maybe an expected value) and returns pass/fail. Same input, same verdict, in milliseconds, for free. Many failure modes that matter are checkable this way:

  • Exact or normalized match: labels, IDs, numbers; strip case, whitespace and punctuation first.
  • Regex / contains / not-contains: a required disclaimer, no leaked system prompt, no competitor names, a valid date format.
  • Schema validity: output parses as JSON and validates against a Pydantic or JSON Schema model, enums in range.
  • Tool use: the right tool was called with arguments that validate and match expected values; no forbidden tool.
  • Execution: generated SQL runs and its result set matches the reference query's; generated code passes unit tests (how HumanEval and SWE-bench grade).
  • Operational budgets: latency, tokens, cost per request, output length.

They run in pytest like any test, so they gate every commit (Evals in CI/CD & release gates). Their limit is nuance: tone, helpfulness and faithfulness need LLM-as-a-judge or humans. The Staff move is to decompose: turn a fuzzy criterion into checkable parts ("cites a doc id that was actually retrieved") and leave only the residue to a judge.

Code pytest graders: tool call, schema, latency and SQL execution
pythonpytest graders: tool call, schema, latency and SQL execution
import json, sqlite3, time
import pytest
from pydantic import BaseModel

class Refund(BaseModel):  # the contract the app actually parses
    order_id: str
    amount: float
    reason: str

CASES = [json.loads(l) for l in open("golden/refunds.jsonl")]
SQL_CASES = [json.loads(l) for l in open("golden/sql.jsonl")]

@pytest.mark.parametrize("case", CASES, ids=lambda c: c["id"])
def test_refund_turn(case):
    t0 = time.perf_counter()
    resp = run_agent(case["input"])                      # system under test
    assert time.perf_counter() - t0 < 5.0                # latency budget
    call = resp.tool_calls[0]
    assert call.name == "issue_refund"                   # right tool
    args = Refund.model_validate_json(call.arguments)    # raises if schema-invalid
    assert args.order_id == case["expected"]["order_id"]
    assert args.amount == pytest.approx(case["expected"]["amount"], abs=0.01)
    assert "system prompt" not in resp.text.lower()      # no leakage

@pytest.mark.parametrize("case", SQL_CASES, ids=lambda c: c["id"])
def test_sql_result_matches(case):
    db = sqlite3.connect("file:fixtures/shop.db?mode=ro", uri=True)  # fixed snapshot, read-only
    got = db.execute(generate_sql(case["question"])).fetchall()
    want = db.execute(case["reference_sql"]).fetchall()
    # Compare results, not SQL text: many correct queries look different.
    # Order-insensitive unless the question asks for ordering.
    assert got == want if case.get("ordered") else sorted(got) == sorted(want)
Real example

A text-to-SQL assistant for finance analysts had an LLM judge rating "is this SQL correct?" at 91%. The team switched to execution: run generated and reference SQL on a fixed database snapshot and compare result sets. Real accuracy was 74%. The judge had approved queries that looked right but used an INNER JOIN that dropped rows, or summed gross instead of net. The 300-case suite now runs in under a minute per commit at zero token cost, and the judge only grades the explanation text shown to users.

Trade-offs +3 · −3

+ You gain

  • Free and instant: run thousands of cases on every commit.
  • Reproducible: no grader variance, so any score change comes from the system.
  • Failures are unambiguous, easy to debug and easy to show in a PR.

− You pay

  • Blind to nuance: tone, helpfulness and faithfulness need a judge or a human.
  • Brittle when written naively: exact match fails on "Paris." versus "Paris".
  • Execution graders need sandboxes and fixture data that someone must maintain.

Use it when

First, for every criterion with a checkable answer: labels, extracted fields, structured output, tool calls, SQL, code, forbidden strings, latency and cost budgets. Use them as the CI gate and, where cheap, as runtime guardrails.

Avoid it when

Open-ended quality, like summaries, tone or whether an answer is grounded in its context, where any regex is a misleading proxy. Decompose what you can; judge the rest with an LLM judge or humans.

Numbers to know 4
  • HumanEval: 164 hand-written Python problems, graded by unit tests and reported as pass@k (Chen et al., 2021).
  • Unbiased pass@k from n samples with c correct: 1 − C(n−c, k) / C(n, k), averaged over problems.
  • SWE-bench: 2,294 real GitHub issues from 12 Python repos, graded by running each repo's own tests.
  • Cost gap: a code check is ~milliseconds and $0; a judge call is ~seconds plus tokens, on every case, every run.
Common pitfalls 4
  • Exact-matching free text: normalize case, whitespace and punctuation, or extract the field first.
  • Comparing SQL strings instead of executing them: many correct queries look different.
  • Asserting order on unordered results, or on tool calls the model may legitimately run in parallel.
  • Stopping at "valid JSON": schema-valid output can still carry wrong values.
Interview questions 2

Answer out loud first, then reveal.

When would you use a code-based grader instead of an LLM judge?Show answer

Whenever the criterion has a checkable answer, which is more often than people think. Classification, extracted fields, JSON validity, which tool was called with which arguments, SQL results, generated code passing tests, latency and cost: all code. They're free, instant and have zero grader variance, so a score change means the system changed. I reach for a judge only for nuance like tone or faithfulness, and even then I decompose first: "cites a retrieved doc id" is code; "the cited doc supports the claim" is the judge's residue.

How do you evaluate a text-to-SQL feature?Show answer

By execution, not by string match or a judge. I keep a fixed database snapshot and a golden set of questions with reference SQL. For each case I run both queries and compare result sets, order-insensitive unless the question asks for ordering, with a tolerance for floats. I also check the query is read-only, finishes under a timeout and touches only allowed tables. String match underrates correct alternatives; a judge overrates plausible-looking wrong joins. Execution gets both right and is cheap enough to run on every commit.