How to Cap AI Agent Structured Output Validation Retry Before JSON Breaks A structured-output retry policy for AI agents should cap retries at two to three attempts, since an uncapped loop turns a schema bug into a permanent cost multiplier where every request burns the maximum number of calls, according to guidance published by Startup Fortune. The guidance recommends logging which attempt succeeds to set the cap from real traffic, feeding the model its previous output plus the validator's exact error message rather than a generic retry prompt, and routing exhausted jobs to a dead-letter queue with the raw output attached. It notes that a 5% independent failure rate adds only about 5% to spend, but a schema bug that fails every attempt at 100% uses every allowed retry, and three retries on an eight-second model call means half a minute of dead air for the user. One malformed field can quietly multiply your token bill and freeze every job waiting behind it. A fixed retry cap, a short error message fed back to the model, and a planned fallback keep that from happening. - Retries that aren't capped turn a broken schema into a permanent cost multiplier, because every request burns the maximum number of calls. - A cap of two retries covers most real failures, but you should confirm that by logging which attempt succeeds in your own traffic. - Send the model its previous output plus the validator's exact error message, not a generic 'try again'. - Never retry truncation, refusals or timeouts the same way you retry a schema mismatch, since they need different fixes. - When the cap runs out, route the job to a dead-letter queue with the raw output attached, and alert on the rate rather than on single failures. - If your provider offers schema-constrained decoding, use it first and keep the validator and retry cap as a backstop. Your agent calls a model, asks for JSON, and passes the result to the next step. Then one day the model wraps the object in a markdown fence, or returns a string where your schema wants an integer. If you haven't set an ai agent structured output validation retry policy, one of two things happens. The job crashes, or the loop keeps asking until something passes. Both are bad, and the second is harder to spot. A crash shows up in your alerts. An uncapped loop shows up three weeks later as a line on the invoice nobody can explain. Start with the arithmetic. If a call fails validation 5% of the time and failures are independent, the expected number of calls per task is 1 divided by 0.95, about 1.05. That's a 5% bump in spend, and nobody notices it. It's the model most teams carry in their heads. The model breaks when failures aren't independent. A schema bug, such as a required field the model has no way to fill, makes every attempt fail. Now the failure rate isn't 5%, it's 100%, and each request uses every retry you allow. With a cap of three retries, that's four calls per task. With no cap, it's a loop that ends when your rate limiter, your budget alarm or your patience does. Set Your LLM Fallback Model Routing Strategy Before the Outage, Not During It https://startupfortune.com/set-your-llm-fallback-model-routing-strategy-before-the-outage-not-during-it/ LLM fallback model routing strategy comes down to four numbers: trigger thresholds, parity pass marks, a spend cap at 2x your hourly baseline, and a monthly drill. Here's the rule, including which errors should never trigger failover. - how to test LLM fallback model routing https://startupfortune.com/set-your-llm-fallback-model-routing-strategy-before-the-outage-not-during-it/ - LLM fallback strategy for production outages https://startupfortune.com/set-your-llm-fallback-model-routing-strategy-before-the-outage-not-during-it/ It gets worse because retries aren't priced like first attempts. A good retry sends the original prompt, the bad output and the error message back to the model. The input grows each round, and the failed output you're resending is often as long as the answer you wanted. Count both sides when you estimate the cost of a failing schema: the repeated input and the repeated output. Then there's the stall. If your pipeline processes jobs in order, or a downstream worker waits for a result, a task stuck in a retry loop holds everything behind it. Latency is the cost nobody puts in the spreadsheet. Three retries on a model that takes eight seconds per call is half a minute of dead air for the user on the other end. Pick the cap from your own logs, not from a blog post You'll see 'retry up to three times' in a lot of tutorials. Three is a fine starting number, and it's also a guess. The better method takes an afternoon. Log the attempt number on every call that passes validation. After a week of traffic you'll have a histogram: how many tasks passed on attempt one, how many on attempt two, and so on. Tasks that needed a second attempt tell you the feedback loop works. Tasks that needed a fourth tell you something else is going on. In most setups the curve falls off hard. The first retry rescues the majority of failures, because the model sees exactly what it got wrong and fixes that one thing. The second rescues a smaller share. By the third, you're mostly watching the model repeat the same mistake with slightly different wording. Set your cap where the marginal rescue rate drops below what a retry costs you. For many teams that lands at two retries, so three calls in total. If your histogram says otherwise, believe the histogram. Set the cap per schema, not globally. A flat object with four string fields and an enum almost never needs a second try. A nested schema with arrays of objects, optional branches and cross-field rules fails far more often and may justify one more attempt. Tying the cap to schema complexity is more honest than pretending every output is equally hard. Also cap the thing people forget: total tokens per task. A retry count limits calls, but a model that returns a 6,000-token answer on every try can still burn money inside that limit. Put a token budget next to the retry count, and stop on whichever trips first. How to build an AI agent kill switch before a loop burns your budget https://startupfortune.com/how-to-build-an-ai-agent-kill-switch-before-a-loop-burns-your-budget/ Knight Capital lost more than $440 million in roughly 45 minutes in 2012 because nobody could stop a faulty system fast enough. The fix is three layers: a per-run dollar breaker, a global flag, and short-lived credentials. The article also shows how to rehearse the drill in staging. - how to build an AI agent kill switch https://startupfortune.com/how-to-build-an-ai-agent-kill-switch-before-a-loop-burns-your-budget/ - prevent AI agent loops burning your budget https://startupfortune.com/how-to-build-an-ai-agent-kill-switch-before-a-loop-burns-your-budget/ Feed the validation error back, and keep it short The worst retry is the blind one: same prompt, same settings, hope for a different result. At temperature zero you may get the identical bad output back, and you've paid twice for it. The retry that works tells the model what went wrong. Libraries already do this. Instructor, the Python library built on Pydantic, takes a max retries setting and, when validation fails, re-asks the model with the validation errors attached. LangChain ships parsers in the same spirit, including OutputFixingParser and RetryOutputParser, which hand the bad output and the parse error back to a model for repair. If you roll your own, copy the pattern and keep control of the details. The details matter more than the pattern. A Pydantic ValidationError lists the field path, the rule that failed and the value it saw. That's enough. Send something like: 'Your previous response failed validation. Field items 2 .quantity must be an integer, got the string "two". Return the full corrected JSON only.' It names the field, states the rule and says what to return. Don't paste the entire stack trace. Don't add a paragraph of apology or a lecture on JSON syntax. And don't tell the model to 'be more careful', because that carries no information. If you have five errors, send five lines. If you have forty, send the first five and say how many more there are, otherwise your retry prompt becomes the most expensive part of the call. One more habit pays off. Ask for the complete corrected object, not a patch. Patch-style repairs invite the model to return a fragment, which then fails validation for a new reason and burns an attempt you can't spare. Sort the failure before you choose the retry Not every bad output is a schema problem, and treating them all the same is how teams waste retries. There are four kinds worth separating in code. Truncation comes first. If the response hit the max token limit mid-object, the JSON is cut off and the parser throws. Feeding that back with an error message won't help, because the model didn't make a mistake, you ran out of room. Check the stop reason before you parse. A length stop means raise the output limit or shrink the task, not retry. Refusals look like malformed JSON. The model returns a polite paragraph of prose where you wanted an object, and your parser chokes on the first character. Retrying a refusal rarely changes the answer, and it can look like you're trying to argue the model into compliance. Detect it, log it and send it to review. Then there's the pure syntax slip: a trailing comma, a code fence around the object, a stray sentence before the opening brace. These are cheap to repair without a model at all. A small cleanup step that strips fences and extracts the outermost braces will fix a lot of them, and a deterministic fix costs no tokens and adds no latency. Try it before you spend a retry. Last is the real schema mismatch: a wrong type, a missing required field, a value outside the allowed enum. This is the case the feedback retry is built for, and it's the only one where spending an attempt makes sense. Timeouts and rate-limit errors sit outside all four. Those are transport problems, and they belong in a separate retry policy with exponential backoff and jitter, with their own cap. If you count a 429 against your validation budget, a busy afternoon will exhaust your retries on outputs you never even saw. The best fix is making the failure rarer Retries are a repair mechanism, and the cheapest repair is the failure that never happens. Check what your provider offers before you build much of this. OpenAI introduced Structured Outputs in August 2024, which constrains decoding to a supplied JSON schema. In its announcement, OpenAI said gpt-4o-2024-08-06 scored a perfect 100% on its evaluation of complex JSON schema following, compared with under 40% for gpt-4-0613. Open-source tools such as Outlines apply the same grammar-constrained idea to models you host yourself. Tool use with a declared input schema, which Anthropic and others support, pushes the model toward the right shape as well, though you should still validate what comes back. Constrained decoding guarantees shape, not sense. The output will parse and match your types, and the date can still be in the wrong year or the total can still disagree with the line items. So keep a validator for the rules a schema can't express, and keep the retry cap for those. Frankly, teams that skip the validator because 'the API guarantees the schema' are the ones who find out about semantic errors from customers. You can also lower your own failure rate by editing the schema. Flatten deep nesting. Replace free-text fields with enums where the set is small. Add a one-line description to every field, since models read them. Make fields optional with a null default when the model may not have the information, instead of required fields that force it to invent a value. A required field with no possible answer is the classic cause of the 100% failure case from earlier. Decide what happens when the cap runs out Every retry loop ends in one of two places: success or the fallback. Teams spend days on the first and ten minutes on the second, which is backwards, because the fallback is what your users see on the bad days. You have a few honest options, and the right one depends on the task. For a low-stakes field, such as a tag or a category, fill in a safe default and flag the record. For a task that matters, park it in a dead-letter queue with the raw model output, the last validation error and the attempt count attached, so a person or a later job can pick it up without rerunning anything. For an interactive agent, tell the user the step failed and offer to try again, rather than hanging. A second model is a legitimate fallback too, with a caveat. Escalating from a small, cheap model to a larger one after the cap is a sound pattern, since the larger model often handles the awkward schema. But it adds a call to your worst-case cost, so count it when you set the cap. Escalate once, not in a loop. What you shouldn't do is let a failed step pass bad data downstream. A half-valid object that squeaks through with a missing field turns a visible error into a silent one three steps later, where it's far more expensive to trace. Fail closed. A task in the dead-letter queue is a problem you know about. Watch rates, not single events. One validation failure is noise. A jump in the share of tasks that need a second attempt, from 4% to 15% overnight, usually means someone changed the prompt, the schema or the model version. Alert on that number, and you'll catch a provider-side change before your users do. The checklist Here's the whole thing as something you can paste into a pull request description. Start by validating every model output against a typed schema, with Pydantic in Python or Zod in TypeScript, before anything downstream touches it. Check the stop reason before parsing, so truncation and refusals never enter the retry loop. Run a deterministic cleanup for fences and stray text. Only then, for a true schema mismatch, send one retry that includes the previous output and the specific validator errors, and ask for the complete corrected object. Set the cap per schema, begin at two retries, and tune it from a log of which attempt succeeded. Add a token budget beside the retry count. Keep transport errors on their own backoff policy. Use schema-constrained decoding where your provider offers it, and keep the validator anyway. Decide the fallback before you ship: default and flag, dead-letter queue, escalation to a larger model once, or a visible error. Alert on the retry rate. None of this needs a new framework. Instructor's max retries and a tenacity-style stop condition get you most of the way in an afternoon, and a single counter on the attempt number gives you the data to tune it. Without the cap, a broken schema costs you the maximum number of calls on every single request, forever. With a cap of two, the worst case is three calls, and you can put that number in a budget. Also read: How to Set Concurrency Limit for AI Agents Before Parallel Runs Hit 429s https://startupfortune.com/how-to-set-concurrency-limit-for-ai-agents-before-parallel-runs-hit-429s/ • What Are RSA and Elliptic Curve Cryptography, and Why Moving to Post-Quantum Cryptography Matters Now https://startupfortune.com/what-are-rsa-and-elliptic-curve-cryptography-and-why-moving-to-post-quantum-cryptography-matters-now/ • Outcome based pricing for AI agents without losing margin https://startupfortune.com/outcome-based-pricing-for-ai-agents-without-losing-margin/ This article is posted in AI News https://startupfortune.com/category/ai/ , check it out for more related stories. Join the discussion Open in the community → https://startupfortune.com/community/ Almost there. Sign in and your reply posts straight away.