Paj Digital Labs
All articles
AI & Automation

Structured Output from LLMs: JSON Schemas, Retries and When to Give Up

Parsing JSON out of a language model with regex is a rite of passage. The tool-use APIs, schema-constrained decoding, and the retry loop that treats the model like an unreliable dependency — because it is one.

Paj Digital Labs 3 min read
Robotic gripper sorting components on a laboratory workbench
Editorial illustration · AI & Automation

The first version of every LLM integration looks the same: a prompt that says "respond only with valid JSON," a prayer, and a JSON.parse wrapped in a try-catch that swallows the evidence. It works in testing. Then production traffic arrives and the model helpfully wraps its answer in a markdown fence, adds a preamble sentence, or invents a field called summary_text because the schema said summary.

Structured output is a solved problem now, but only if you use the mechanisms that actually constrain the model instead of asking it nicely.

Ask nicely vs. constrain

There are three tiers, in ascending order of reliability:

Tier 1: Prompt instructions. "Return JSON matching this schema." This is a suggestion. The model will violate it under load, on weird inputs, and on days ending in y. Fine for prototypes, unacceptable for pipelines.

Tier 2: Tool use / function calling. You declare the schema as a tool, and the model's response comes back as a structured tool call. The API validates against your schema. This is the minimum for production.

ts
const result = await client.messages.create({
  model: class="text-code-string">"claude-sonnet-4-6",
  tools: [{
    name: class="text-code-string">"extract_invoice",
    input_schema: {
      type: class="text-code-string">"object",
      properties: {
        vendor: { type: class="text-code-string">"string" },
        total_cents: { type: class="text-code-string">"integer" },
        due_date: { type: class="text-code-string">"string", description: class="text-code-string">"ISO 8601 date" },
        line_items: {
          type: class="text-code-string">"array",
          items: {
            type: class="text-code-string">"object",
            properties: {
              description: { type: class="text-code-string">"string" },
              amount_cents: { type: class="text-code-string">"integer" },
            },
            required: [class="text-code-string">"description", class="text-code-string">"amount_cents"],
          },
        },
      },
      required: [class="text-code-string">"vendor", class="text-code-string">"total_cents"],
    },
  }],
  tool_choice: { type: class="text-code-string">"tool", name: class="text-code-string">"extract_invoice" },
  messages: [{ role: class="text-code-string">"user", content: invoiceText }],
});

Tier 3: Constrained decoding. Some providers enforce the schema at the token level — the model literally cannot emit tokens that would violate it. Where available, this is the strongest guarantee. Where not, tier 2 plus validation is the answer.

Validate anyway

Schema-constrained output can still be semantically wrong: a date that does not exist, a total that does not match the line items, an enum value that is valid JSON and invalid business logic. Treat model output like user input — parse it through a real validator.

ts
import { z } from class="text-code-string">"zod";

const Invoice = z.object({
  vendor: z.string().min(1),
  total_cents: z.number().int().positive(),
  due_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
  line_items: z.array(z.object({
    description: z.string(),
    amount_cents: z.number().int(),
  })).default([]),
});

const parsed = Invoice.safeParse(toolCall.input);

The retry loop that works

When validation fails, do not just resend the same prompt — send the error back. Models are good at fixing mistakes they can see.

ts
for (let attempt = 0; attempt < 3; attempt++) {
  const result = await extract(messages);
  const parsed = Invoice.safeParse(result);
  if (parsed.success) return parsed.data;
  messages.push({
    role: class="text-code-string">"user",
    content: class="text-code-string">`Validation failed: ${parsed.error.issues
      .map((i) => `${i.path.join(class="text-code-string">".")}: ${i.message}class="text-code-string">`)
      .join("; ")}. Correct the output.`,
  });
}
throw new Error(class="text-code-string">"extraction failed after 3 attempts");

Three attempts catches the overwhelming majority of transient failures. Past three, the input is probably genuinely ambiguous — a scanned invoice with two totals, a contract with no dates. That is not a retry problem.

When to give up

Design the fallback before you need it. After the retries exhaust, the extraction goes to a dead-letter queue and a human sees it. Track how often that happens: if your human-review rate is 2%, you have a product. If it is 20%, you have a demo with extra steps, and the fix is almost never a better prompt — it is a better input, a narrower schema, or the honest admission that this document type needs a person.

The model is an unreliable dependency with a remarkable talent for language. Engineer around it exactly the way you would engineer around any flaky third-party API: contracts, validation, bounded retries, and a dead-letter queue. The magic is in the model. The reliability is on you.

Paj Digital Labs

The engineering journal of Paj Digital Solutions — hosting, server infrastructure and web engineering, written by the people who run the servers.

Related reading