← Journal
AI7 min · 2026-05-30· 5-phase teardown

Structured output without the retries tax

Asking a model for JSON and parsing whatever comes back is a coin flip, and retrying until it parses quietly triples your token bill. Schema injection plus one independent validation pass turns model output into a validated boundary — with predictable cost and predictable shape.

01

Issue

The problem, framed precisely.

Parse-and-pray doesn't survive contact with load

Ask a model for JSON, parse whatever it returns, and you're flipping a coin on every request. Under load the flips compound: a malformed brace here, a missing required field there, a stray prose preface that breaks JSON.parse. In a demo it looks fine. In production it's an intermittent 500 that's maddening to reproduce because the input that broke it looks identical to a hundred that didn't.

The instinctive fix — retry until it parses — is worse than it looks. It trades a visible error for an invisible cost: you're now paying for two, three, sometimes four full generations per logical request, and your token bill grows with no corresponding line in the code review that caused it.

02

Hypothesis

What I believed was true, and why.

Treat model output like any other untrusted boundary

My hypothesis: model output deserves exactly the treatment we already give user input and third-party APIs — validate it at the boundary, and never let unvalidated data leak inward. If I inject the schema into the request and then validate the response independently against that same schema, the caller receives either a typed, valid object or a clean typed error. Never half-parsed garbage.

The sharper part of the hypothesis: most failures are self-correcting on a single re-ask if I tell the model precisely what was wrong. A blind retry starts from zero; a repair pass that includes the validation error starts from a corrected premise.

03

Strategy

The approach and the trade-offs weighed.

Inject the schema, validate independently, repair once

  • Inject the JSON schema into the request via response_format, so the model is constrained at generation time.
  • Validate the response independently against the same schema — trust the constraint, but verify it.
  • On failure, re-ask exactly once with the validation error appended; the model now knows the specific defect.
  • On a second failure, fail loudly with a typed 422 — bounded cost, never an infinite retry loop.

The bound is the whole point. Blind retry has no natural ceiling; a single repair pass caps worst-case cost at two generations while resolving the large majority of failures. And validation living at the gateway means every consumer inherits the guarantee — no per-caller parsing code to drift out of sync.

04

Implementation

How it was actually built.

The repair loop, and where confidence comes from

The core is a small state machine: generate, validate, and if invalid, repair-once with the error in context. Confidence falls out of how cleanly the output matched — a first-pass success scores higher than one that needed repair, and that signal surfaces in the response meta for the UI to show.

let result = await complete({ ...opts, jsonSchema });
let parsed = tryParse(result.content);
let repaired = false;

if (parsed === undefined) {
  repaired = true;
  // Re-ask ONCE, feeding back the exact defect \u2014 not a blind retry.
  result = await complete({ ...opts, jsonSchema, messages: [
    ...messages,
    { role: 'assistant', content: result.content },
    { role: 'user', content:
      'Your reply was not valid JSON for the schema. Return ONLY valid JSON.' },
  ]});
  parsed = tryParse(result.content);
}

if (parsed === undefined) return problem(422, 'schema-invalid');
return { data: parsed, meta: { confidence: repaired ? 0.75 : 0.94 } };

The tryParse helper is deliberately forgiving on the wrapper (stripping ```json fences) but strict on the structure (the schema does the real gatekeeping). Forgiving where models are sloppy, strict where correctness lives — that split is what makes the boundary both robust and trustworthy.

05

Summary

Outcome, evidence, and what I'd change.

Predictable cost, predictable shape

The result is a boundary that behaves like every other validated boundary in the system: the caller gets a valid object or a clean error, cost is capped at two generations in the worst case, and confidence is a real signal rather than a vibe. You stop paying the retries tax and start treating model output as data you can reason about.

The honest limit: schema injection narrows the output distribution but doesn't guarantee semantic correctness — the model can return schema-valid JSON that's factually wrong. Structure is a syntactic guarantee, not a truth guarantee. Where truth matters, the schema is the floor, not the ceiling; you still need evals, grounding, or human review on top. What this buys you is that you're never again debugging a malformed brace at 2am — you're debugging meaning, which is the problem actually worth your time.

Written by Ridha Fahmi Junaidi · AI Implementation Lead · AI Integration Engineer

Next
Real-time inventory: killing an N+1 across a nationwide retail network→