How do you validate LLM-generated JSON against a Zod schema and auto-retry with validation error feedback? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you validate LLM-generated JSON against a Zod schema and auto-retry with validation error feedback?

message-square
0

Why Zod + Retry Feedback Loops Work for LLM JSON

Even with JSON mode or structured output instructions, LLMs can still return syntax errors (such as markdown fences or stray text), wrong field types, missing required fields, or values that violate business/semantic rules.

Using Zod with a bounded retry loop gives you runtime type safety and actionable self-correction:

  • Single source of truth: Define your data contract once with z.object(...), infer the TypeScript type with z.infer<typeof schema>, and validate untrusted model output at runtime.
  • safeParse() over parse(): Calling schema.safeParse(data) returns structured error.issues (with exact field paths and messages) without throwing an uncaught exception.
  • Targeted error feedback: Passing the previous invalid output plus concise, human-readable Zod issue instructions helps the model fix exact mismatches on the next attempt.

Steps to Validate and Auto-Retry

  1. Extract and parse JSON safely: Strip optional markdown code fences (```json ... ```) and run JSON.parse() inside a try/catch.
  2. Validate with safeParse(): Pass the parsed object into your Zod schema (including .refine() or .superRefine() rules for cross-field or semantic checks).
  3. Format concise issue feedback: If safeParse() fails or JSON syntax is invalid, format each issue (path, message) into a clear correction prompt alongside the prior output.
  4. Cap retries (for example, 2–3 attempts): Append the assistant’s invalid attempt and a user correction message (or pass structured error feedback) up to a strict attempt limit so latency and token spend stay bounded.

TypeScript Example Using OpenAI + Zod Auto-Retry

import OpenAI from "openai";
import { z } from "zod";

const openai = new OpenAI();

const TaskExtractionSchema = z
  .object({
    title: z.string().min(1, "Title is required"),
    priority: z.enum(["low", "medium", "high"]),
    estimateHours: z.number().positive("Estimate must be a positive number"),
    dueDate: z.string().date().nullable(),
  })
  .refine(
    (data) => !(data.priority === "high" && data.estimateHours > 40),
    {
      path: ["estimateHours"],
      message: "High-priority tasks should be broken down to 40 hours or less",
    }
  );

type TaskExtraction = z.infer<typeof TaskExtractionSchema>;

function extractJsonText(raw: string): string {
  const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
  if (fenced?.[1]) {
    return fenced[1].trim();
  }
  const firstBrace = raw.indexOf("{");
  const lastBrace = raw.lastIndexOf("}");
  if (firstBrace !== -1 && lastBrace > firstBrace) {
    return raw.slice(firstBrace, lastBrace + 1).trim();
  }
  return raw.trim();
}

function formatZodIssues(error: z.ZodError): string {
  return error.issues
    .map((issue) => {
      const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
      return `- ${path}:${issue.message}`;
    })
    .join("\n");
}

export async function generateValidatedJson<T>(
  prompt: string,
  schema: z.ZodType<T>,
  maxAttempts = 3
): Promise<T> {
  const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
    {
      role: "system",
      content:
        "You extract structured data and return valid JSON only with no markdown or extra commentary.",
    },
    {
      role: "user",
      content: prompt,
    },
  ];

  let lastFeedback = "";

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const completion = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      temperature: 0,
      response_format: { type: "json_object" },
      messages,
    });

    const rawContent = completion.choices[0]?.message?.content ?? "";
    const jsonString = extractJsonText(rawContent);

    let parsedJson: unknown;
    try {
      parsedJson = JSON.parse(jsonString);
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Malformed JSON syntax";
      lastFeedback = `JSON syntax error: \${msg}`;
      messages.push({ role: "assistant", content: rawContent });
      messages.push({
        role: "user",
        content: `Your output was not valid JSON (\${lastFeedback}). Return a single valid JSON object only.`,
      });
      continue;
    }

    const result = schema.safeParse(parsedJson);
    if (result.success) {
      return result.data;
    }

    lastFeedback = formatZodIssues(result.error);
    messages.push({ role: "assistant", content: rawContent });
    messages.push({
      role: "user",
      content: `Your JSON failed schema validation:\n\${lastFeedback}\nReturn the corrected JSON object only.`,
    });
  }

  throw new Error(
    `Failed to produce valid JSON after \${maxAttempts} attempts. Last error:\n\${lastFeedback}`
  );
}

// Example usage
const task = await generateValidatedJson<TaskExtraction>(
  "Urgent: fix checkout webhook signature bug before Friday. Probably takes 3 hours.",
  TaskExtractionSchema
);
console.log(task);

Helpful Tips for Production Loops

  • Keep retries low (2–3 attempts): Every retry adds another round-trip and input tokens, so cap attempts and handle final failures gracefully.
  • Prefer nullable() over optional() for missing facts: If a field is absent in the source text, asking for null is often clearer for the model than omitting keys.
  • Use z.preprocess() carefully: Normalizing obvious formatting issues (like trimming whitespace) can save a retry, while strict validation catches real schema or semantic mistakes.