Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 11/ 160
01. LLM Fundamentals

Structured Outputs

JSON schemas, constrained decoding, and reliable tool/function argument generation.

IntermediateJSON Schema · Constrained Decode3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Instead of letting the model write whatever it likes, you give it a template and it can only fill in the blanks.

Think of it like…

A paper form versus a blank page: on a form, each box accepts only the right kind of entry, so the clerk processing it never has to interpret handwriting. Constrained decoding turns the model's blank page into a form it cannot fill in wrongly.

Where you’ve seen it

An expense-processing service extracts {vendor, date, total, currency, line_items[]} from receipts. With prompt-only JSON, about 3 percent of responses fail to parse or use the wrong key names, triggering retries. Switching to schema-constrained outputs makes every response parse and match the schema; the team still validates business rules (total equals the sum of line items) and routes mismatches to human review.

Words you’ll hear

JSON Schema
A standard description of allowed fields, types, enums and required keys.
JSON mode
Guarantees syntactically valid JSON, but not any particular structure.
Constrained decoding
Masks tokens that would violate the schema at each generation step.
Function calling
The model outputs a function name and schema-valid arguments for your code to run.

Visual diagram

Loading interactive diagram

Theory & deep dive

Levels of reliability

Prompting alone ("respond with JSON like this") works most of the time and fails unpredictably: extra prose, trailing commas, missing keys. JSON mode removes syntax errors but still lets the model choose the keys. Schema-constrained decoding, offered as structured outputs by major providers and implemented in open-source tools such as Outlines, XGrammar and llama.cpp grammars, compiles the schema into a grammar and zeroes the probability of tokens that would break it, so the response always matches the declared structure.

Function calling is the same idea applied to tools: you describe functions with JSON schemas, and the model returns a call (name and arguments) that your code executes. Strict modes make arguments conform to the schema. Either way, you still parse and validate in your own code, because constrained output can be well-formed and wrong.

A schema that closes the loopholes

{"type":"object","properties":{"category":{"type":"string","enum":["billing","refund","tech"]},"confidence":{"type":"number","minimum":0,"maximum":1}},"required":["category","confidence"],"additionalProperties":false} forces a known category and a bounded number.

Key takeaway: Prompt < JSON mode < schema-constrained decoding for guaranteeing shape.

Design tips and what constraints don't solve

Design schemas for the model as much as for your code: use descriptive field names and short descriptions, enums for closed sets, required fields, additionalProperties false, and put a reasoning or notes field before the final answer fields if you want the model to "think" first, since fields are generated in order. Keep schemas modest; very deep or huge schemas increase latency, hit provider limits and can reduce accuracy. Allow a null or an "unknown" option so the model isn't forced to invent values.

Constraints guarantee structure, not truth: a perfectly formed {"total": 99999} may still be wrong. Validate semantically (ranges, cross-field sums, dates, database lookups), keep a retry or human-review path, and handle edge cases such as refusals, truncation at max tokens (which can cut JSON short) and unsupported schema features. Measure field-level accuracy against labelled examples, not just parse rate.

Let the model say "I don't know"

Make invoice_date a nullable string with the description "null if not present on the document". Without it, a schema that requires a date pushes the model to guess one on receipts that have none.

Key takeaway: Allow nulls, order fields sensibly, and validate meaning after validating shape.

How it works, step by step

Step 1 of 4
Design

1. Define the schema

Write a JSON Schema with typed fields, enums, required keys, descriptions and additionalProperties false.

category: enum[billing, refund, tech]
Key numbers at this step
Closed sets
use enums

When to use it & trade-offs

What it is

Structured outputs make a model return data that conforms to a schema, typically JSON Schema, so code can parse it without guessing. Approaches range from asking nicely in the prompt, to JSON mode (valid JSON, but any shape), to schema-constrained decoding, where the sampler is only allowed to emit tokens that keep the output valid against the schema. Function (tool) calling uses the same machinery to generate arguments for your functions.

Why it matters: Free-form text breaks pipelines: a missing quote, an extra explanation before the JSON, a field renamed on a whim. Reliable structure is what lets LLMs sit inside software, from extracting invoice fields to routing agent tool calls. Knowing the difference between "valid JSON" and "valid against my schema", and what constrained decoding does and doesn't guarantee, prevents a class of production incidents.

When to reach for it

  • Extracting fields from documents and emails
  • Generating tool and function arguments for agents
  • Classification with a closed label set

When to avoid or be careful

  • Parsing free text with regexes when structure can be enforced
  • Required fields with no way to say "not present"
  • Treating a schema-valid response as verified

Ways to get structured data from an LLM

Prompt-only JSON
Best for: Quick prototypes

Strengths: Works anywhere; no API features needed.

Watch out: Unreliable; needs repair and retries.

JSON mode
Best for: Guaranteeing parseable JSON

Strengths: No syntax errors.

Watch out: Keys and types can still be wrong.

Schema-constrained / strict function calling
Best for: Production extraction and tool arguments

Strengths: Output always matches the schema.

Watch out: Schema limits, slight first-request latency; values can still be wrong.

Interview signals & numbers to know

When this topic comes up

  • “The model sometimes returns invalid JSON”
  • “How do we make function calling reliable?”
  • “What's the difference between JSON mode and structured outputs?”
  • Constrained decoding
  • Extraction pipelines

Benchmarks & rules of thumb

3% → ~0% -
parse-failure rate in the receipt example
3 levels -
prompt, JSON mode, schema-constrained
additionalProperties: false -
closes extra-key loopholes

Common mistakes & follow-ups

Common interview mistakes

  • Declaring a field required when the source often lacks it, so the model fabricates a value.
  • Not handling max-token truncation, which cuts the JSON off before it closes.
  • Reporting 100% parse success as accuracy and never checking field values.

Likely interviewer follow-ups

  • How does constrained decoding guarantee valid output?
  • How would you evaluate an extraction pipeline?
  • How do structured outputs relate to function calling?
Interview tip: Separate "valid shape" from "correct values". Saying you'd enforce the first with the schema and measure the second with labelled data shows production maturity.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Structured Outputs with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Reasoning Models
Next topic
Prompt Caching