{"slug": "how-to-automatically-repair-invalid-llm-responses", "title": "How to Automatically Repair Invalid LLM Responses", "summary": "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.", "body_md": "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.\n\nNothing 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.\n\nThis 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.\n\nStructured 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.\n\nRe-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.\n\nFormat 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.\n\nValGuard 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.\n\nThe repair rules are grouped into three tiers. A preset decides which tiers an agent may use.\n\n| Tier | What it does | Enabled by | \n|---|---|---|\n| 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 | \n| 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 | \n| Tier 3, field-scoped | Clamps numeric ranges, converts amounts to cents, generates deterministic UUIDv5 values for empty ID fields | Custom only, per named field | \n\nTier 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.\n\nTier 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.\n\nPresets 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.\n\nHere 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`.\n\n```\n{\"invoice_id\": \"INV-4471\", \"amount\": \"1250.00\", \"status\": \"Paid\",}\n```\n\nSafe 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.\n\nStandard 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.\n\nStandard 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.\n\nSafe is low risk because its rules only touch syntax. Standard changes values, and some of those changes deserve a careful read first.\n\nIf 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.\n\nWhen a range violation must block, use Custom instead and leave the clamp and truncation rules off.\n\nStandard 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`.\n\nResponse repair fixes shape, not meaning.\n\nIf the model routinely omits a field, that is a prompt or extraction problem. Repair should not hide it.\n\nRepair 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.\n\nResponse 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.\n\n| Header | When it is set | \n|---|---|\n| `X-VG-Repair-Attempted` | Repair changed the payload, whatever the final verdict | \n| `X-VG-Repair-Rules` ,`X-VG-Repair-Trace` | Rule IDs, and `rule@field` entries, for the attempt | \n| `X-VG-Healed` | The final response passed and repair contributed to it | \n| `X-VG-Healed-Rules` ,`X-VG-Healed-Event-Count` | Rules and event count behind the passing response | \n\nWhen validation still blocks after repair, the healed headers are cleared. A blocked request is never labeled as repaired.\n\nRequest 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.\n\nRepair changes what validators see, so treat a preset change like a validator change.\n\n`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.\n`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.\n\nRepair 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.\n\nTo estimate savings at your volume, use the [response repair calculator](https://valguard.ai/tools/response-repair-calculator).\n\nValGuard 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.\n\nPick 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.\n\nOriginally published on the [ValGuard blog](https://valguard.ai/blog/how-to-automatically-repair-invalid-llm-responses).", "url": "https://wpnews.pro/news/how-to-automatically-repair-invalid-llm-responses", "canonical_source": "https://dev.to/robertbobrowski/how-to-automatically-repair-invalid-llm-responses-4nn6", "published_at": "2026-12-03 13:10:20+00:00", "updated_at": "2026-12-03 13:17:54.043896+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools", "structured-data", "developer-tools"], "entities": ["ValGuard"], "also_reported_by": [], "takeaway": "Repairing malformed LLM JSON deterministically on the proxy path—extracting fenced bodies, stripping trailing commas, casting numeric strings and normalizing enum casing—lets validators pass without a second completion, reserving re-ask as a last resort.", "recommendation": {"advice": "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.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/how-to-automatically-repair-invalid-llm-responses", "markdown": "https://wpnews.pro/news/how-to-automatically-repair-invalid-llm-responses.md", "text": "https://wpnews.pro/news/how-to-automatically-repair-invalid-llm-responses.txt", "jsonld": "https://wpnews.pro/news/how-to-automatically-repair-invalid-llm-responses.jsonld"}}