Structured Outputs & JSON Schema for LLMs: Eliminating Hallucinations in AI APIs
Asking an LLM to 'please reply in valid JSON' breaks production pipelines. Learn how schema-constrained decoding and strict validation guarantee parseable outputs.

How Constrained Decoding Prevents Syntax Errors
Instead of hoping the model remembers to close every brace and avoid ```json markdown fences, modern LLM APIs compile your JSON Schema into a context-free grammar (CFG) state machine. At every decoding step, invalid tokens are masked to zero probability—making malformed JSON structurally impossible.
Designing High-Accuracy Schemas with Zod or Pydantic
Field ordering inside a JSON Schema directly affects reasoning quality because autoregressive models generate left-to-right. Place a brief `reasoning` string field *before* `category` or `score` so the model thinks before committing to a label.
import { z } from "zod";
export const TicketTriageSchema = z.object({
reasoning: z.string().describe("1-2 sentence justification before classifying"),
severity: z.enum(["low", "medium", "high", "critical"]),
team: z.enum(["billing", "auth", "infrastructure", "product"]),
requiresEscalation: z.boolean(),
});
export type TicketTriage = z.infer<typeof TicketTriageSchema>;Frequently Asked Questions
Why does field order matter in LLM JSON outputs?
LLMs generate tokens sequentially from left to right. Putting a `reasoning` field before a `classification` or `score` field lets the model condition its final decision on explicit intermediate reasoning.
What should I do if an open-weight model still wraps JSON in markdown fences?
Use an inference engine like vLLM with guided_json decoding enabled, or strip leading/trailing ```json fences before running Zod/Pydantic validation.