Structured Outputs constrains completed, non-refusal output to your schema, but your application still needs to handle refusals, incomplete responses and API errors. A refusal is not JSON, and a reply cut short by the token limit is not complete JSON. Both must be detected in code, because parsing them as if they were complete will crash or corrupt data.
Prerequisites
- Code that calls Structured Outputs.
- A way to read the response’s finish reason or refusal field.
- A retry policy: how many times to retry before giving up.
Steps
Step 1: Check for refusal
After each call, check whether the response is a refusal before parsing anything. If it is, log it and decide whether to rephrase the request or report it to the user; do not treat refusal text as data.
Step 2: Check for truncation
Check the finish reason and the reply length. A reply that ends because the token limit was reached is incomplete; parse it only to log it, never to store it as a result.
Step 3: Retry or ask again
For a truncated reply, retry with a higher token limit or a shorter input. For a refusal, change the request. Retry at most twice, then report the failure instead of looping.
Worked example: Cedar Street Library catalogue extract
The fictional Cedar Street Library extracts catalogue records with Structured Outputs and a 200-token cap. One reply stops mid-record.
| Reply | Finish reason | Parse | Action |
|---|---|---|---|
| Complete record | stop | Parses | Store it |
| Stops after 2 of 4 fields | length | Does not parse | Retry with a higher cap |
| Refusal text | refusal | Not JSON | Log and rephrase |
Of 3 replies, 1 stores, 1 retries with a higher cap and 1 is logged as a refusal, so no partial record reaches the catalogue.
Expected result. Every reply is checked for refusal and truncation before parsing, and incomplete replies are retried or reported, never stored. UNTESTED: this guide was not run against a live model or API. The worked example below is fictional practice material, and its result is the expected result, not a measured one.
Limits
- Raising the token cap costs more per call; shorten the input as well as raising the cap.
- A refusal may be a safety decision; rephrasing to evade it is not the aim of this guide.
- This guide does not cover API errors such as rate limits.
