Trustworthy LLM Table Extraction: Layered Validation
A large language model (LLM) can read a tender document and return a table of award criteria with weights and sub-criteria. Usually it will be right. The rare wrong row is expensive: a weight of 35 read as 53 changes how bids are scored, and nothing in the output says so. This post describes a layered way to make such extraction reliable enough to use, with a worked example on a scoring grid, the table in a public tender that says how bids are marked.
In earlier work on a document-intelligence platform for construction, I designed an LLM extraction pipeline for public-procurement scoring grids with layered validation. What follows is general technique, not a description of that work. No single check is enough, but cheap checks stacked in order catch different kinds of error.
Version notice. Written and run with Python 3.13.7 and Pydantic 2.14.4, the latest release on PyPI on 1 December 2026. It uses typing.Self, so it needs Python 3.11 or later. Provider documentation was read on the same date and changes often, so check the current pages. The measurements further down used the same versions.
In short
- Constrained output guarantees the shape of a response, not the truth of its values, and each provider supports only a subset of JSON Schema.
- Pydantic validators in your own code enforce types, ranges and cross-field rules such as "weights sum to 100" that a provider schema often cannot express.
- Making the model quote its source and then checking that the quote exists on the cited page catches invented values that pass every structural check.
- Route by rule: retry on structural failures, send grounding or disagreement failures to a person, and log every failure by layer. On 450 synthetic corrupted records, layers 2 to 4 left 95 unflagged; a count check and an independent second pass left 5.
Five layers, cheapest first
An extraction is a claim: "this document says criterion X is worth Y points". Each layer tests that claim in a different way, and the cheap ones run first so that the expensive ones see fewer inputs.
Layer 1: constrained output and what it guarantees
Constrained output (also called structured outputs) makes the provider restrict generation so that the response parses against a JSON Schema, a standard way to describe the shape of JSON. It removes a whole class of failures, such as broken JSON and missing keys.
The guarantee is narrow, and the providers say so:
- OpenAI states that Structured Outputs constrains "completed, non-refusal" output to the schema. Refusals, incomplete responses (for example at a maximum token limit) and API errors still need handling, and business rules the schema does not express must be validated by you. The same page warns that "Structured Outputs can still contain mistakes."
- Google says its structured output mode supports a subset of JSON Schema, and that although output is syntactically correct JSON, you should "always validate values in your application".
- Anthropic lists numerical constraints such as
minimumandmaximum, and string length limits, as unsupported in its schemas. Its SDK helpers send a simplified schema, move the constraint into the field description and, where the helper validates responses, enforce it afterwards in your code. OpenAI listsminimumandmaximumas supported for models that are not fine-tuned.
Support differs by provider and by model, so a constraint that one API enforces may be only a hint on another. A schema also cannot say "these three numbers sum to 100"; cross-field rules belong in your own code.
There is also a quality trade-off. Tam and colleagues (2024) report a decline in reasoning performance under format restrictions, larger for stricter formats. Their tasks were reasoning benchmarks, not extraction, so test on your own documents. One option is to let the model reason or quote freely first and produce the structured record in a second step.
Layers 2 and 3: schema and semantic checks in Pydantic
Pydantic is a Python library that validates data against type-annotated classes. Validating again on your side costs little and does not depend on provider support. The model below describes a scoring grid. Field(ge=0, le=100) sets a range, extra="forbid" rejects invented keys, and every value carries an Evidence record, meaning the verbatim quote and page it came from. Calling model_json_schema() on such a model emits ordinary JSON Schema (for a points field with ge=0, le=100 it printed "maximum": 100, "minimum": 0), so the same class can drive layer 1 where the provider supports it.
Pydantic is lax by default: per its documentation it "will attempt to coerce values to the desired type when possible", so the string "123" becomes an integer. For model output that may hide a problem. Passing strict=True turns coercion off, though the documentation notes that strict mode is looser for JSON input, for example for date strings.
Semantic checks use @model_validator(mode="after"), which runs once the whole model has validated and should return self. Raising ValueError inside a validator is reported as a validation error. Two checks run here: sub-criteria must sum to their parent, and top-level criteria must sum to 100 with a deadline after the publication date.
from __future__ import annotations
import re
from datetime import date
from difflib import SequenceMatcher
from typing import Literal, Self
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
# Synthetic tender excerpt: page number -> text. Not a real document.
SOURCE = {
1: "Section 5. Award criteria. The contract is awarded to the tender with "
"the highest total score out of 100 points. Tenders are published on "
"2026-03-02 and must be submitted by 2026-04-15.",
2: "5.1 Price: 40 points. 5.2 Quality: 60 points, made up of "
"Methodology: 35 points and Team experience: 25 points.",
}
class Strict(BaseModel):
model_config = ConfigDict(extra="forbid") # unknown keys are errors
class Evidence(Strict):
quote: str = Field(min_length=3) # verbatim text the value came from
page: int = Field(ge=1)
class SubCriterion(Evidence):
name: str
points: float = Field(ge=0, le=100)
class Criterion(Evidence):
name: str
points: float = Field(ge=0, le=100)
sub_criteria: list[SubCriterion] = []
@model_validator(mode="after")
def subs_sum_to_parent(self) -> Self:
if self.sub_criteria:
total = sum(s.points for s in self.sub_criteria)
if abs(total - self.points) > 1e-6:
raise ValueError(
f"{self.name}: sub-criteria sum to {total}, parent is {self.points}")
return self
class AwardGrid(Strict):
published: date
deadline: date
criteria: list[Criterion] = Field(min_length=1)
@model_validator(mode="after")
def cross_field_checks(self) -> Self:
total = sum(c.points for c in self.criteria)
if abs(total - 100) > 1e-6:
raise ValueError(f"criteria sum to {total}, expected 100")
if self.deadline <= self.published:
raise ValueError("deadline is not after publication date")
return self
The sample document is a synthetic two-page excerpt held in a dictionary from page number to text. A real pipeline would take it from a PDF parser.
Layer 4: ground every value in the source
Schema and sum checks cannot detect a plausible, internally consistent fabrication. A model can return weights of 40 and 60 that sum correctly but were never in the document. Grounding closes that gap: require a verbatim quote and a page for every value, then verify mechanically.
The grounding check here does three things:
- It normalises whitespace and case, then looks for the quote on the cited page.
- If the exact match fails, it computes a similarity ratio with
difflib.SequenceMatcherfrom the standard library. A ratio of 0.9 or more counts as an approximate match, which is a soft signal for review, not a pass. - It checks that the extracted number actually appears inside the quote, so a real quote cannot be attached to the wrong value.
Dates are checked the same way, by looking for their ISO text in the source. That works only because the source here writes dates in ISO form. Real documents write dates many ways, so a production check needs a date parser first.
Two limits appear in the measurements below. The number-in-quote test passes if the number appears anywhere in the quote, so one long quote holding every weight defeats it; requiring the number next to its label is stricter. And 0.9 is lenient for short quotes: ratio() is 2.0*M/T (M matching characters, T the total length of both strings), so changing one digit of a 20-character quote still scores 0.95. The approximate tier is a flag for review, never evidence that the value is right.
Grounding is strong against invention and weak against misreading. If the model quotes the right sentence and misreads it, the quote check passes, which is what the number-in-quote step is for. Scanned documents add another failure source: the text layer may contain optical character recognition (OCR) errors, so an exact match can fail on a correct extraction. That is a reason to allow the fuzzy tier and route it to review.
def norm(text: str) -> str:
"""Collapse whitespace and case so line breaks do not defeat matching."""
return re.sub(r"\s+", " ", text).strip().lower()
def ground(item: Evidence, points: float, source: dict[int, str]) -> str:
"""Return 'exact', 'fuzzy' or an error string for one extracted value."""
page = norm(source.get(item.page, ""))
quote = norm(item.quote)
if quote in page:
status = "exact"
else:
# Slide the quote over the page and keep the best similarity ratio.
best = max((SequenceMatcher(None, quote, page[i:i + len(quote)]).ratio()
for i in range(max(1, len(page) - len(quote) + 1))), default=0)
if best < 0.9:
return f"quote not found on page {item.page}"
status = "fuzzy"
numbers = {float(n) for n in re.findall(r"\d+(?:\.\d+)?", item.quote)}
if points not in numbers:
return f"value {points} does not appear in its quote"
return status
def check_grounding(grid: AwardGrid, source: dict[int, str]) -> tuple[list[str], bool]:
"""Return (hard problems, any_fuzzy). Fuzzy matches are a soft signal."""
problems, fuzzy = [], False
for c in grid.criteria:
for item in [c, *c.sub_criteria]:
result = ground(item, item.points, source)
if result == "fuzzy":
fuzzy = True
elif result != "exact":
problems.append(f"{item.name}: {result}")
return problems, fuzzy
def check_dates(grid: AwardGrid, source: dict[int, str]) -> list[str]:
text = " ".join(source.values())
return [f"date {d} not in source" for d in (grid.published, grid.deadline)
if d.isoformat() not in text]
def agree(a: AwardGrid, b: AwardGrid) -> bool:
"""Compare dates, criteria and sub-criteria (names lower-cased, order ignored)."""
def flat(g: AwardGrid) -> tuple:
rows = sorted((c.name.lower(), c.points,
tuple(sorted((s.name.lower(), s.points) for s in c.sub_criteria)))
for c in g.criteria)
return g.published, g.deadline, rows
return flat(a) == flat(b)
def run(raw: str, source: dict[int, str], second_pass: str | None = None) -> tuple[str, str]:
"""Return (route, reason). Routes: accept, retry, review."""
try:
grid = AwardGrid.model_validate_json(raw, strict=True) # layers 2 and 3
except ValidationError as e:
err = e.errors()[0]
layer = "semantic" if err["type"] == "value_error" else "schema"
return "retry", f"{layer}: {err['msg']}"
hard, fuzzy = check_grounding(grid, source) # layer 4
hard = check_dates(grid, source) + hard
if hard:
return "review", f"grounding: {hard[0]}"
if second_pass is not None: # layer 5
other = AwardGrid.model_validate_json(second_pass, strict=True)
if not agree(grid, other):
return "review", "consistency: two passes disagree"
if fuzzy:
return "review", "grounding: quote matched only approximately"
return "accept", "all layers passed"
Layer 5: consistency between passes
Self-consistency, introduced by Wang and colleagues (2022), samples several reasoning paths from the model and keeps the answer that most of them agree on. It was evaluated on arithmetic and commonsense reasoning, where the paper reports gains of up to 17.9 percentage points on GSM8K over chain-of-thought prompting (PaLM-540B, 56.5 to 74.4 per cent accuracy). Extraction is not the same task, so treat those numbers as evidence that voting helps reasoning, not as a promise for your documents.
For extraction the simpler form is two independent passes, ideally with different prompts or models, followed by a field-by-field comparison. Disagreement is a useful signal even without voting: it tells you the value is hard, and a person should decide. The comparison has to cover the dates and every criterion and sub-criterion, because a skipped field cannot be checked.
The trade-off is cost and correlated error. Two passes roughly double the model spend, and if both make the same mistake, for example misreading the same ambiguous layout, they agree. So run consistency on high-stakes fields or on documents that failed softer checks, not necessarily on everything. The suite below measures the difference.
Recall: rows the model never returned
Every layer so far tests what was extracted. A dropped weighted row breaks the sum; a dropped zero-weight row, such as a pass or fail line, breaks nothing. Catching it needs an expectation from outside the response: count the items the document lists, or run a second pass that only lists every criterion and diff the lists. The count is cheaper:
ITEM = re.compile(r"[A-Z][A-Za-z ]*: \d+(?:\.\d+)? points")
def check_recall(grid: AwardGrid, source: dict[int, str]) -> list[str]:
"""Expected count from the document: most 'Name: N points' items on any one page."""
got = len(grid.criteria) + sum(len(c.sub_criteria) for c in grid.criteria)
want = max(len(ITEM.findall(t)) for t in source.values())
return [f"extracted {got} items, source lists {want}"] if got != want else []
The count is only as good as its pattern: this one fits items written as "Name: N points", and a model that drops one row and invents another passes. Treat a mismatch as a review route, not a retry.
Routing and logging
Different failures deserve different actions. The function run above returns one of three routes:
- Retry for schema and semantic failures. The error message is precise ("sub-criteria sum to 55.0, parent is 60.0"), so it can be fed back to the model in a second attempt, with a cap on attempts. A workflow engine can own the cap and the review queue, as in Temporal for Durable LLM and Document Pipelines.
- Review for grounding failures, approximate quotes and disagreement between passes. A retry is unlikely to settle these, because the model may repeat its mistake with the same confidence.
- Accept only when every layer passes.
Routing by rule is easier to audit than routing by a number. A model-reported confidence score is a weak extra signal until calibrated against labelled documents.
Finally, log every failure with its layer, the field, the document and the prompt version. A counter by layer, like the last line of the output below, shows where to spend effort. Schema failures point to the prompt or schema, grounding failures to the parser or page splitting, and repeated reviews on one field to an ambiguous clause worth a dedicated rule. Reviewed corrections also make a labelled set for the next evaluation.
Running the demonstration
The last block feeds fake model outputs through the pipeline: one valid record and eight broken variants, each built by editing the valid one. It calls no model; the outputs are hard-coded strings standing in for a real client.
import json
from collections import Counter
GOOD = {
"published": "2026-03-02", "deadline": "2026-04-15",
"criteria": [
{"name": "Price", "points": 40, "quote": "5.1 Price: 40 points", "page": 2},
{"name": "Quality", "points": 60, "quote": "5.2 Quality: 60 points", "page": 2,
"sub_criteria": [
{"name": "Methodology", "points": 35,
"quote": "Methodology: 35 points", "page": 2},
{"name": "Team experience", "points": 25,
"quote": "Team experience: 25 points", "page": 2}]}],
}
def variant(**edits):
"""Copy GOOD and apply edits given as paths joined by double underscores, e.g. criteria__0__points."""
doc = json.loads(json.dumps(GOOD))
for path, value in edits.items():
keys = path.split("__")
node = doc
for k in keys[:-1]:
node = node[int(k)] if k.isdigit() else node[k]
node[int(keys[-1]) if keys[-1].isdigit() else keys[-1]] = value
return json.dumps(doc)
CASES = {
"valid": (variant(), None),
"wrong type": (variant(criteria__0__points="forty"), None),
"weights sum to 110": (variant(criteria__0__points=50,
criteria__0__quote="5.1 Price: 50 points"), None),
"subs do not sum": (variant(criteria__1__sub_criteria__0__points=30,
criteria__1__sub_criteria__0__quote="Methodology: 30 points"), None),
"invented quote": (variant(criteria__0__quote="5.1 Price: 40 points, lowest bid wins"), None),
"value not in quote": (variant(criteria__0__quote="5.2 Quality: 60 points"), None),
"date not in source": (variant(deadline="2026-05-15"), None),
"passes disagree": (variant(), variant(criteria__0__points=60,
criteria__0__quote="5.2 Quality: 60 points",
criteria__1__points=40, criteria__1__quote="5.1 Price: 40 points",
criteria__1__sub_criteria=[])),
"fuzzy quote": (variant(criteria__0__quote="5.1 Price 40 points"), None),
}
failures = Counter()
for label, (raw, second) in CASES.items():
route, reason = run(raw, SOURCE, second)
if route != "accept":
failures[reason.split(":")[0]] += 1 # in production: append to a JSONL log
print(f"{label:20} -> {route:6} {reason}")
print(dict(failures))
Running the file printed the following:
valid -> accept all layers passed
wrong type -> retry schema: Input should be a valid number
weights sum to 110 -> retry semantic: Value error, criteria sum to 110.0, expected 100
subs do not sum -> retry semantic: Value error, Quality: sub-criteria sum to 55.0, parent is 60.0
invented quote -> review grounding: Price: quote not found on page 2
value not in quote -> review grounding: Price: value 40.0 does not appear in its quote
date not in source -> review grounding: date 2026-05-15 not in source
passes disagree -> review consistency: two passes disagree
fuzzy quote -> review grounding: quote matched only approximately
{'schema': 1, 'semantic': 2, 'grounding': 4, 'consistency': 1}
The invented quote, the wrong value and the date outside the source all satisfy the schema and the arithmetic, so only grounding catches them. The disagreement case is a valid record in both passes, so only the comparison sees the problem.
Which layer catches which error
The nine cases above show only that each layer fires on a toy excerpt, not what each buys. The suite below injects 15 error types into random synthetic tenders, 30 records per type (450 in all), and records the first layer to flag each, in the order schema, semantic, grounding (exact, then approximate), count check, consistency. Documents have three to five criteria (weights in multiples of 5, summing to 100), half of the larger rows split into two sub-criteria, a zero-weight pass or fail row in 40 per cent, and a verbatim annex in 30 per cent. The second pass is simulated in two ways. In the first it is the ground truth, so any error differs from it by construction and the flag counts are an upper bound. In the second it is an exact repeat of the error. Real passes, with their own mistakes, fall between. To reproduce, save the first two code blocks as pipeline.py and the next as suite.py, then run python suite.py (seed 7, so counts are deterministic; timings are not).
"""Perturbation suite: which layer flags which injected error (synthetic data, no model calls).
Needs pipeline.py (the first two code blocks of the post). Run: python suite.py
"""
from __future__ import annotations
import json
import random
import re
import statistics
import time
from collections import Counter
from datetime import date, timedelta
from pydantic import ValidationError
from pipeline import AwardGrid, agree, check_dates, check_grounding
NAMES = ["Price", "Quality", "Delivery", "Sustainability", "Support", "Warranty",
"Safety", "Innovation", "Maintenance", "Training"]
SUBS = ["Methodology", "Team experience", "Schedule", "References", "Equipment", "Logistics"]
ITEM = re.compile(r"[A-Z][A-Za-z ]*: \d+(?:\.\d+)? points")
def make_doc(rng: random.Random) -> tuple[dict[int, str], dict]:
"""One random tender: (pages, ground-truth extraction). Weights are multiples of 5, sum 100."""
names = rng.sample(NAMES, rng.randint(3, 5))
cuts = sorted(rng.sample(range(1, 20), len(names) - 1))
weights = [5 * (b - a) for a, b in zip([0, *cuts], [*cuts, 20])]
pub = date(2026, 1, 1) + timedelta(days=rng.randint(0, 200))
clar, dead = pub + timedelta(days=rng.randint(7, 14)), pub + timedelta(days=rng.randint(30, 50))
crit, lines = [], []
for i, (n, w) in enumerate(zip(names, weights), 1):
line, row = f"5.{i} {n}: {w} points", {"name": n, "points": w, "page": 2}
row["quote"] = line
if w >= 30 and rng.random() < 0.5: # two sub-criteria that sum to the parent
a, (sa, sb) = 5 * rng.randint(1, w // 5 - 1), rng.sample(SUBS, 2)
line += f", made up of {sa}: {a} points and {sb}: {w - a} points"
row["sub_criteria"] = [
{"name": sa, "points": a, "quote": f"{sa}: {a} points", "page": 2},
{"name": sb, "points": w - a, "quote": f"{sb}: {w - a} points", "page": 2}]
crit.append(row)
lines.append(line + ".")
if rng.random() < 0.4: # a pass/fail row with zero weight
line = f"5.{len(crit) + 1} Compliance: 0 points"
crit.append({"name": "Compliance", "points": 0, "quote": line, "page": 2})
lines.append(line + " (pass or fail).")
pages = {1: f"Section 5. Award criteria. The contract is awarded to the tender with the "
f"highest total score out of 100 points. Tenders are published on {pub} and must "
f"be submitted by {dead}. Clarification questions are accepted until {clar}.",
2: " ".join(lines)}
if rng.random() < 0.3: # an annex repeating the criteria word for word
pages[3] = "Annex. Recap. " + " ".join(lines)
return pages, {"published": str(pub), "deadline": str(dead), "criteria": crit}
# --- the recall check and the layer-attributing pipeline --------------------------------
def check_recall(grid: AwardGrid, source: dict[int, str]) -> list[str]:
"""Expected count from the document: most 'Name: N points' items on any one page."""
got = len(grid.criteria) + sum(len(c.sub_criteria) for c in grid.criteria)
want = max(len(ITEM.findall(t)) for t in source.values())
return [f"extracted {got} items, source lists {want}"] if got != want else []
def first_flag(raw: str, source: dict[int, str], second: str) -> str:
"""Name the first layer that flags the record, or 'accepted'."""
try:
grid = AwardGrid.model_validate_json(raw, strict=True)
except ValidationError as e:
return "schema" if e.errors()[0]["type"] != "value_error" else "semantic"
hard, fuzzy = check_grounding(grid, source)
if check_dates(grid, source) + hard:
return "grounding"
if fuzzy:
return "approximate"
if check_recall(grid, source):
return "recall"
if not agree(grid, AwardGrid.model_validate_json(second, strict=True)):
return "consistency"
return "accepted"
# --- perturbations: each edits a deep copy `g` of the truth, returns a dict or a raw string ---
def rev(n: int) -> int:
return int(str(n)[::-1])
def weighted(g):
return [c for c in g["criteria"] if c["points"] > 0]
def flat_rows(g): # weighted rows without sub-criteria
return [c for c in weighted(g) if not c.get("sub_criteria")]
def swappable(g):
return [c for c in g["criteria"] if c["points"] >= 10 and c["points"] != rev(c["points"]) <= 100]
def truncated(g, rng, pages):
return json.dumps(g)[: int(len(json.dumps(g)) * 0.8)]
def wrong_type(g, rng, pages):
g["criteria"][0]["points"] = "4O" # letter O, not zero
return g
def unit_change(g, rng, pages):
rng.choice(weighted(g))["points"] = 0.4
return g
def digit_swap(g, rng, pages):
c = rng.choice(swappable(g))
c["points"] = rev(c["points"])
return g
def move_five(g, rng, pages, rewrite=False):
a, b = rng.sample(flat_rows(g) if len(flat_rows(g)) > 1 else weighted(g), 2)
a["points"] += 5
b["points"] -= 5
for c in (a, b):
if rewrite: # the model also edits the number inside its quote
c["quote"] = re.sub(r"\d+(?:\.\d+)?(?= points)", str(c["points"]), c["quote"], count=1)
return g
def move_five_rewritten(g, rng, pages):
return move_five(g, rng, pages, rewrite=True)
def invented_quote(g, rng, pages):
rng.choice(g["criteria"])["quote"] += ", lowest bid wins"
return g
def paraphrase(g, rng, pages):
c = rng.choice(weighted(g))
c["quote"] = f"{c['name']} is worth {c['points']} points"
return g
def wrong_page(g, rng, pages):
rng.choice(g["criteria"])["page"] = rng.choice([1, 3])
return g
def deadline_invented(g, rng, pages):
g["deadline"] = str(date.fromisoformat(g["deadline"]) + timedelta(days=rng.randint(10, 30)))
return g
def deadline_other_real_date(g, rng, pages):
g["deadline"] = re.search(r"until (\d{4}-\d{2}-\d{2})", pages[1]).group(1) # the clarification date
return g
def drop_weighted(g, rng, pages):
g["criteria"].remove(rng.choice(weighted(g)))
return g
def drop_zero(g, rng, pages):
g["criteria"] = weighted(g)
return g
def invent_zero_row(g, rng, pages):
g["criteria"].append({"name": "Social value", "points": 0,
"quote": "5.9 Social value: 0 points", "page": 2})
return g
def swap_with_broad_quote(g, rng, pages):
a = rng.choice(flat_rows(g))
b = rng.choice([c for c in flat_rows(g) if c["points"] != a["points"]])
a["points"], b["points"] = b["points"], a["points"]
for c in g["criteria"]:
c["quote"] = pages[2] # one long quote containing every number
return g
# label -> (perturbation, eligible(truth))
TYPES = {
"truncated JSON": (truncated, lambda g: True),
"wrong type (points as text)": (wrong_type, lambda g: True),
"unit change (fraction)": (unit_change, lambda g: True),
"digit swap (35 to 53)": (digit_swap, lambda g: bool(swappable(g))),
"weights moved, sum kept": (move_five, lambda g: True),
"weights moved, quote rewritten": (move_five_rewritten, lambda g: True),
"invented quote text": (invented_quote, lambda g: True),
"paraphrased quote": (paraphrase, lambda g: True),
"wrong page": (wrong_page, lambda g: True),
"deadline invented": (deadline_invented, lambda g: True),
"deadline swapped for another real date": (deadline_other_real_date, lambda g: True),
"dropped weighted row": (drop_weighted, lambda g: True),
"dropped zero-weight row": (drop_zero, lambda g: any(c["points"] == 0 for c in g["criteria"])),
"invented zero-weight row": (invent_zero_row, lambda g: True),
"weights swapped, one broad quote": (swap_with_broad_quote,
lambda g: len({c["points"] for c in flat_rows(g)}) >= 2),
}
COLUMNS = ["schema", "semantic", "grounding", "approximate", "recall", "consistency"]
def run_suite(seed: int = 7, per_type: int = 30):
rng = random.Random(seed)
docs = [make_doc(rng) for _ in range(400)]
table = {}
for label, (fn, eligible) in TYPES.items():
hits, repeat_miss, n = Counter(), 0, 0
for pages, truth in [d for d in docs if eligible(d[1])][:per_type]:
out = fn(json.loads(json.dumps(truth)), rng, pages)
raw = out if isinstance(out, str) else json.dumps(out)
hits[first_flag(raw, pages, json.dumps(truth))] += 1 # pass 2 independent and correct
if first_flag(raw, pages, raw if raw.endswith("}") else json.dumps(truth)) == "accepted":
repeat_miss += 1 # pass 2 repeats the same error
n += 1
table[label] = (n, hits, repeat_miss)
clean = Counter(first_flag(json.dumps(t), p, json.dumps(t)) for p, t in docs[:100])
ocr = Counter()
for pages, truth in docs[100:150]: # clean extraction, one OCR slip in the text layer
t = pages[2]
i = rng.choice([m.start() for m in re.finditer(r"[a-z]", t[: t.index(":")])])
noisy = {**pages, 2: t[:i] + "x" + t[i + 1:]}
ocr[first_flag(json.dumps(truth), noisy, json.dumps(truth))] += 1
return table, clean, ocr, docs
def timings(docs):
"""Median and p95 microseconds per record for each stage."""
out: dict[str, list[float]] = {k: [] for k in
("parse, schema, semantic", "grounding, quotes found", "count check",
"consistency compare", "grounding, quote missing")}
for pages, truth in docs:
raw = json.dumps(truth)
for _ in range(5):
t0 = time.perf_counter()
grid = AwardGrid.model_validate_json(raw, strict=True)
t1 = time.perf_counter(); check_grounding(grid, pages); check_dates(grid, pages)
t2 = time.perf_counter(); check_recall(grid, pages)
t3 = time.perf_counter(); agree(grid, AwardGrid.model_validate_json(raw, strict=True))
t4 = time.perf_counter()
for k, a, b in zip(list(out)[:4], (t0, t1, t2, t3), (t1, t2, t3, t4)):
out[k].append(b - a)
for pages, truth in docs[:100]:
bad = json.loads(json.dumps(truth))
bad["criteria"][0]["quote"] += " extra words"
grid = AwardGrid.model_validate_json(json.dumps(bad), strict=True)
t0 = time.perf_counter(); check_grounding(grid, pages)
out["grounding, quote missing"].append(time.perf_counter() - t0)
return {k: (statistics.median(v) * 1e6, sorted(v)[int(len(v) * 0.95)] * 1e6) for k, v in out.items()}
if __name__ == "__main__":
table, clean, ocr, docs = run_suite()
print(f"{'error type':40}{'n':>3} " + " ".join(f"{c[:6]:>6}" for c in COLUMNS) + " missed missed_if_repeat")
totals = Counter()
for label, (n, hits, rep) in table.items():
totals.update(hits)
print(f"{label:40}{n:3d} " + " ".join(f"{hits.get(c, 0):6d}" for c in COLUMNS)
+ f" {hits.get('accepted', 0):6d} {rep:6d}")
n_all = sum(v[0] for v in table.values())
print("records", n_all, "| accepted (missed)", totals["accepted"],
"| missed if pass 2 repeats", sum(v[2] for v in table.values()))
left = n_all
for c in COLUMNS:
left -= totals[c]
print(f" after {c:12} still unflagged {left}")
print("clean records (100):", dict(clean), "| clean with OCR slip (50):", dict(ocr))
for k, (med, p95) in timings(docs).items():
print(f"{k:28} median {med:8.1f} us p95 {p95:8.1f} us")
| Error type | First flagged by (of 30) | Missed | Missed if pass 2 repeats it |
|---|---|---|---|
| truncated JSON | schema 30 | 0 | 0 |
| wrong type (points as text) | schema 30 | 0 | 0 |
| unit change (fraction) | semantic 30 | 0 | 0 |
| digit swap (35 to 53) | semantic 30 | 0 | 0 |
| weights moved, sum kept | semantic 2, grounding 28 | 0 | 0 |
| weights moved, quote rewritten | semantic 2, approx. quote 28 | 0 | 0 |
| invented quote text | grounding 30 | 0 | 0 |
| paraphrased quote | grounding 30 | 0 | 0 |
| wrong page | grounding 25 | 5 | 5 |
| deadline invented | grounding 30 | 0 | 0 |
| deadline swapped for another real date | 2nd pass 30 | 0 | 30 |
| dropped weighted row | semantic 30 | 0 | 0 |
| dropped zero-weight row | count 30 | 0 | 0 |
| invented zero-weight row | grounding 30 | 0 | 0 |
| weights swapped, one broad quote | 2nd pass 30 | 0 | 30 |
What the numbers say:
- Layers 2 to 4 flagged 355 of 450, with no false alarms on 100 clean records: grounding 173, sum and date rules 94, schema 60, approximate quotes 28.
- The count check flagged all 30 dropped zero-weight rows, which no sum can see.
- Only a second pass, simulated as correct, flagged the 60 records with a deadline swapped for another real date or weights swapped under one broad quote. If it repeats the error they stay missed (65 missed in total).
- The 5 records missed regardless are wrong pages where an annex repeats the quote: the value is right, the provenance link is not.
- All 50 clean records with one simulated OCR slip went to review: on scans, review load follows text quality.
The perturbations were written alongside the checks, so the table shows what each layer can see, not how often real models fail. The documents are tiny (median 427 characters), which flatters the timings.
| Stage | Median (µs) | 95th percentile (µs) |
|---|---|---|
| Parse, schema, semantic | 8 | 12 |
| Grounding, quotes found | 37 | 76 |
| Grounding, quote missing (fuzzy scan) | 5,106 | 9,676 |
| Count check | 4 | 6 |
| Consistency compare | 12 | 19 |
Medians over 400 documents with 5 repeats (100 for the fuzzy path), from one run on one machine. A second run differed by up to a third, so read these as indicative. The fuzzy scan is over a hundred times slower than an exact match and grows with page length times quote length (quadratic in the worst case, per the difflib documentation), so run it only after an exact match fails.
When to use what
| Situation | Add |
|---|---|
| Any extraction | Strict schema and sum, range and date rules |
| Traceable values | Quote and page per value, number next to its label |
| Rows can go missing | Count from the document, or a "list every row" pass |
| High stakes, or errors sums cannot see | Independent second pass comparing every field |
| Scans | Budget review time for approximate matches |
| Both passes misread alike | Sampled human audit |
What this does not cover
- Parsing. Getting clean text and page numbers out of PDFs, scans and tables is a separate hard problem, covered in PDF Tables to Spreadsheets, and errors there pass through every layer here.
- Recall beyond the count check. The count depends on a pattern that matches how the document lists items. A missing optional criterion the pattern cannot see, or one dropped row traded for one invented row, passes.
- Evaluation. Rates of error, review load and cost per document must be measured on a labelled sample of your own documents, with repeats and confidence intervals as in Making LLM Evaluation Reproducible with MLflow. The synthetic suite above is not such a measurement.
- Provider details. Schema support, refusal handling and limits change between models and releases.
- Review tooling. The example routes to review but does not show the interface where a person sees the quote beside the page.
A short checklist: constrain the output where the provider allows it; validate again in Pydantic with strict mode; encode every sum, range, unit and date rule; require a quote and page per value; verify the quote and the number in it; count the rows the document lists; compare two passes, dates included, on high-stakes fields; route by rule; log by layer; and audit a sample of accepted records by hand.
Sources
- OpenAI docs: Structured Outputs
- Anthropic docs: Structured outputs
- Google Gemini docs: Structured output
- Pydantic docs: Validators
- Pydantic docs: Strict mode
- Wang et al. (2022), Self-Consistency Improves Chain of Thought Reasoning in Language Models
- Tam et al. (2024), Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models
- Python docs: difflib (SequenceMatcher.ratio and its complexity)
- PyPI: pydantic