cd /news/large-language-models/how-to-automatically-repair-invalid-… · home › topics › large-language-models › article
[ARTICLE · art-181013] src=dev.to ↗ pub= topic=large-language-models verified=true sentiment=↑ positive

How to Automatically Repair Invalid LLM Responses

A developer built deterministic response repair into ValGuard, a proxy that fixes malformed LLM output in process before validators run, avoiding costly re-asks. The system uses three tiers: syntax fixes like extracting fenced JSON and removing trailing commas, schema-aware casts and enum normalization, and field-scoped repairs such as converting amounts to cents and generating deterministic UUIDv5 IDs. Repair only runs when output parses as JSON, and presets default to off at both agent and platform level.

recommendation

Fix format failures with deterministic code before validators run—extract fenced JSON, strip trailing commas, cast numeric strings and normalize enum case—and re-ask only when repair still fails.

more in playbook: Verifying model output
by read6 min views7 publishedDec 3, 2026

Picture an on-call thread, an illustrative scenario, that opens with "the model got worse." Pass rate on the invoice agent is flat, latency is flat, and the provider has shipped nothing. What has climbed is the re-ask count, and finance spots the token bill first.

Nothing is wrong with the answers. The model is drifting on format: JSON wrapped in a markdown fence, a trailing comma, a number returned as a string, an enum value in the wrong case. Each of those fails a strict validator, and each re-ask pays for another full completion.

This article covers how deterministic response repair handles that class of failure in ValGuard, where it stops, and how to roll it out. The short version: fix shape with code, keep meaning in validators, and leave re-ask as the last option.

Structured output validation catches two different problems. Some responses are wrong: a missing invoice total, a made-up customer ID. Others are right but badly encoded, so the data is there and the parser cannot read it.

Re-ask treats both the same way. It sends validator feedback back to the model and hopes the next completion is clean. That adds latency, tokens, and unpredictability, because a second completion can fix the comma and break something else.

Format failures do not need a model. A trailing comma has one correct repair, and a fenced JSON block has one correct body. That is the case for LLM JSON repair as a deterministic step on the proxy path.

ValGuard applies response repair after the upstream call returns and before validators run, in process and without a network call. The repaired text is what validators score. If it passes, the request completes without a re-ask. If it still fails, the agent's normal on_fail behavior applies, so block still blocks.

The repair rules are grouped into three tiers. A preset decides which tiers an agent may use.

Tier What it does Enabled by
Tier 1, syntax Trims whitespace, extracts JSON from a markdown fence, normalizes smart quotes, fixes single quotes, unquoted keys, trailing and leading commas, and missing commas between quoted values on separate lines Safe, Standard, or Custom
Tier 2, schema-aware Casts numeric and boolean strings, normalizes enum casing, fills configured defaults, normalizes dates, currency, and country codes, clamps to configured bounds, truncates arrays to configured maximums Standard, or Custom
Tier 3, field-scoped Clamps numeric ranges, converts amounts to cents, generates deterministic UUIDv5 values for empty ID fields Custom only, per named field

Tier 2 and Tier 3 only run when the output parses as JSON after Tier 1. Repair never edits a field inside a document that still cannot be parsed.

Tier 2 reads the agent's JSON Schema rule plus hints from field validators such as range_validator, enum_validator, and list_length. Defaults are never invented: a field is filled only when a default is configured for it.

Presets are set per agent or inherited from the workspace, and both start at Off. Response repair is also off at the platform level by default; the agent's Response Repair tab appears once an admin enables it.

Here is a response from an invoice agent whose schema expects amount as a number and status as one of paid or open. The model wrapped it in a markdown fence labeled json.

{"invoice_id": "INV-4471", "amount": "1250.00", "status": "Paid",}

Safe extracts the fenced body and removes the trailing comma. The document now parses, but amount is still a string and Paid is not an allowed value, so validators still fail it.

Standard goes one step further. It casts "1250.00" to the number 1250 and maps Paid to paid, because the enum match ignores case. The validators then see a clean object, and no extra model call is needed.

Standard does not map Payed to paid. Near-match enum repair only runs on fields you opt into fuzzy matching; other values outside the allowed list still fail.

Safe is low risk because its rules only touch syntax. Standard changes values, and some of those changes deserve a careful read first.

If an agent has a range_validator with a minimum or maximum, Standard can clamp an out-of-range number to that bound instead of letting the validator block it. If a list_length rule sets a maximum, Standard can truncate the array. These changes are deterministic and logged, but they change values.

When a range violation must block, use Custom instead and leave the clamp and truncation rules off.

Standard also has one non-deterministic behavior. When the only enforcing failures are invalid-format errors, it may spend one extra model call asking for well-formed JSON. That is a re-ask, and a successful one is recorded as reask:valid_format.

Response repair fixes shape, not meaning.

If the model routinely omits a field, that is a prompt or extraction problem. Repair should not hide it.

Repair follows the same explainability rule as validators. Each fix produces a log event with a rule ID, a field path where one applies, and before and after snippets redacted according to the agent's log level.

Response headers separate "repair ran" from "repair made the request pass." The OpenAI-compatible response body keeps its shape; only the assistant content is replaced with the repaired text.

Header When it is set
X-VG-Repair-Attempted Repair changed the payload, whatever the final verdict
X-VG-Repair-Rules ,X-VG-Repair-Trace Rule IDs, and rule@field entries, for the attempt
X-VG-Healed The final response passed and repair contributed to it
X-VG-Healed-Rules ,X-VG-Healed-Event-Count Rules and event count behind the passing response

When validation still blocks after repair, the healed headers are cleared. A blocked request is never labeled as repaired.

Request rows store healed, heal_rules, heal_field_paths, and post_heal_validation_pass. The request log has a Repaired column, request detail lists the rules that fired, and the proxy exports valguard_response_repair_total by rule.

Repair changes what validators see, so treat a preset change like a validator change.

payload_shape telemetry for the agent. It records json_valid and a parse_error_type such as trailing_comma, without storing content. on_fail settings alone in the same window. payload_shape is computed on the text validators score, which is the repaired text when a preset is on. A rising json_valid=false count with repair enabled means repair is not covering the failure.

Repair presets have no observe-only mode of their own: when a preset is on, clients receive the repaired text. Shadow mode belongs to validators, so test rule changes with Simulate before production.

To estimate savings at your volume, use the response repair calculator.

ValGuard also publishes five repair playbooks. They are human triage checklists for this rollout. They do not change presets, cap re-asks, or block traffic on their own.

Pick one agent where tickets mention invalid JSON but model evals look fine. Check its parse error types, enable Safe, and watch re-ask counts and the Repaired column for a few days. Move to Standard only after you know which values it would change.

Originally published on the ValGuard blog.

── more in #large-language-models 4 stories · sorted by recency
── more on @valguard 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-automatically…] indexed:0 read:6min 2026-12-03 · —