CertPrep
Domain 6 · Lesson 6.3 · 5 min read

Structured Output and Defensive Parsing

Exam skillStructured Output and Defensive Parsing

Applying structured outputs with strict schema validation, response validation, and defensive parsing of free-text fallbacks to protect downstream code from malformed or unexpected model output.

Protect downstream code from malformed or unexpected model output with structured outputs and strict tool schemas, schemas that mirror the data (arrays, enums, nullable fields), business-rule validation after parsing, stop-reason and refusal checks before reading fields, and defensive parsing for any free-text fallback.

What you need to know

"Respond in JSON" in a prompt works most of the time. Code that breaks the rest of the time is the defect this skill is about.

Layers of protection

LayerGuaranteesDoes not guarantee
Structured outputs (JSON schema on the response)Valid JSON in the declared shape, no preambleThat values are true or sensible
Strict tool use (strict schema on a tool)Tool inputs match the declared types and required fieldsThat the arguments are the right ones
Response validation in codeBusiness rules: totals add up, dates in range, IDs existNothing, if you skip it
Stop-reason and refusal checksYou never parse truncated or refused output as valid
Defensive parsing of free-text fallbacksUnsafe or partial text is rejected, not executed or guessed

Schemas that mirror the data

  • Arrays for repeated items (contacts, line items), not contact1 to contact10.
  • Enums for fixed values ("positive", "negative", "neutral"), so "Positive." and "mixed" cannot appear.
  • Nullable fields for values that may be absent, plus an instruction to use null. A required field with no way to say "missing" pushes the model to invent a value.
  • Descriptions on fields where meaning is not obvious.

Check before you parse

resp = client.messages.create(...)
if resp.stop_reason == "max_tokens":
    raise Incomplete("raise the budget or reduce scope")   # never parse partial JSON
if resp.stop_reason == "refusal":
    return handle_refusal(resp)                            # refusals may not match the schema
data = parse_and_validate(resp)                            # schema, then business rules

Free-text fallbacks

Where structured outputs are not available (for example, on a platform that lacks the feature), ask for JSON, then extract, validate against the same schema and reject what fails. Never eval() model output, never accept anything that merely starts with {, and never fill missing fields with silent defaults.

Streaming structured data

Fields that stream in are provisional until the message completes and the full object validates. Show them as in progress; do not commit them early.

In the exam

Items show a parser, a schema or a downstream failure and ask for the change that protects downstream code. Use structured outputs or strict tools for shape, schema features for absent and enumerated values, validation for meaning, and stop-reason checks for truncation and refusal. Distractors strip preambles by string slicing, retry until values match, trust the schema for facts, or repair partial JSON.

Check your understanding

Question 1

JSON.parse fails when the model adds "Here is the JSON:". Most robust fix?

Show answer

Answer: C. The response is constrained to the schema, with no preamble.

Question 2

Required fields lead the model to invent missing phone numbers. Fix?

Show answer

Answer: A. The schema must offer a truthful way to say "missing".

Question 3

Structured output comes back with stop_reason max_tokens and cut-off JSON. Handling?

Show answer

Answer: D. Truncated output is never valid data.

Apply it: Harden Bluestem's extraction output

Exercise · about 25 minCase: Bluestem Lending

Bluestem's extraction asks for JSON in the prompt. 3% of outputs fail to parse, 1.5% parse with totals that do not match line items, and documents missing a tax ID come back with invented IDs. One cloud platform the team may use for failover does not support the structured outputs feature yet.

  1. Write the schema for a bank statement (sketch the fields).
  2. List the validation rules applied after parsing.
  3. Define the handling for max_tokens, refusal and validation failure.
  4. Design the fallback path for the platform without structured outputs.
    Done when: no unvalidated record can reach the loan system.
Check your work
Show model answer

1. account_holder (string), tax_id (string or null), period_start and period_end (date), opening_balance and closing_balance (number), line_items (array of {date, description, amount, direction: enum credit or debit}), total_credits and total_debits (number).

2. Sum of credit line items equals total_credits (within one cent), same for debits; opening plus credits minus debits equals closing; dates inside the period; tax_id matches the expected pattern when present.

3. max_tokens: rerun once with a higher budget, else split by statement page. Refusal: route to manual entry. Validation failure: send to the review queue with the failed rule named; never write to the loan system.

4. On that platform: ask for JSON matching the same schema, extract the JSON object, validate with the same schema library and the same rules, reject on any failure; no repair, no eval.

Key termsStructured outputs

Sources