Structured Outputs can still contain mistakes, and a schema-correct reply can still be wrong on the facts. Validation is the step that catches both: parse the JSON, check every field against the schema, and check the business rules the schema cannot express. When validation fails, the documented fix is to adjust the instructions, provide examples in the system instructions, or split the task into simpler subtasks, and then retry.
What you need
- A schema for the reply
- A validator for that schema in your language
- A retry policy with a maximum number of attempts
Step 1: Parse and validate the reply
Parse the JSON and validate it against the schema: required fields present, types correct, enum values allowed. Then check the business rules the schema does not express, such as a date that must be in the future.
Step 2: Retry with the error when it fails
On failure, send the reply back with the validation error named and ask for a corrected reply. Log the raw string of every failed attempt so the failure can be inspected later.
Step 3: Fall back after the last retry
If the retries are exhausted, fall back to a safe default: ask the user for the missing field, or store the item for manual review instead of guessing.
Worked example: synthetic validation and retry
The table below is a synthetic example. It shows the expected result of validating a reply; no API call was made.
| Check | First reply | After retry |
|---|---|---|
| Required field priority | Missing | Present |
| Enum value | urgent – not allowed | high – allowed |
| Business rule: date in future | Past date | Future date |
| Verdict | Fail – retry | Pass |
Expected result (UNTESTED). the first reply fails validation on three checks, and the retry passes all three. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- Schema adherence is not truth: shape is not the same as correct facts.
- Structured Outputs can still contain mistakes; adjust instructions, add examples, or split the task into simpler subtasks.
- Log raw strings; a parsed object hides the exact text the model produced.
- A refusal or an incomplete response is not a validation failure; handle those separately.
