Skip to content

Prompts

Structured output: ask for JSON and validate it before you trust it

How to ask a model for JSON that matches a schema, why you validate it with a library such as zod before using it, and what to do when it does not match.

Talqeen wrote this article and no editor has reviewed it yet. Search engines do not see this page until it is reviewed.

When a person reads a model's reply, clarity is enough. When your program reads it, it must have a fixed shape the program knows in advance. Structured output means asking for the reply in a format such as JSON, with set keys and types, and validating it before use.

Describe the shape precisely

Extract the following from the customer's message and answer with JSON only:
{
  "intent": "complaint" | "question" | "request",
  "order_id": string, or null if no number is given,
  "urgent": true or false
}
Add no text before or after the JSON.

The prompt says what happens when the information is missing: null. Without that, the model may invent an order number.

Use the provider's feature

Many providers and libraries such as the AI SDK let you pass the schema with the request so the reply follows it. That beats describing it in words, but it does not replace the next step.

Always validate

Model output is untrusted input. In TypeScript, zod does it:

import { z } from "zod";

const Reply = z.object({
  intent: z.enum(["complaint", "question", "request"]),
  order_id: z.string().max(40).nullable(),
  urgent: z.boolean(),
});

const parsed = Reply.safeParse(JSON.parse(text));
if (!parsed.success) {
  // retry once, then use the fallback
}

When the reply does not match

Retry once with the error message; do not retry forever; then fall back to a safe default or a human review. That is how Talqeen works: every AI task has an output schema, one repair attempt, and a fallback that works with no model at all.

Small tips

Keep schemas small, prefer fixed lists over free text, cap the length of every string, and never render the output as HTML without sanitising it.