Skip to content
mentoor

Topic 2 of 5 · 5 min read

Validating output structure with schemas

Goal: Write a schema check that separates malformed output from correct-format, wrong-content output.

A schema check answers one question: is this output shaped the way the next system needs it? It says nothing about whether the content is right, and that separation is its main value.

Check yourself · 1 of 3

An output is valid JSON and matches the schema, but the category is wrong. What does the schema check report?

Choose one answer

Why it matters

When a model feeds a parser, a database or an API call, one missing field breaks the pipeline. A schema check catches that without a human. It also splits your failures into two buckets. Output that does not parse is a format failure, fixed with prompt wording, structured output modes or a retry. Output that parses but is wrong is a content failure, fixed in another way. One blended pass rate hides which one you have.

How to do it

  1. Define the contract once. Use JSON Schema, a Pydantic model in Python or a Zod schema in TypeScript. Reuse the same definition in production code and in the eval.
  2. Be strict where the consumer is strict. Mark required fields, use enum for closed sets, set additionalProperties: false when extra keys would cause harm, and bound numbers.
  3. Report two scores. Format-valid rate first, then content accuracy among the valid outputs only.
  4. Keep the error. Store the validator's message, such as priority: Input should be 'low', 'medium' or 'high'. It tells you the failure pattern.
  5. Do not repair silently. If the grader strips code fences or fixes quotes, count that as a separate "repaired" outcome so you know how often it happens.

Before and after

# Weak: passes anything that is valid JSON
def grade(output: str) -> bool:
    json.loads(output)
    return True
from typing import Literal
from pydantic import BaseModel, ValidationError

class Ticket(BaseModel):
    category: Literal["billing", "shipping", "other"]
    priority: Literal["low", "medium", "high"]
    summary: str

def grade_format(output: str):
    try:
        return Ticket.model_validate_json(output), None
    except ValidationError as e:
        return None, str(e)

The second version rejects {"category": "refund"} and priority: 3. A later step compares category with the key.

What goes wrong

  • Schema as the whole grade. {"category": "other", ...} is valid and may be wrong.
  • Too loose. A field typed string that should be an enum lets any text through.
  • Too strict. Rejecting a harmless extra key can fail good answers and hide real quality.
  • Constrained decoding hides the signal. If the provider forces valid JSON, format failures vanish, but content failures remain, so keep the content grader.

Examples

Zod in a TypeScript eval

import { z } from "zod";

const Ticket = z.object({
  category: z.enum(["billing", "shipping", "other"]),
  priority: z.enum(["low", "medium", "high"]),
});

export function gradeFormat(raw: string) {
  try {
    const r = Ticket.safeParse(JSON.parse(raw));
    return r.success ? { ok: true, data: r.data } : { ok: false, error: r.error.message };
  } catch {
    return { ok: false, error: "not JSON" };
  }
}

The result separates "not JSON" from a schema error, so the report shows which one dominates.

Two numbers in the report

Out of 200 cases, 188 pass the schema (94% format-valid). Of those 188, 150 have the right category (80% content accuracy). The weak spot is content, not format, so adding a stricter JSON instruction would not help.

Key points

  • A schema check grades structure only: required fields, types, enums and allowed extra keys.
  • Report format-valid rate and content accuracy separately, because they have different fixes.
  • Share one schema between production code and the eval so the test matches what the consumer enforces.
  • Keep the validator's error message with each failure; the pattern shows what the model gets wrong.
  • A valid output can still be wrong, so a schema check never replaces a content check.

Common mistakes

  • Calling json.loads and treating a successful parse as a pass.
  • Reporting one pass rate that mixes format failures and wrong answers.
  • Writing the eval schema by hand separately from the production one, so they drift apart.
  • Silently repairing the output in the grader and never counting how often it was needed.

Check yourself · 2 of 3

Your eval reports one pass rate of 80%. Why is it more useful to report format-valid rate and content accuracy separately?

Choose one answer

Check yourself · 3 of 3

The field priority should only ever be "low", "medium" or "high". Which schema rule enforces that?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic