hardAI Engineering

How do you validate and repair structured LLM output at runtime?

480 views
01

Understand the problem

Schema validation, bounded retries with error feedback, and safe fallbacks when repair fails.

validationstructured-outputrepair-loopreliability
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Bounded repair with semantic checks
async function extractInvoice(text: string): Promise<Invoice> {
  let lastErrors = "";
  for (let attempt = 0; attempt < 3; attempt++) {
    const raw = await model.extract(text, lastErrors);       // errors appended on retry
    const parsed = InvoiceSchema.safeParse(raw);
    if (parsed.success) {
      const sem = await semanticChecks(parsed.data);          // vendor exists? totals add up?
      if (sem.ok) { metrics.repairAttempts(attempt); return parsed.data; }
      lastErrors = sem.errors.join("; ");
    } else {
      lastErrors = parsed.error.issues.map((i) => i.path + ": " + i.message).join("; ");
    }
  }
  await reviewQueue.push({ text, lastErrors });               // deterministic fallback
  throw new NeedsHumanReview();
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.