Skip to content
Visual explainer 3h to learn 5 steps

Request and validate structured output from a model

Request output that matches a JSON schema, validate it in code and handle missing values and refusals without crashing.

By Invicly Tech, , in Prompt Engineering and Vibe Coding. About 10 minutes to read.

Topic 4 of 29

In short

When code reads a model's answer, free text is risky. Structured output means the model returns data that matches a JSON schema, a description of the fields and their types. Your code still validates the result, because a valid shape does not mean the values are right, and refusals or missing values must not crash the program.

Think of it like this: A schema is like a paper form with boxes: the model fills the boxes, and your code checks the form before using it.

Explained simply

When a person reads a model's answer, free text is fine. When a program reads it, free text is a problem. Your code needs to know where the category is, where the date is and whether a field is missing. Structured output solves this by asking the model for data in a fixed shape, usually JSON.

The shape is described with a JSON schema. A schema lists the fields, their types (text, number, true or false), which fields are required and which values are allowed. Many model APIs can enforce a schema, so the reply is built to match it. Check your provider's current docs for the exact setting name.

Even then, your code should validate the result. Validation means checking the data against the rules before using it. In TypeScript, a popular tool is Zod. A schema guarantees the shape at best; it cannot guarantee that the category is the right one.

Plan for trouble. The model may refuse a request, run out of space and cut the answer short, or leave a value empty. Decide in advance what your code does in each case: retry once, use a safe default or send the item to a person.

Press Play on a diagram to walk through it one step at a time.

FlowRequest, validate, recover
  1. 1
    Define schema

    Fields, types, allowed values

  2. 2
    Call the model

    Ask for output in that schema

  3. 3
    Parse JSON

    Turn text into an object

  4. 4
    Validate

    Check with Zod or similar

  5. 5
    Handle failure

    Retry once, then fall back

CompareAsking nicely versus an API guarantee
Prompt says 'reply in JSON'
  • Works most of the time
  • May add text around the JSON
  • Fields can be missing
  • You must always validate
API structured output with a schema
  • Provider constrains the output to the schema
  • Fewer parse errors
  • Refusals are reported separately
  • You still validate the values
MapOutcomes your code must handle
Model reply
  • Valid data
    • Use it
  • Valid but a field is null
    • Show unknown
    • Ask a person
  • Refusal
    • Show a message
    • Do not retry the same request
  • Invalid or cut off
    • Retry once with the error
    • Then fall back

In depth

Describing the shape with a JSON schema

A JSON schema is itself a JSON document. It says the reply is an object, lists its properties and gives each a type. You can limit a text field to a fixed set of values with enum, and mark fields as required. Keep schemas small and clear, with field names that explain themselves, such as customer_sentiment instead of cs.

Short descriptions on fields help the model fill them well. For values that may not exist, use an explicit way to say so, such as null or a field called found. This is better than letting the model invent a value to fill the box.

  • type: object, with named properties
  • enum for a fixed list of values
  • required lists the fields that must appear
  • Use null or a flag for unknown values

Validating with Zod

Zod lets you write the schema in TypeScript, then call safeParse on the data. It returns either the clean, typed data or a list of problems, and it does not throw. That makes it easy to branch: use the data, or handle the failure.

Parse in two steps. First JSON.parse the text inside a try block, because the reply may not be JSON at all. Then run Zod. Log the failure reason with a request id so you can see patterns later, but do not log private user data.

FlowTwo-step validation in code
  1. Step 1
    Receive text

    Model reply as a string

  2. Step 2
    JSON.parse in try

    Catch non-JSON

  3. Step 3
    Zod safeParse

    Check types and values

  4. Step 4
    Use or recover

    Typed data, or the failure path

Missing values, refusals and cut-off replies

A refusal is a valid reply that holds no data, such as when the model declines an unsafe request. Provider APIs usually report it separately from the content, for example in a refusal field, so check for it before you read data fields. A cut-off reply happens when the output hits the token limit. The JSON is then incomplete and will not parse.

Treat all three as normal events. Return a clear result such as status: refused or status: incomplete, and let the calling code decide what to do. Do not fill gaps with made-up defaults that look like real data.

  • Check for a refusal before reading fields
  • Check why the reply stopped
  • Return a clear status, not a guess
  • Set the output limit high enough for the schema

UI formatting versus an API guarantee

In a chat window you can say 'answer as a table' and get a nicely drawn table. That is formatting for human eyes, and the layout can change between runs. It is not a promise about field names or types.

An API feature that enforces a schema is a stronger promise: the reply is constrained to match the shape you gave. Still, the promise covers the shape, not the truth. A valid category field can hold the wrong category. So you keep validating and you keep a test set to measure accuracy.

CompareWhat each approach gives you
Chat formatting
  • Good for people
  • Layout may vary
  • No type guarantee
Schema enforced by API
  • Fields and types match
  • Parse errors are rare
  • Values can still be wrong

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Describe the shape with a JSON schema~35m
  2. 2
    Validate results with Zod~35m
  3. 3
    Handle missing values and refusals~35m
  4. 4
    Tell UI formatting from API guarantees~35m
  5. 5
    Retry or fall back on invalid output~35m

Key points

  • Describe the shape with a JSON schema: field names, types, required fields and allowed values.
  • Validate in code every time. A library such as Zod gives clear errors instead of crashes.
  • Plan for missing values (use null or a flag) and for refusals, which are not valid data.
  • Telling a chat window to format a table is UI formatting. A schema enforced by the API is a stronger guarantee.
  • On invalid output, retry once with the error message, then fall back to a safe default or a human.

Key terms

Tap a card to flip it. 0/5 known

Examples

ts
import { z } from "zod";
const Ticket = z.object({
  category: z.enum(["billing", "bug", "other"]),
  urgent: z.boolean(),
  summary: z.string().max(200),
});

export function parseTicket(raw: string) {
  try {
    const result = Ticket.safeParse(JSON.parse(raw));
    return result.success ? result.data : null;
  } catch {
    return null; // not JSON at all
  }
}

Validate a model reply with Zod and fail safely.

A ticket classifier schema

You want each support ticket turned into data. Step 1: write the schema with category, urgent and summary. Step 2: give the schema to the API and ask for that output. Step 3: validate the reply. Step 4: if the category is outside the list, Zod fails and you retry once. Below is the schema as JSON.

json
{
  "type": "object",
  "properties": {
    "category": { "type": "string", "enum": ["billing", "bug", "other"] },
    "urgent": { "type": "boolean" },
    "summary": { "type": "string", "maxLength": 200 }
  },
  "required": ["category", "urgent", "summary"],
  "additionalProperties": false
}

Retry once, then fall back

A reply fails validation. Step 1: send one more request that includes the error message, such as 'category must be billing, bug or other'. Step 2: validate again. Step 3: if it still fails, stop. Mark the ticket as needs_review and send it to a person. Never loop without a limit.

ts
async function classify(text: string) {
  for (let attempt = 0; attempt < 2; attempt++) {
    const raw = await callModel(text); // your API call
    const parsed = parseTicket(raw);   // Zod safeParse inside
    if (parsed) return { status: "ok", data: parsed };
  }
  return { status: "needs_review" };
}

Quick reference

  • JSON schema lists fields, types, required fields and allowed values
  • Keep schemas small, with clear field names and short descriptions
  • Use null or a found flag for values that may not exist
  • JSON.parse inside try, then Zod safeParse
  • Check for a refusal before reading data fields
  • Allow enough output tokens or the JSON may be cut off
  • Retry once with the error, then fall back to a person

Common mistakes

  • Trusting the schema and skipping validation. The shape can be right while the value is wrong.
  • Crashing on a refusal because the code assumed every reply holds the data fields.
  • Retrying in a loop with no limit, which wastes money and time.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does a schema guarantee when the API enforces it?

Question 2

2Why parse in two steps, JSON.parse then Zod?

Question 3

3How should code treat a refusal?

Question 4

4What is a safe way to represent an unknown date?

Question 5

5A chat window draws a neat table when asked. What is this?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a JSON schema for a review with rating (1 to 5), a title and a boolean recommend field. Mark all as required.

  2. Exercise 2medium

    Write the same shape in Zod and test it with one good and one bad sample object. Print the outcome.

  3. Exercise 3hard

    Design a wrapper that returns status ok, refused, incomplete or needs_review. List what triggers each status and what the app does next.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is asking for JSON in the prompt enough?
It often works, but replies can include extra text or miss fields. Use the API's structured output feature where it exists, and always validate.
Do I need Zod specifically?
No. Any validator works. Zod is popular in TypeScript because one schema gives both validation and types.
What if the model refuses a harmless request?
Treat it as a prompt problem. Make the request clearer, add context about the legitimate use and test again, but do not hide real refusals.

Go deeper

ShareXLinkedInWhatsApp