AI

Structured LLM Output: Schemas, Validators and Repair Loops

JSON mode only promises parseable text. We layer strict schemas, context-aware validators and a bounded repair loop so model answers are safe to act on.

Weaveward ai editorial illustration

A model that returns valid JSON has told you almost nothing. The object can parse, match every type in your schema and still point at a candidate id that was never in the prompt, give a sentence range that ends before it starts, or skip half the items it was asked to judge. If the next step of your pipeline cuts video, writes a ledger row or sends an email based on that object, "it parsed" is not a safety property.

Our position is that model output is untrusted input crossing a boundary, and it deserves the same layered checks as a public API payload: a strict schema generated from one Pydantic model, a parse step, a semantic validator that knows exactly what the model was shown, and a bounded repair loop that feeds the validator's complaints back without ever loosening the contract. Validated answers get cached; everything else gets counted.

Below we build each layer in runnable Python 3.12 and Pydantic v2, and ground it in the reasoning layer of our AI Video Clipper prototype, which asks agent CLIs (Claude Code or Codex) to triage and verify short-clip candidates. We describe what that code actually does, including where it chose a different trade-off from our default.

Three promises that are easy to confuse

"We use structured output" can mean three very different guarantees. The table separates them, plus the two layers you own.

Layer What it guarantees What it cannot catch
JSON mode Output is valid JSON, apart from edge cases the provider tells you to handle Missing fields, wrong types, invented keys
Provider structured outputs Completed, non-refusal output follows a supported subset of your JSON Schema Refusals, truncation, any rule that depends on the prompt
Pydantic parse Types, enums, required fields, closed objects, on your side of the wire Whether the values make sense for this request
Semantic validator Ids and ranges exist in the context shown; completeness and uniqueness Editorial or factual quality
Deterministic post-processing Cosmetic bounds clamped and recorded Anything that changes meaning

OpenAI's guide is explicit that structured outputs still leave refusals, incomplete responses, API errors and business rules to the application. Claude Code's headless docs say that when a run ends without valid structured output, the structured_output field is simply absent. Constrained decoding narrows the failure space; it does not remove the need to validate.

Layer 1: one Pydantic model, one strict schema

The schema you send to the provider and the model you validate with must come from the same source. A hand-written JSON Schema beside a Pydantic class eventually drifts, and you pay for calls whose answers pass the provider's checks and fail yours.

Strict structured-output modes impose a subset of JSON Schema. OpenAI requires every object to set additionalProperties: false, every property to be listed in required (optional values are emulated with a union that includes null), a root that is an object rather than an anyOf, and limits of 5,000 object properties, 10 levels of nesting and 1,000 enum values. Composition keywords such as allOf, not and if/then/else are not supported, and a strict request with an unsupported schema returns an error. Design your response models inside that box: Literal[...] for enums, no defaults, nullable instead of optional.

The clipper's strict_json_schema takes model_json_schema() output, inlines every $ref, lists all properties in required, closes every object and drops default, title, examples, numeric and length bounds, pattern, format and discriminator. Its docstring gives the reason: Codex needs the strict subset, Claude Code accepts any valid schema, so it emits the common subset and enforces ranges in Python after the call. That is a portability choice, not a hard limit: OpenAI's guide lists minimum, maximum and pattern as supported outside fine-tuned models, while Claude Code treats format as an unenforced annotation. A bound that only lives in the schema is a bound you are hoping for.

One detail is worth copying. The keyword title is dropped, yet VerifyAnswer has a field called title; a naive recursive delete would remove the field. The code cleans only the sub-schemas under properties, never the names, and a test asserts that every model field survives.

The parse side is a separate decision. The clipper parses responses with extra="ignore", while its persisted artifacts use extra="forbid" so hand edits fail loudly. With a closed schema on the wire we lean towards forbid for responses too: an unexpected key usually means the model misread the task, and forbidding it makes that a repairable error.

Layer 2: validate against what the model actually saw

Pydantic can tell you that start_sentence is an integer. Only code that knows the prompt can tell you that sentence 52 was not in it. The validator therefore closes over the request: the set of ids shown and the window of sentence numbers shown.

from typing import Literal

from pydantic import BaseModel, ConfigDict

class Closed(BaseModel):
    model_config = ConfigDict(extra="forbid")

class MoreContext(Closed):
    before: int
    after: int

class Decision(Closed):
    candidate_id: str
    verdict: Literal["keep", "drop", "need_more_context"]
    start_sentence: int  # inclusive ids, exactly as numbered in the prompt
    end_sentence: int
    reason: str
    more_context: MoreContext

class Triage(Closed):
    decisions: list[Decision]

def check_against_shown(ans: Triage, shown_ids: set[str], lo: int, hi: int) -> list[str]:
    """Rules no schema can express: they depend on what this prompt showed."""
    errors: list[str] = []
    got = [d.candidate_id for d in ans.decisions]
    if missing := shown_ids - set(got):
        errors.append(f"missing decisions for: {sorted(missing)}")
    if unknown := set(got) - shown_ids:
        errors.append(f"unknown candidate ids: {sorted(unknown)}; use only the ids shown")
    if len(got) != len(set(got)):
        errors.append("duplicate candidate ids: return exactly one decision per id")
    for d in ans.decisions:
        if not lo <= d.start_sentence <= d.end_sentence < hi:
            errors.append(
                f"{d.candidate_id}: need {lo} <= start_sentence <= end_sentence <= {hi - 1} "
                f"(the sentences shown); got {d.start_sentence}-{d.end_sentence}"
            )
        if d.verdict == "need_more_context" and d.more_context.before + d.more_context.after == 0:
            errors.append(f"{d.candidate_id}: need_more_context must ask for at least 1 sentence")
    return errors

Each message is written for the model: it names the field, states the allowed range and quotes what was received. That is the difference between a repair that converges in one round and one where the model guesses again.

The clipper's validators follow this pattern. Discovery rejects missing decisions, unknown or duplicate candidate ids, reversed or out-of-range spans, and boundaries moved more than three sentences from the proposed candidate. Verification requires the span to lie inside the sentences in the context pack, a rejection to carry a rejection code and an approval to have a title. Prompts ask for inclusive sentence ids, which is how models read numbered lines; the code converts to half-open ranges itself.

Not every violation deserves a repair round. The verify stage clamps scores to 0 to 10 and confidence to 0 to 1, truncates titles, and deterministically extends a span that starts or ends inside an unfinished utterance, noting the change in the clip's editing notes. Our rule: repair anything that changes meaning, clamp anything cosmetic, and always leave a trace of the clamp.

Layer 3: a bounded repair loop that never loosens the contract

When validation fails, tell the model exactly what was wrong. The loop below does that, caches only answers that pass both layers, and gives up after a fixed number of rounds.

import hashlib
import json
from collections.abc import Callable

from pydantic import ValidationError

VALIDATOR_VERSION = "triage-3"  # bump when check_against_shown changes meaning
cache: dict[str, str] = {}

class RepairExhausted(Exception):
    pass

def cache_key(model_id: str, system: str, prompt: str) -> str:
    material = {"v": VALIDATOR_VERSION, "model": model_id, "system": system,
                "prompt": prompt, "schema": Triage.model_json_schema()}
    return hashlib.sha256(json.dumps(material, sort_keys=True).encode()).hexdigest()

def ask(llm: Callable[[str], str], model_id: str, system: str, prompt: str,
        validate: Callable[[Triage], list[str]], max_repairs: int = 2) -> tuple[Triage, int]:
    key = cache_key(model_id, system, prompt)
    if (raw := cache.get(key)) is not None:
        hit = Triage.model_validate_json(raw)
        if not validate(hit):  # re-check on read; a stale entry falls through
            return hit, 0
    current, errors = prompt, ["no attempt made"]
    for attempt in range(1, max_repairs + 2):
        raw = llm(current)
        try:
            answer = Triage.model_validate_json(raw)  # bad JSON is a ValidationError too
            errors = validate(answer)
        except ValidationError as exc:
            errors = [f"{'.'.join(map(str, e['loc'])) or '<root>'}: {e['msg']}"
                      for e in exc.errors()[:12]]
        if not errors:
            cache[key] = raw  # only answers that passed both layers are stored
            return answer, attempt
        current = (f"{prompt}\n\n### Correction required\nThe validator rejected your answer:\n"
                   + "\n".join(f"- {e}" for e in errors)
                   + f"\nPrevious answer (truncated):\n{raw[:4000]}\n"
                   "Return a corrected, complete JSON object only.")
    raise RepairExhausted(errors)

This mirrors the clipper's ReasoningEngine.call. It appends a "Correction required" section (up to 12 Pydantic errors as dotted paths, or the semantic messages, plus the previous answer cut to 4,000 characters) to the original prompt, not to the last repair prompt, so prompts do not snowball. The default max_repair_attempts is 2, so a logical question costs at most three calls. When rounds run out it raises ReasoningValidationError, logs status invalid and caches nothing.

A fake LLM is enough to exercise every branch:

import functools

def dec(cid: str, verdict: str, s: int, e: int, before: int = 0) -> dict:
    return {"candidate_id": cid, "verdict": verdict, "start_sentence": s, "end_sentence": e,
            "reason": "...", "more_context": {"before": before, "after": 0}}

script = [
    '{"decisions": [',  # truncated output
    json.dumps({"decisions": [dec("c1", "keep", 40, 47), dec("c9", "drop", 52, 49)]}),
    json.dumps({"decisions": [dec("c1", "keep", 40, 47),
                              dec("c2", "need_more_context", 50, 55, before=4)]}),
]
seen: list[str] = []

def fake_llm(prompt: str) -> str:
    seen.append(prompt)
    return script[len(seen) - 1]

validate = functools.partial(check_against_shown, shown_ids={"c1", "c2"}, lo=36, hi=60)
answer, attempts = ask(fake_llm, "fake-1", "You are an editor.", "Triage c1, c2.", validate)
print(attempts, [d.verdict for d in answer.decisions])  # 3 ['keep', 'need_more_context']
answer, attempts = ask(fake_llm, "fake-1", "You are an editor.", "Triage c1, c2.", validate)
print(attempts, len(seen))  # 0 3: served from cache, no new call

The first round fails as <root>: Invalid JSON: EOF while parsing a list. The second parses but reports a missing decision for c2, an unknown id c9 and a reversed range. The third passes. What the loop never does is "help" by relaxing the contract: no dropping the failing field on retry, no falling back to JSON mode, no accepting the least-bad answer. Each turns a visible failure into silent bad data. If the contract is wrong, fix it in review and bump the version.

Make "I need more context" a valid answer

A required verdict of approve or reject forces a pick even when the evidence sits outside the window, which is how you get confident guesses. The clipper's VerifyAnswer.verdict has a third value, need_more_context, with a more_context object (before, after, reason) that is always required; the prompt says to set both counts to zero when nothing more is needed.

The verify stage treats that answer as a bounded retrieval request. It starts from configured context_before and context_after windows, pre-expands when local flags suggest a missing setup or payoff, and clamps each request to twice the expansion step (default step 4, so at most 8 sentences per side); a request for zero on both sides becomes one step. After max_expansions rounds (default 2), a candidate that still needs context is rejected with missing_context. Each expansion is a new prompt with its own cache key, drawing on the same run budget. Our validator enforces the other half of the bargain: asking for more means saying how much.

Cache validated answers by everything that shaped them

The clipper keys its SQLite response cache on a SHA-256 of canonical JSON holding an engine version, the backend name, the configured model, the task, the system prompt, the full prompt and the generated schema. Change a prompt word or a model field and the key changes. The key uses the original prompt, not the repair prompt, so a repaired answer serves the next identical question.

On a read the engine re-runs Pydantic and the semantic validator; an entry that no longer passes falls through to a fresh call. That handles tightened rules. Our snippet adds VALIDATOR_VERSION for what re-validation cannot see: a rule whose meaning changed while old answers still pass.

Model identity needs care. The clipper keys on the model it is configured to request (a per-task override or the backend default) and logs the model the backend reports. If configuration names a moving alias, the cache will serve answers from its previous target; pin versions in the key when that matters.

The payoff shows in the clipper's one documented end-to-end run, on a 21.4-minute NASA interview (a single measured run of a prototype, not a benchmark): a second job on the same video made zero LLM calls, because the global map is stored per source and the 13 discovery and verify answers came from the response cache.

Budgets, quotas and failures that are not the model's fault

Repair rounds and context expansions are where spend hides, so every fresh attempt reserves budget before it runs. The clipper's defaults allow 60 non-cached calls and 1,500,000 prompt characters per run. Cache hits are free, which makes a stopped run cheap to resume.

Failure How the clipper recognises it What happens
Overload, 5xx, timeout Pattern match on the CLI's error text Retried after 5 s and then 20 s, inside the same attempt
Usage limit, 429, quota Pattern match; QuotaExceededError Run stops, call logged as quota; a re-run resumes from cache
Run budget exhausted BudgetExceededError before the call Verify skips that candidate and lists it as unverified
Still invalid after repairs ReasoningValidationError Logged as invalid, nothing cached

The project's architecture notes put Codex's overhead at roughly 14,000 tokens per call against about 1,200 for Claude Code with a custom system prompt, and every repair round pays it again. Parallel calls are capped by max_parallel (default 2), and the first exception to escape a worker, such as a quota stop, cancels pending work. Deadlines and backpressure for interactive endpoints are covered in LLM API backpressure, deadlines and streaming.

Test with fakes and recorded envelopes; watch the repair rate

None of this needs a live model. The clipper's engine tests use a FakeBackend that replays scripted answers or exceptions, asserting that identical questions hit the cache, that a repair prompt starts with the original prompt and names the failing field, that three failed attempts leave the cache empty and log one invalid call, that the budget blocks new calls but not cache hits, and that transient errors are retried (delays patched to zero).

Parsing is tested separately against real CLI output captured from both tools: a Claude Code JSON envelope with structured_output and usage, Codex JSONL events, and a Codex model error. Record the whole envelope, not just the payload: a CLI upgrade can change the wrapper while the answer stays the same, and only a recorded envelope catches that.

Every logical call, cache hits included, lands in an llm_calls table with its attempts, status, tokens and duration, and clipper report aggregates attempts and failures per task. That is enough to compute a repair rate:

-- Fresh calls only: cache hits made no attempts, and quota or budget
-- stops say nothing about answer quality.
SELECT task,
       model,
       COUNT(*)                                            AS calls,
       ROUND(AVG(attempts > 1), 3)                         AS repair_rate,
       ROUND(AVG(status = 'invalid'), 3)                   AS exhausted_rate,
       ROUND(1.0 * SUM(attempts) / SUM(status = 'ok'), 2)  AS attempts_per_valid
FROM llm_calls
WHERE cache_hit = 0
  AND status IN ('ok', 'invalid')
GROUP BY task, model
ORDER BY repair_rate DESC;

Repair rate is a leading indicator. It moves when a prompt edit, a model swap or a schema change degrades the contract, before final output quality visibly drops, which makes it a natural gate in LLM release evaluation in CI. As simple arithmetic, a task where 20% of questions need one repair costs at least 1.2 calls per valid answer, and more in tokens because repair prompts carry the previous answer. A rising exhausted rate usually means the contract is impossible for the context you supply, not that the model is careless.

FAQ

If the provider enforces our schema, do we still need Pydantic?

Yes. The provider enforces a subset of the schema on completed, non-refusal output. Pydantic is the same contract checked on your side, and it catches truncation, refusals, and backends or CLIs that fall back to free text. The semantic layer has no provider equivalent at all.

How many repair rounds should we allow?

Two is a sensible default and it is what the clipper uses. If a third round regularly succeeds where the second failed, the error messages are probably not specific enough; improve them rather than raising the limit.

Checklist

  • Generate the provider schema from the same Pydantic model you validate with; never maintain two copies
  • Keep response models inside the strict subset: closed objects, every field required, enums as Literal
  • Enforce bounds in code even if the schema states them
  • Close the semantic validator over the ids and ranges actually shown in the prompt
  • Write validator errors as instructions: field, allowed range, received value
  • Bound repairs, append feedback to the original prompt and never loosen the schema on retry
  • Cache only validated answers, keyed by prompt, system prompt, schema, model and validator version, and re-validate on read
  • Offer a structured "need more context" answer with hard limits on how much more
  • Count every attempt against a run budget; treat quota as a resumable stop
  • Test with fake backends and recorded envelopes, and track repair rate per task and model

Primary references

The full reasoning layer, including progressive retrieval and the response cache, is described in the AI Video Clipper case study, and our AI solutions team builds the same validation discipline into production LLM features.

Let’s connect the dots

What would this look like for your business?

Let's turn the right ideas into a clear next step.

Discuss your project