Skip to content
mentoor

Topic 3 of 5 · 4 min read

Validating structured output before you use it

Goal: Add checks that reject schema-valid but wrong output, such as invented ids, impossible values and refusals.

A schema proves the shape of the output, not that it is true, so treat the parsed result as untrusted input and check it against what your system knows. Validation is the code between the model's reply and any database write, payment or email.

Check yourself · 1 of 3

A reply passes the schema and contains order_id: "ORD-48213". What must your code still do before refunding?

Choose one answer

Why it matters

A schema can say order_id is a string. It cannot say the order exists. The model can return "ORD-99999", a well-formed id that belongs to nobody. It can return a refund of -40, a date in the year 1900, or "summary": "". All of these pass the type check.

Three layers of checks

  1. Parse and type check. Parse the reply with Pydantic or Zod. This catches bad JSON, wrong types and missing fields when the provider does not enforce the schema.
  2. Range and format rules. Add constraints the schema language lacks in your validator: amounts above zero and below a limit, dates inside a sensible window, non-empty strings, a string that matches your id format.
  3. Cross-checks against your data. Look up every id the model returned. Compare extracted amounts against the source text. Confirm that quoted text really appears in the document.

Also check for refusals and incomplete stops. A reply can be cut at the token limit, or the model may decline the request. In both cases the body may not match the schema, and the response carries a field or stop reason that tells you. Read it before you parse.

Before and after

# Weak: trusts the parsed value
ticket = Ticket.model_validate_json(resp.text)
db.orders.refund(ticket.order_id, ticket.refund_eur)
# Fixed: stop reason, range, lookup
if resp.stop_reason != "end_turn":
    raise NeedsRetry("incomplete or refused")
ticket = Ticket.model_validate_json(resp.text)
order = db.orders.get(ticket.order_id)
if order is None:
    raise InvalidOutput(f"unknown order {ticket.order_id}")
if not (0 < ticket.refund_eur <= order.total_eur):
    raise InvalidOutput("refund outside order total")
db.orders.refund(order.id, ticket.refund_eur)

Raise a specific error type so the retry code in the next topic can send a useful message back.

What goes wrong

  • Trusting ids. Models produce ids that look right. Always look them up.
  • Checking only types. A negative amount is still a number.
  • Silent defaults. Replacing an empty string or a missing value with a default hides the failure and stores bad data.
  • Validating late. Do the checks before side effects. A refund that already ran cannot be rejected afterwards.

Examples

Zod with range checks and a refinement

const Refund = z.object({
  order_id: z.string().regex(/^ORD-\d{5}$/),
  refund_eur: z.number().positive().max(5000),
  reason: z.string().min(5),
});

const parsed = Refund.parse(JSON.parse(text));
const order = await db.orders.find(parsed.order_id);
if (!order || parsed.refund_eur > order.total) throw new InvalidOutput("bad refund");

A quote that is not in the source

The model extracts a contract clause and returns "quote": "Payment within 14 days". The schema accepts any string. A substring check against the contract text fails because the document says 30 days. Without the check, a wrong quote reaches the review screen.

Key points

  • Schema-valid output can still be false, so validate before any side effect.
  • Add range, format and non-empty rules that the schema language cannot express.
  • Look up every id and entity the model returns against your own data.
  • Check the stop reason or refusal field before parsing the body.
  • Raise specific validation errors so the retry step can explain what was wrong.

Common mistakes

  • Assuming that valid against the schema means correct.
  • Not looking up ids the model returned.
  • Replacing missing or empty values with silent defaults.
  • Running validation after the refund, email or write has happened.

Check yourself · 2 of 3

Which of these values would pass a type check of refund_eur: number but should still be rejected?

Choose one answer

Check yourself · 3 of 3

The response ends with a stop reason saying the output hit the token limit. What is the right first step?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic