AI Agents & LLMsMedium
How do you get reliable structured (JSON) output from an LLM?
Learning path, stage 2 of 5: Prompting and model features · question 6 of 10Don't just ask nicely for JSON. Use the provider's constrained output, such as structured outputs with a JSON Schema or strict tool definitions, so generation is forced to match the schema. Then still validate in code, because a valid shape doesn't guarantee correct values.
Levels of reliability, from weakest to strongest
- "Respond in JSON" in the prompt. This breaks sometimes (extra prose, trailing commas).
- A few-shot example of the exact JSON.
- Tool calling: the model fills a tool's
input_schema. - Structured outputs / strict mode: decoding is constrained so the output always parses and matches the schema.
Best practices
- Keep schemas simple and flat. Use
enumfor categories and mark fieldsrequired. - Add a way out:
"status": "ok" | "insufficient_info", so the model isn't forced to invent values. - Validate with Zod (or a similar library) and handle failure: retry, fall back, or send to a person.
- Ask for reasoning in a separate field if you need it. Don't let it leak into data fields.
Sources
Code example
tsx
1// Structured outputs with a Zod schema; the SDK parses and validates.2import Anthropic from "@anthropic-ai/sdk";3import { z } from "zod";4import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";56const Ticket = z.object({7 category: z.enum(["bug", "feature_request", "question", "other"]),8 severity: z.enum(["low", "medium", "high"]),9 summary: z.string(),10 needs_human: z.boolean(),11});1213const client = new Anthropic();1415export async function triage(text: string) {16 const res = await client.messages.parse({17 model: "claude-opus-5-5",18 max_tokens: 1024,19 messages: [{ role: "user", content: `Triage this support ticket:\n${text}` }],20 output_config: { format: zodOutputFormat(Ticket) },21 });22 if (!res.parsed_output) throw new Error("Model did not return a valid ticket");23 return res.parsed_output; // typed as z.infer<typeof Ticket>24}
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.