2. Structured Output
Getting machines to parse what models produce
A language model that writes beautiful prose is impressive. A language model that returns valid JSON every single time is useful. The gap between "interesting demo" and "production system" is almost always about structured output: getting the model to produce data in a format that downstream code can parse, validate, and act on without brittle string matching.
This article covers the techniques — from simple prompt tricks to formal schema enforcement — that make LLM output reliably machine-readable.
The Problem
LLMs generate text token by token. They have no built-in concept of "this must be valid JSON" or "this field is required." Left to their own devices, they'll produce output that looks like JSON but contains trailing commas, unquoted keys, or commentary mixed in with the data:
Here's the JSON you requested:
{
name: "Alice", // unquoted key
"age": 30,
"hobbies": ["reading", "hiking",] // trailing comma
}
Let me know if you need anything else!
Every failure mode here is a natural consequence of how language models work: they generate text that's statistically likely given the context, and "helpful commentary around JSON" is extremely common in training data.
Prompt-Level Techniques
The simplest approach: tell the model exactly what you want and exactly what to avoid.
Format specification
Extract the person's name, age, and city from the following text.
Return ONLY a JSON object with keys "name", "age", "city".
Do not include any text before or after the JSON.
Do not include comments in the JSON.
Text: "Maria is a 28-year-old software engineer living in Berlin."
This works surprisingly well — maybe 90-95% of the time with modern models. The remaining 5-10% is the problem.
Template prompting
Provide the exact shape of the expected output:
Fill in the values in this JSON template based on the text below.
Replace the placeholder values but keep the structure exactly as shown.
Template:
{
"name": "<string>",
"age": <integer>,
"city": "<string>"
}
Template prompting is more reliable than freeform generation because the model can attend to the template structure when producing output. It's pattern completion rather than generation from scratch.
XML/delimiter wrapping
Ask the model to wrap its output in delimiters:
Analyze the sentiment of the following review.
<analysis>
{
"sentiment": "positive" | "negative" | "neutral",
"confidence": 0.0 to 1.0,
"key_phrases": ["list", "of", "phrases"]
}
</analysis>
Your code can then extract everything between the delimiters, ignoring any commentary the model adds before or after. This is robust because even when models add extra text, they rarely insert it inside properly delimited blocks.
JSON Mode
Most modern LLM APIs now offer a dedicated JSON mode that constrains the model's output at the decoding level. When enabled, the model is guaranteed to produce valid JSON.
The mechanism works by modifying the token sampling process. At each step, the decoder
masks out tokens that would produce invalid JSON given what's been generated so far. If
the model has generated {"name": "Ali, the only tokens with non-zero probability are
those that continue a valid JSON string — not a newline followed by prose.
How to use it (typical API):
const response = await client.messages.create({
model: "claude-sonnet-4-6-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
response_format: { type: "json_object" }
});
// response.content is guaranteed to be valid JSON
const data = JSON.parse(response.content[0].text);
JSON mode guarantees syntax, not semantics. The model will produce valid JSON, but it might have the wrong keys, wrong types, or missing fields. You still need validation.
Schema-Constrained Generation
The next level up: provide a JSON Schema that defines exactly which fields are required, what types they must be, and what values are allowed.
const response = await client.messages.create({
model: "claude-sonnet-4-6-20250514",
max_tokens: 1024,
messages: [{ role: "user", content: "Extract info from: Maria, 28, Berlin" }],
response_format: {
type: "json_schema",
json_schema: {
name: "person_info",
schema: {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
city: { type: "string" }
},
required: ["name", "age", "city"],
additionalProperties: false
}
}
}
});
This is the gold standard for structured output. The schema is enforced during decoding, so the output is both syntactically valid JSON AND conformant to your schema. No post-processing required.
Schema support varies by provider. Some support full JSON Schema draft 2020-12, others support a subset. Common limitations:
- No
$refor recursive schemas - Limited
oneOf/anyOfsupport - No custom formats or patterns
- Depth limits on nesting
Function Calling / Tool Use
Function calling is structured output's killer application. Instead of asking the model to produce JSON that you then interpret, you define functions the model can call, and it produces structured arguments for those functions.
const tools = [{
name: "search_codebase",
description: "Search for files matching a pattern",
input_schema: {
type: "object",
properties: {
pattern: {
type: "string",
description: "Glob pattern like '**/*.ts' or 'src/**/test.*'"
},
content_match: {
type: "string",
description: "Optional regex to match within files"
}
},
required: ["pattern"]
}
}];
When the model decides it needs to search the codebase, it doesn't generate prose like "I'll look for TypeScript files" — it produces a structured tool call:
{
"name": "search_codebase",
"arguments": {
"pattern": "**/*.ts",
"content_match": "export function"
}
}
This is how every modern coding assistant works. The model doesn't directly edit files or run commands — it produces structured tool calls that the host application executes. We'll go much deeper on this pattern in the next article on tool use.
Validation and Retry
Even with schema constraints, you should validate output in production. Schemas catch type errors but can't enforce semantic correctness (e.g., "age must be positive" or "city must be a real place").
A simple but effective pattern:
import { z } from 'zod';
const PersonSchema = z.object({
name: z.string().min(1),
age: z.number().int().positive().max(150),
city: z.string().min(1)
});
async function extractPerson(text: string, retries = 2): Promise<Person> {
for (let i = 0; i <= retries; i++) {
const response = await callLLM(text);
const result = PersonSchema.safeParse(JSON.parse(response));
if (result.success) return result.data;
// Feed the error back to the model
text = `${text}\n\nYour previous response had errors:\n${
result.error.message
}\n\nPlease fix and try again.`;
}
throw new Error('Failed to extract valid person data');
}
This "generate → validate → retry with error feedback" loop is a fundamental pattern in LLM engineering. The model is remarkably good at fixing its own mistakes when you show it the specific validation error.
Choosing the Right Technique
| Situation | Technique |
|---|---|
| Quick scripts, prototyping | Prompt-level formatting |
| Simple JSON extraction | JSON mode |
| Production APIs with strict contracts | Schema-constrained generation |
| Models calling external systems | Function calling / tool use |
| Complex validation logic | Schema + Zod/Pydantic + retry loop |
Start with the simplest technique that meets your reliability requirements. Prompt-level formatting is fine for a personal script. A production API serving thousands of users needs schema enforcement and validation.
Output Parsing Libraries
Several libraries wrap these patterns into convenient abstractions:
- Zod (TypeScript) — schema definition and validation, widely used with LLM tooling
- Pydantic (Python) — type-safe models that can generate JSON schemas
- Instructor — patches LLM clients to return validated Pydantic/Zod objects directly
- LangChain output parsers — structured output with automatic retry on parse failure
The pattern is always the same: define a schema, pass it to the model (via system prompt, JSON mode, or function calling), validate the response, retry if needed.
When Structured Output Fails
Even with all these techniques, some failure modes persist:
Hallucinated values. The model produces valid JSON with the right types, but the content is fabricated. Schema constraints can't prevent this — you need application-level checks or retrieval-augmented generation.
Excessive nesting. Complex schemas with deep nesting and many optional fields increase the chance of errors. Flatten your schemas where possible.
Token limits. Long structured outputs can get truncated mid-JSON. Set max_tokens
high enough for the expected output, and consider streaming with incremental JSON parsing
for very large responses.
Enum drift. The model generates values that are close to but not exactly matching your
enum values ("Positive" instead of "positive"). Use JSON Schema enum constraints or
post-process with case normalization.
Try It — JSON Validation Pipeline
Paste raw LLM output below (or load an example) and see the full validation pipeline in action: extract JSON from commentary, parse it, and validate against the schema.
Target Schema
LLM Output
What's Next
Structured output turns LLMs from text generators into components you can wire into software systems. The most powerful application of this is tool use — giving models the ability to call functions, read files, query databases, and take actions in the real world. That's the next article.