New Tool Radar

AI Concepts

How to Retry and Repair a Model Reply That Fails JSON Parsing

Parse the reply, log the exact error, retry once with the error message included, and fall back to a safe default if it still fails.

Schematic with three steps: Parse strictly and log the exact error; Retry once with the error included; Fall back safely if the retry fails.

Even with structured outputs, your application still needs to handle refusals, incomplete responses and API errors, and a reply that fails JSON parsing must never be used as if it parsed. The safe pattern is to parse strictly, log the exact error, and retry once with the error included in the next request, so the model can fix the specific mistake. If the retry also fails, fall back to a safe default or ask the user, rather than guessing at the intended data.

What you need

  • The schema the reply must follow
  • A strict JSON parser that reports the error position
  • A safe fallback value for the case where parsing keeps failing

Step 1: Parse strictly and log the exact error

Parse the reply with a strict parser and record the error and the position where it failed, for example a missing comma or an unclosed bracket. Do not use a lenient parser that silently repairs the text.

Step 2: Retry once with the error included

Send the failed reply and the error message back to the model, asking for a corrected JSON object that follows the schema. One retry fixes most formatting slips; more retries rarely help and cost tokens.

Step 3: Fall back safely if the retry fails

If the retry also fails to parse, use the safe fallback: return an empty result, ask the user for the missing data, or mark the task as failed. Never invent the missing fields.

Worked example: synthetic repair of a broken reply

The table below is a synthetic example. It shows the expected result of repairing a reply; no call was made.

Attempt Reply Result
First Missing closing brace Parse error at end
Retry with error Valid JSON, all fields Parses – used
Retry failed Still invalid Fallback – ask the user
Decision One retry only Then fall back

Expected result (UNTESTED). the first reply fails to parse, the retry with the error message parses, and a second failure falls back to asking the user. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Structured outputs can still contain mistakes, so adjust instructions, provide examples, or split tasks into simpler subtasks when errors repeat.
  • The model will always try to adhere to the schema, which can result in hallucination if the input is unrelated to the schema.
  • Streaming a JSON reply lets you parse fields as they arrive, but a partial stream is not a complete object until it ends.
  • Log the raw reply with the error, so a repeated failure can be diagnosed instead of retried blindly.

Sources

See all