Structured output with LLMs is the difference between a demo that works on your laptop and a feature that survives real users. A model that answers in free-form prose is fine for a chat window. The moment your code has to read that answer, parse a field out of it, and store it in a database, free-form text becomes a liability. One extra sentence, one missing quote mark, one field renamed on a whim, and your parser throws an error at 2 a.m.
The fix is to tell the model exactly what shape its answer must take, and then check that shape before you trust it. That means JSON Schema, function calling, and a validation step that treats the model like any other untrusted input.
Structured Output with LLMs: Why Plain Text Breaks Your App
Ask a model to extract an invoice total and it might reply 42.50, or The total is $42.50., or {"total": 42.5}, or a three-paragraph explanation that happens to contain the number. Your code cannot rely on any of those.
Structured output removes the guesswork. You define a schema, the model is constrained to produce output that matches it, and your code receives a typed object instead of a string to scrape. The result is boring in the best way: the same input shape every time, ready for JSON.parse without a regex in sight. If you are still deciding whether your feature needs this at all, the earlier guide on getting reliable JSON from LLMs covers the basic case and when plain text is still fine.
JSON Schema for LLM Output: The Basics
A JSON Schema is a contract. It describes the fields, their types, which ones are required, and what values are allowed. Most LLM providers accept a schema alongside your prompt and constrain the model’s output to match it. JSON schema for LLM output works best when the schema is small and strict.
Keep these rules in mind when you write one:
- Use few, flat fields. Deep nesting invites mistakes. If you can flatten a structure, flatten it.
- Mark required fields explicitly. A field the model treats as optional is a field your code must handle as missing.
- Use enums for fixed choices. A
statusfield with["open", "closed", "pending"]beats a free string every time. - Describe each field in plain language. The
descriptionproperty is read by the model, so write it like instructions, not documentation.
A schema for extracting a task from a message might have just three fields: title (string, required), due_date (string in date format, optional), and priority (enum of low, medium, high, required). That is enough to build on. Resist the urge to add ten more fields “just in case” — every extra field is another chance for the model to invent data.
Function Calling vs JSON Mode: Which One to Use
Most providers offer two ways to get structured output: JSON mode and function calling. They overlap, but they solve different problems, and picking the wrong one is a common source of llm validation errors later.
| Approach | What it does | Best for | Watch out for |
|---|---|---|---|
| JSON mode | Forces the whole reply to be valid JSON matching a schema | Extraction, classification, summarization | Model can still pick wrong values |
| Function calling | Model picks a function and fills its arguments | Actions, tool use, multi-step agents | Arguments can be wrong even when the call looks right |
| Prompt-only JSON | You ask for JSON in the prompt and parse the reply | Providers without schema support | Formatting drifts; needs retry logic |
Use JSON mode when you need data back and nothing else. Use function calling when the model should trigger an action, like creating a ticket or looking up a record, and the arguments are the payload. Structured output function calling combines both ideas: the function definition is itself a schema, so the arguments arrive typed and validated. That combination is the default choice for most production features. Remember that function calling does not run your function. The model only returns a name and arguments. Your code decides whether to execute it, and that decision point is where validation belongs.
Common LLM Validation Errors and How to Fix Them
Even with a schema, output fails. The model is a text generator with a constraint on top, not a database. Expect these errors and handle each one deliberately.
Missing required fields
The model omits a field your schema marked required, usually because the source text genuinely lacks that information. The fix is not a stricter prompt. It is a schema that matches reality: make the field nullable, give it a default in your code, or add an explicit “unknown” enum value. A schema that demands data the input cannot supply will fail forever.
Wrong types
A number arrives as a string (“42” instead of 42), a date arrives in the wrong format, or a boolean arrives as “yes”. Coerce where the conversion is safe, such as parsing a numeric string, and reject where it is not. Log every coercion. If one field needs coercing in a quarter of your calls, fix the schema description or the prompt instead of papering over it in code.
Extra fields
Models add fields you never asked for. Most validators ignore unknown fields by default, which is fine, but do not pass the raw object straight to your database. Strip unknown keys at the boundary.
Enum violations
The model returns “urgent” when your enum only allows low, medium, and high. This usually means your enum is missing a real category your users need. Add the value, or map synonyms to allowed values in code.
Truncated output
Long structured responses can hit the token limit mid-object, leaving you with invalid JSON. Keep schemas small, ask for short field values, and set a generous output token limit. When truncation happens, the only reliable recovery is to retry with a shorter request, not to patch the broken JSON by hand.
None of these errors means structured output failed as an approach. They mean your contract and your data disagree somewhere, and the validator found the disagreement before your users did. That is the system working. The same discipline applies to the rest of your feature: the guide to testing an AI feature before shipping it shows how to build an eval set that catches these failures before production does.
Build a Validation Pipeline, Not a Single Check
A single JSON.parse in a try-catch is not a pipeline. Production code needs layers: parse the raw string (one repair pass for stray markdown fences, then fail loudly), validate the object against the schema with a real validator and log the exact errors, retry fixable errors by sending the error message back to the model (cap it at two retries), and fall back to a safe default if retries fail — ask the user, queue the item for review, or skip the field. Never silently store bad data. Finally, monitor failure rates per schema, so a spike tells you within the hour that a prompt or model changed.
Function calling validation belongs in the same pipeline. Validate the arguments against the function schema before you run anything, and never let a model-invented argument reach a destructive operation. A function that deletes records should require a confirmation step no matter how confident the model sounds. Guardrails and grounding matter here too: the guide on grounding, citations, and guardrails covers the wider set of checks that keep model output safe to act on.
Design Schemas for the Model You Actually Use
Not every provider supports every JSON Schema feature. Some ignore pattern, some cap the number of properties, some handle nested objects poorly. Check what your provider actually enforces, and test with real calls before you design a clever schema. Test schemas the way you test code: build a small set of inputs covering the easy case, the missing-data case, the ambiguous case, and the adversarial case, then run each one and inspect the output by hand. Ten careful examples beat a hundred random ones, and rerun the set whenever the schema changes.
Also worth remembering: the model reads your field descriptions, so write them for the model, not for your API docs. “The customer’s full name as written in the message” gets better results than “name”. If you are publishing the underlying API as well, keep the two audiences separate: the schema description serves the model, while your API documentation for AI agents serves the developers and tools that call it.
Start Small, Then Grow the Schema
Pick one feature this week. Write the smallest schema that could work, add the validation pipeline above, and run your eval set. Then ship it, watch the failure rate for a few days, and only then decide whether the schema needs to grow. Structured output with LLMs rewards that kind of patience: a small contract you can trust beats a large one you keep patching.