Structured output: extract, validate, repair
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Extract a JSON object from a reply that contains prose or markdown fences without throwing on malformed input.
- Validate a parsed object against a small schema with enums and required non-empty strings, producing actionable error messages.
- Trace a bounded repair loop that resends exact validation errors and returns a structured failure after the budget is spent.
Overview
#Why raw text is not an interface
When a model's reply feeds code, the reply is an API response, and API responses need contracts. "Ask the model for JSON and parse it" sounds simple and fails in specific, repeatable ways: prose around the JSON, markdown fences, truncated output from maxOutputTokens (lesson 4), wrong field types, and invented enum values. Structured output engineering is the discipline of expecting every one of those and handling them cheaply.
Three layers: extract, validate, repair
Layer 1: extraction
Replies often wrap the payload in prose or fences. Extract the JSON-looking region before parsing, and return a sentinel failure instead of throwing:
function extractJson(text) {
const start = text.indexOf("{");
const end = text.lastIndexOf("}");
if (start === -1 || end <= start) return null;
try {
return JSON.parse(text.slice(start, end + 1));
} catch {
return null;
}
}
This handles fenced blocks and chatty preambles in one place. It is deliberately not clever: if the model emits two JSON objects, extraction takes the span from the first { to the last }, which is why the prompt must demand exactly one object.
Layer 2: validation against your schema
The model does not know your schema unless you state it, and even a stated schema is a request, not an enforcement mechanism. Validate after parsing, every time:
const TASK_SCHEMA = { title: "string", priority: ["high", "medium", "low"] };
function validateTask(obj, schema) {
const errors = [];
for (const [key, rule] of Object.entries(schema)) {
const v = obj ? obj[key] : undefined;
if (Array.isArray(rule)) {
if (!rule.includes(v)) errors.push(key + ": expected one of " + rule.join(", "));
} else if (rule === "string") {
if (typeof v !== "string" || v.length === 0) errors.push(key + ": expected non-empty string");
}
}
return errors.length ? { ok: false, errors } : { ok: true, errors: [] };
}
Two properties matter. Validation is total: any input produces a result, never an exception. And validation checks your contract, not just JSON-ness: {"priority": "urgent"} is valid JSON and an invalid task.
Layer 3: one bounded repair attempt
When validation fails, the cheapest effective repair is to resend the failure to the model: include the invalid output and the exact validation errors, and ask for corrected JSON only. Bound the loop (one or two attempts), then fail loudly to your caller.
function askForTask(mockModel, instruction) {
let messages = [
{ role: "system", content: "Reply with only a JSON object with keys "
+ "title (string) and priority (high, medium, or low)." },
{ role: "user", content: instruction }
];
for (let attempt = 1; attempt <= 2; attempt++) {
const content = mockModel(messages);
const parsed = extractJson(content);
if (parsed === null) {
messages.push({ role: "assistant", content });
messages.push({ role: "user", content: "That was not valid JSON. Reply with only the JSON object." });
continue;
}
const check = validateTask(parsed, TASK_SCHEMA);
if (check.ok) return { task: parsed, attempts: attempt };
messages.push({ role: "assistant", content });
messages.push({ role: "user", content: "Fix these problems and reply with only the JSON object: " + check.errors.join("; ") });
}
return { error: "invalid_output", attempts: 2 };
}
With a scripted mock whose first reply omits priority and whose second reply is valid, the loop returns the task on attempt 2. Trace it by hand: extraction succeeds both times, validation fails once, and the repair message carries the exact error forward.
Schema-valid is not business-valid
Passing validation means the shape is right, not that the content is true or appropriate. A task with priority: "high" and title "Delete the production database" is schema-valid. Downstream code must still apply business rules, and content from the model is untrusted input: treat it like user input when you render, store or execute it.
Where providers help, and where they do not
Most providers now offer a JSON or structured-output mode that constrains decoding toward valid JSON for a declared schema. Use it when available: it removes most extraction failures. It does not remove validation, because syntactic validity is not semantic validity, and it does not remove the finish-reason check, because a truncated JSON payload is still truncated. The layered pattern, extract, validate, bounded repair, stays valuable regardless of which provider features you adopt.
Continue with ai-engineering-streaming-and-abort to see how streaming changes where extraction and validation run. Tool arguments in ai-engineering-tool-calling need the same validate-before-execute discipline.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement extractJson(text): find the first { and the last }, slice that region, and JSON.parse it. Return null when there is no region or parsing throws. It must never throw.
starter.javascriptfunction extractJson(text) { // Find the first { and the last }, slice that region, JSON.parse it. // Return null when there is no region or parsing throws. Never throw. }Reveal the reference answer
reference.javascriptfunction extractJson(text) { const start = text.indexOf("{"); const end = text.lastIndexOf("}"); if (start === -1 || end <= start) return null; try { return JSON.parse(text.slice(start, end + 1)); } catch { return null; } } const reply = "Sure! Here is the JSON:\n```json\n{\"title\":\"Fix login\",\"priority\":\"high\"}\n```\nHope that helps!"; console.log(JSON.stringify(extractJson(reply)));Authored expected output: {"title":"Fix login","priority":"high"}
The input is a fenced block wrapped in prose. Slicing from the first { to the last } strips both, and the try/catch converts syntax errors into the null sentinel so callers handle failure as data.
Exercise 2Implement
Implement validateTask(obj, schema) where schema maps keys to either the string "string" (non-empty string required) or an array of allowed values. Return { ok: true, errors: [] } or { ok: false, errors } with one message per violated key. Must be total: no exceptions for null or malformed input.
starter.javascriptconst TASK_SCHEMA = { title: "string", priority: ["high", "medium", "low"] }; function validateTask(obj, schema) { // For each key in schema: // rule "string": value must be a non-empty string // rule array: value must be one of the array entries // Collect one error message per violated key, e.g. // "priority: expected one of high, medium, low" // Return { ok, errors }. Never throw. }Reveal the reference answer
reference.javascriptconst TASK_SCHEMA = { title: "string", priority: ["high", "medium", "low"] }; function validateTask(obj, schema) { const errors = []; for (const [key, rule] of Object.entries(schema)) { const v = obj ? obj[key] : undefined; if (Array.isArray(rule)) { if (!rule.includes(v)) errors.push(key + ": expected one of " + rule.join(", ")); } else if (rule === "string") { if (typeof v !== "string" || v.length === 0) errors.push(key + ": expected non-empty string"); } } return errors.length ? { ok: false, errors } : { ok: true, errors: [] }; } console.log(JSON.stringify(validateTask({ title: "Fix login", priority: "urgent" }, TASK_SCHEMA)));Authored expected output: {"ok":false,"errors":["priority: expected one of high, medium, low"]}
validateTask({ title: "Fix login", priority: "urgent" }, TASK_SCHEMA) fails only the priority rule. Total validators turn model misbehavior into data your code can branch on.
Exercise 3Predict
With the scripted mockModel in the starter code (first reply omits priority, second reply is complete), predict what askForTask returns, including the attempts field.
starter.javascriptfunction mockModel(messages) { // Scripted mock: the first call omits priority, later calls are complete. if (mockModel.calls === undefined) mockModel.calls = 0; mockModel.calls += 1; if (mockModel.calls === 1) { return "Here is the task:\n```json\n{\"title\":\"Fix login\"}\n```\nNote: I left priority out."; } return "{\"title\":\"Fix login\",\"priority\":\"high\"}"; } function askForTask(mockModel, instruction) { // Copy the repair loop from the lesson body: extract, validate, // on failure push the assistant reply plus a repair user message with // the exact errors, and stop after 2 attempts. }Reveal the reference answer
reference.javascriptfunction mockModel(messages) { if (mockModel.calls === undefined) mockModel.calls = 0; mockModel.calls += 1; if (mockModel.calls === 1) { return "Here is the task:\n```json\n{\"title\":\"Fix login\"}\n```\nNote: I left priority out."; } return "{\"title\":\"Fix login\",\"priority\":\"high\"}"; } function askForTask(mockModel, instruction) { let messages = [ { role: "system", content: "Reply with only a JSON object with keys " + "title (string) and priority (high, medium, or low)." }, { role: "user", content: instruction } ]; for (let attempt = 1; attempt <= 2; attempt++) { const content = mockModel(messages); const parsed = extractJson(content); if (parsed === null) { messages.push({ role: "assistant", content }); messages.push({ role: "user", content: "That was not valid JSON. Reply with only the JSON object." }); continue; } const check = validateTask(parsed, TASK_SCHEMA); if (check.ok) return { task: parsed, attempts: attempt }; messages.push({ role: "assistant", content }); messages.push({ role: "user", content: "Fix these problems and reply with only the JSON object: " + check.errors.join("; ") }); } return { error: "invalid_output", attempts: 2 }; } console.log(JSON.stringify(askForTask(mockModel, "Create a task for the login bug")));Authored expected output: {"task":{"title":"Fix login","priority":"high"},"attempts":2}
Attempt 1: extraction succeeds, validation fails on priority, and the loop pushes a repair message containing the exact error. Attempt 2: the scripted mock returns the complete object, validation passes, and the loop returns attempts 2.
Exercise 4Test
Write four assertions for validateTask: a valid task passes; a missing priority fails; an empty title fails; an invented priority value fails. Log PASS or FAIL for each.
starter.javascriptfunction check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } // Write four assertions against validateTask(obj, TASK_SCHEMA): // 1. A complete valid task passes (ok === true). // 2. A task missing priority fails. // 3. A task with an empty-string title fails. // 4. A task with priority "urgent" (not in the enum) fails.Reveal the reference answer
reference.javascriptfunction check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } check("valid task passes", validateTask({ title: "Fix login", priority: "high" }, TASK_SCHEMA).ok === true); check("missing priority fails", validateTask({ title: "Fix login" }, TASK_SCHEMA).ok === false); check("empty title fails", validateTask({ title: "", priority: "high" }, TASK_SCHEMA).ok === false); check("invented priority fails", validateTask({ title: "Fix login", priority: "urgent" }, TASK_SCHEMA).ok === false);Authored expected output: PASS PASS PASS PASS
The four cases cover the contract: shape, required fields, non-empty strings and enum membership. These are deterministic graders of the same kind lesson 13 reuses for model evaluation.
Exercise 5Explain
Knowledge check: what does a provider's JSON mode guarantee, and what does it still not guarantee?
starter.text// Choose the correct option.Reveal the reference answer
reference.textJSON mode constrains decoding toward syntactically valid JSON for the declared schema. It does not guarantee business validity: values can be wrong, fabricated or semantically inappropriate, and truncated output can still break parsing, so extraction and validation remain mandatory.Authored expected output: Syntactic JSON validity only; semantic and business validity still require validation
Structured-output features remove a failure class, not the contract. The extract, validate, repair pattern stays in place.
Common misconceptions
#- Myth: the model knows your schema without being told. Fact: a schema is a request you must state precisely, and even then it is not enforced; validate every reply.
- Myth: JSON mode makes validation unnecessary. Fact: JSON mode targets syntactic validity; wrong types, missing fields and invented enum values still pass JSON parsing.
- Myth: retrying with the same prompt fixes parsing failures. Fact: retries work when they carry new information, the exact validation errors; identical retries mostly reproduce identical failures.
Follow-up practice
#- ai-engineering-streaming-and-abort
- ai-engineering-tool-calling
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.