Skip to content
FORGENO ADS GAMESUnlock all $8

Building AI-Powered Apps · Unit 4 of 8

Unit 4: Structured output and validation

Why app features need structured output, defining schemas in code, the validate-then-act pipeline with business rules, and showing model output safely.

Opens the first lesson of this unit in Building AI-Powered Apps. Every lesson is open from the start.

Lesson 1: Why apps need structured output

Goal: Choose structured output for features that feed code, and know what JSON modes guarantee.

When a model's output feeds your code, such as filling a form, saving to a database or deciding which screen to show, free text is fragile. Ask for structured output, usually JSON matching a schema, so your code can read the fields reliably.

App featureStructured output
Support ticket triage{"category": ..., "priority": ..., "summary": ...}
Details from a booking email{"name": ..., "date": ..., "guests": ...}
Product listing generator{"title": ..., "bullets": [...], "tags": [...]}
Choosing the next step{"action": "answer" | "ask_question" | "handoff"}

Many providers offer a structured output or JSON mode that constrains the model to produce valid JSON, sometimes matching a schema you supply. Use it when it is available. It guarantees the shape, not the truth: a category can still be wrong, and a field can contain a confident invention. That is why the next lessons validate values and business rules too.

Worked example: free text breaks a feature

  1. A booking app asks the model how many guests and on what date. It replies: "Looks like 4 people on the 12th!"
  2. The code that reads it fails on "the 12th" (which month?) and on the friendly wording, and the booking is lost.
  3. With a schema, {"guests": 4, "date": "2026-12-12"} parses every time, and a missing month becomes null instead of a guess.

If code reads it, ask for structure.

Structured output
Model output in a fixed, machine-readable shape that code can rely on.
JSON mode
A provider feature that constrains a model to produce valid JSON, sometimes matching a schema.

Remember: If code reads the output, ask for JSON with a schema. JSON modes guarantee shape, not truth.

Lesson 2: Schemas in code

Goal: Read and design a JSON Schema with types, enums, patterns and null.

A schema defines what valid output looks like: field names, types, which fields are required, allowed values and limits. In code you usually define it once and use it twice: to tell the model what to produce, and to validate what comes back.

{
  "type": "object",
  "required": ["category", "priority", "summary"],
  "additionalProperties": false,
  "properties": {
    "category": { "enum": ["billing", "delivery", "product", "other"] },
    "priority": { "enum": ["low", "normal", "urgent"] },
    "summary":  { "type": "string", "maxLength": 140 },
    "order_id": { "type": ["string", "null"], "pattern": "^[0-9]{4,6}$" }
  }
}

Read it line by line: an object with three required fields and no extra fields allowed; category and priority limited to fixed lists (enums); summary a string of at most 140 characters; and order_id either null or a string of 4 to 6 digits. Most languages have schema libraries that turn a definition like this into a validator with one line of code.

Design tips: prefer enums to free text wherever you can; make "missing" explicit with null rather than an empty string; keep schemas small, since every field is another chance for an error; and give fields names the model will understand, like "delivery_date", not "dd".

JSON Schema
A standard format for describing what valid JSON looks like.
additionalProperties
A JSON Schema setting that, when false, rejects fields not listed in the schema.
Pattern
A rule, written as a regular expression, that a string must match.

Remember: Required fields, enums, limits, null for missing, no extra fields. One schema to prompt and to validate.

Lesson 3: Validate, then act

Goal: Apply the parse, schema, business-rule and act-or-escalate pipeline.

Every model output that drives code goes through the same pipeline before anything happens.

  1. Parse: is it valid JSON at all?
  2. Validate the schema: the right fields, types and allowed values?
  3. Check business rules: does it make sense for this user and this situation? Is the refund no larger than the order total? Does the order belong to this customer?
  4. Act or escalate: only now update the database, call a service or show the result. On failure, retry once with the error, fall back to a safe default, or hand over to a person.

Hands-on lab in the room: Validate-then-act pipeline. Run eight simulated model outputs through a validation pipeline, switching each check on or off. See exactly which bad outputs slip through each gap.

Worked example: a refund that passed the schema

  1. Output: {"action": "refund", "order_id": "5512", "amount": 480}. Valid JSON, and it matches the schema.
  2. Business rule: order 5512 totals 48 dollars. A refund of 480 is ten times the order.
  3. The rule check catches it and sends it to a person, who spots a misplaced decimal point in the customer's email.

Schemas check shape. Business rules check sense. You need both.

Business rule
A check that an output makes sense for the business, such as a refund within the order total.
Fallback
A safe default action used when an output fails validation.

Remember: Parse → schema → business rules → act or escalate. Nothing acts on unvalidated output.

Lesson 4: Showing model output safely

Goal: Treat model output as untrusted and render it without XSS or injection.

Treat model output like any other untrusted input. It may contain text that came from users, documents or web pages, including text designed to attack your app.

RiskWhat happensDefense
Cross-site scripting (XSS)Output containing HTML or script is inserted into the page as HTML and runs in the user's browserInsert it as text (for example with textContent), or sanitize it with a trusted library
Malicious linksA reply contains a link to a phishing site, perhaps planted in a documentAllow only links to domains you trust, or show links as plain text
Injection into other systemsOutput is pasted into a database query or a shell commandNever build queries or commands by joining strings; use parameterized queries
Running generated codeCode the model wrote is executed on your serverNever run it outside a locked-down sandbox with no access to secrets
// Unsafe: if the reply contains <img src=x onerror=...>, that code runs.
// box.innerHTML = reply;

// Safe: the reply is shown as text, whatever it contains.
box.textContent = reply;

If you render markdown from the model (bold text, lists, links), use a markdown library that escapes HTML and lets you restrict links. And remember that model output can be wrong as well as unsafe: show sources where you can, and label AI-generated text so users know what they are reading.

Untrusted input
Any data your app did not create itself, including model output, which must be handled defensively.
Cross-site scripting (XSS)
An attack in which injected script runs in another user's browser.
Parameterized query
A database query where values are passed separately from the query text, so they cannot change the query.

Remember: Model output is untrusted: show it as text, allow only trusted links, parameterize queries, never run its code unsandboxed.

Practise it in Building AI-Powered Apps

Each lesson ends with three questions that check you can use the idea, not just recognise it. Wrong answers explain why and come back in Review. The unit ends with a 6-question quiz; pass it with 80% or more to master the unit. Hands-on lab: Validate-then-act pipeline.

Every lesson is free: no ads, no lives and no paywall.