Method guide ยท 6 ways to check a model with code

How to validate LLM output with code, not another model

To validate LLM output deterministically, pass it through code that gives the same verdict every time: a grammar, a schema, a test run, a formal verifier, a symbolic critic or an answer checker. Each one catches one kind of error and misses another, so the useful question is which blind spot you can live with.

Every blind spot below is quoted from the Tools shelf or from a library card, which take it from the original sources.

Grammar-constrained decoding

Grammar-constrained decoding rules out every token that would break a grammar, a regex or a JSON schema, so the model can only write text of the right shape. The check runs while the text is produced, not after.

Tools

  • Outlines: Forces a model's output to match a type, regex, choice list or grammar, so the structure is valid by construction.
  • XGrammar: Fast constrained-decoding engine that keeps LLM output inside a JSON schema, regex or context-free grammar.
  • llama.cpp GBNF grammars: llama.cpp can restrict a local model's output to a formal grammar (GBNF), for example valid JSON or a chess move list.
  • Guidance: Python library that steers a model while it writes, using regex, choice lists and grammars to constrain each generated piece.
  • LMQL: A Python-based query language where you write where-constraints that the model's generated text must satisfy.

Library cards

  • PICARD: Constrained beam search that rejects invalid tokens at every decoding step using an incremental Haskell SQL parser and database schema type-checker.
  • Synchromesh: Pairs target-similarity retrieval with Constrained Semantic Decoding (CSD), using an incremental parser and type/scope engine to enforce valid code.

What it does not catch

  • Outlines: It guarantees the shape of the output (valid JSON, a regex match, one of the listed choices), not that the values inside are true or sensible.
  • PICARD: Enforces grammatical and schema well-formedness, but cannot prevent a semantically plausible query that filters on the wrong column value.

Schema validation and retry

Schema validation parses the finished output against a typed schema and sends the error back to the model when parsing fails. It catches wrong shapes after the fact, and each retry costs another model call.

Tools

  • Instructor: Gets typed, validated data out of an LLM using Pydantic models, and retries with the error message when validation fails.
  • Guardrails AI: Python framework that runs validators on LLM inputs and outputs and decides what to do when a check fails.

What it does not catch

  • Instructor: Passing validation shows the data fits the schema and your rules, not that it is true. Retries cost extra model calls and may still end in failure.
  • Guardrails AI: A validator only proves the one property it checks. Some hub validators (for example toxic-language checks) are themselves model-based, so they are not pure code judges.

Test gates and execution feedback

A test gate runs code against tests, keeps what passes and sends the failures back for repair, or picks among candidates by their test results. The tests decide, and the model's own opinion of its code does not count.

Tools

  • Aider: A terminal coding assistant that runs your linter and test command after each edit and asks the model to fix failures.
  • Agentless: Fixes software issues in three fixed steps (locate, repair, validate) and ranks candidate patches by test results.

Library cards

  • CodeT: Samples both candidate programs and synthetic test suites, then runs a RANSAC dual-execution consensus algorithm to select the best program.
  • Self-Debugging with Execution Feedback: Iterative program synthesis loop driven by unit-test execution traces, compiler diagnostics, and line-by-line rubber-duck code explanation.
  • EG-CFG: While the model writes a program line by line, beam search samples possible continuations, runs them on test cases, and feeds the execution results back into the prompt that steers the next tokens.
  • AlphaCode: Samples millions of candidate programs per competitive programming problem, filters by example tests, and clusters by synthetic input behavior.

What it does not catch

  • Self-Debugging with Execution Feedback: Correctness is bounded by the unit-test suite available during the debugging loop.
  • Aider: A clean lint and test run shows only that those checks pass. Behavior the tests do not cover is unchecked, and the tests are only as good as you made them.

Formal verification

A formal verifier checks code or a proof against a specification written in a formal language. A pass is exact for the statement it checks, and the model can propose anything because only what verifies is kept.

Tools

  • Lean REPL: A JSON read-eval-print loop for Lean 4 that returns errors, unfinished-proof markers and proof states for any input.
  • Kimina Lean Server: A server that checks Lean 4 code and proofs at scale, so a model's output gets a pass or fail from Lean.
  • LeanDojo: Python library that lets a program or model try proof steps in Lean and read back the new proof state or the error.

Library cards

  • AutoVerus: LLM agents write the proof annotations Verus needs to prove Rust code correct, and Verus's error messages drive the repair rounds.
  • AlphaVerus: A model translates programs into Verus, tree search repairs them with verifier feedback, and a filter keeps trustworthy results as examples.
  • Clover (Closed-Loop Verifiable Code Generation): Checks mutual consistency between code, docstrings, and formal Dafny specifications using SMT equivalence and deductive verification.
  • DafnyBench Verifier Repair: Iterative synthesis of loop invariants and helper assertions in Dafny guided by Dafny verifier error messages.
  • Baldur: Generates whole-function Isabelle/HOL proofs and uses the prover error message to repair broken proofs.

What it does not catch

  • Lean REPL: It reports what Lean accepts, not whether the theorem is the one you wanted. A proof containing sorry is flagged but not rejected as a command. The README gives lake exe repl as the run command, after building the repo.
  • AutoVerus: Verus-Bench is a 150-task suite the authors built from existing code and verification benchmarks, and the task gives the code and the specification. The tool proves what the spec says; a wrong spec would still pass.

Symbolic critics and planners

A symbolic critic tests a proposed plan against explicit constraints and returns the violations to the model. A classical planner can also finish the job once the model has put the problem into a formal language.

Library cards

  • LLM-Modulo Framework: An LLM proposes candidate plans inside a generate-test-critique loop governed by external symbolic verifiers and programmatic constraint critics.
  • LLM+P (Large Language Models + Classical Planners): An LLM translates a natural-language planning problem into a formal PDDL problem file, and the Fast Downward classical planner computes a sound or minimum-cost plan.
  • Scenario-Based Programming with LLMs: A developer has an LLM write small scenario objects for a behavioural program, runs a model checker on the result, and hands its counterexample traces back to the LLM to fix the strategy.

What it does not catch

  • LLM-Modulo Framework: Even with external critics, 20.6% leaves nearly four out of five complex multi-constraint itineraries unsolved within the retry budget, because critique-guided local edits can still fail when constraints interact globally without an exact solver.
  • LLM+P (Large Language Models + Classical Planners): LLM+P requires a human expert to supply the PDDL domain file (action preconditions and effects) in advance, and its one-shot translator has no validator-repair loop when the LLM emits syntax errors, undeclared objects or inverted goal predicates.

Answer checkers

An answer checker compares the model's answer with a reference by rule, so the verdict does not depend on the model grading itself. Some checkers also test a derivation one equation at a time while the model writes it.

Tools

  • Math-Verify: Rule-based checker that parses an LLM's math answer and tests it against the gold answer, usable as a reward.

Library cards

What it does not catch

  • Math-Verify: It checks that a final answer matches the reference, not that the reasoning is sound, and unusual answer formats can be missed or mismatched.
  • Online CAS checking (Catch It Where It Happens): The checker only catches local algebra errors (signs, expansions, reindexing), not wrong strategies or premises, and 'holds' means numerical agreement, not proof. One benchmark (the lab's own ASyMOB) and three models from two families were tested; the paper is an unreviewed preprint.

The ladder at a glance

Read the table in the order of the sections above. A pass at any rung says only what that rung checks.

Six ways to validate LLM output with code: what each catches, what it misses, and examples
MethodCatchesMissesExamples
Grammar-constrained decodingBroken syntax, invalid JSON, a value outside a fixed list.Wrong facts inside a valid shape.Outlines, XGrammar, PICARD, Synchromesh
Schema validation and retryMissing fields, wrong types and any rule you can write as code.Values that fit the schema and are still false.Instructor, Guardrails AI
Test gates and execution feedbackCode that crashes, fails its tests or breaks a lint rule.Behavior that no test covers.Aider, Agentless, CodeT, Self-Debugging with Execution Feedback
Formal verificationAny program or proof step that does not follow from the stated specification.A specification that does not say what the user meant.Lean REPL, Kimina Lean Server, AutoVerus, AlphaVerus
Symbolic critics and plannersPlans that break a stated constraint.Constraints that nobody wrote down.LLM-Modulo Framework, LLM+P (Large Language Models + Classical Planners)
Answer checkersA final answer that does not match, or an algebra step that does not hold.Sound-looking reasoning built on a wrong strategy or premise.Math-Verify, Online CAS checking (Catch It Where It Happens)

How to combine them

Stack the checks from cheap to expensive: shape first, then tests, then formal proof where the stakes justify it. Each layer shrinks what the next one has to check.

The theory page explains why the order matters. The Tools shelf lists every tool named here with its install line. For systems that run a full loop of propose, check and retry, see program evolution systems compared.