Skip to main content

Structured output repair

Models asked for JSON sometimes return something close to it. Common cases are a reply wrapped in a markdown code fence, a sentence before or after the JSON, a trailing comma, single quotes, NaN, a reply cut off by max_tokens, or a number sent as a string. Structured output repair checks the reply against the requested schema, fixes what can be fixed without guessing, and when the reply still does not match it asks the model again with the validation error. Your application only ever receives JSON that matches the schema, or a clear error.

It is off by default. You turn it on for the whole gateway, per key or team, per deployment or per request, and it applies to non-streaming /v1/chat/completions requests.

A real-world scenario​

An accounts team extracts invoice numbers and totals from emails with a model that is asked for JSON. About one reply in fifty comes back wrapped in a code fence or with a trailing comma, and their parser crashes on it. The admin turns on structured output repair in repair_and_retry mode. The gateway now fixes those small mistakes itself, re-asks the model only when the reply is really wrong, and the team's code only ever receives JSON that matches their schema.

Step by step​

  1. In the Admin UI open Settings, then Router Settings (/ui/router-settings), and go to the Structured Output tab.
  2. In the Structured Output Repair card pick repair_and_retry as Repair mode and 2 as Max correction retries. Each choice is saved as soon as you pick it.
  3. Send a request that asks for a JSON schema, as in Per request, and print the response headers with curl -i.
  4. Open Logs and find the request to see its attempts and cost.

Expected result​

The response body is JSON that matches the schema. The x-spanway-structured-output header says valid when the first reply already matched, repaired when the gateway fixed it locally, or retried when it re-asked the model, and x-spanway-structured-output-attempts says how many model calls were used. When every retry fails, the request answers 422 with a StructuredOutputRepairError that names the last validation problem.

Which requests it checks​

Repair runs when the request sets one of these response_format values.

response_formatChecked against
{"type": "json_schema", "json_schema": {"schema": {...}}}The schema
{"type": "json_object", "response_schema": {...}}response_schema
{"type": "json_object"}Any JSON object

Requests that stream, that ask for more than one choice (n above 1), or that use any other response_format are passed through unchanged. Replies without text content, such as tool calls or refusals, are returned as they are.

Modes​

ModeWhat it does
offNothing is checked. This is the default.
repairFixes the reply locally. If it still does not match, the request fails.
retrySends a correction turn to the model, up to the retry limit. No local fixes.
repair_and_retryFixes locally first, and re-asks only when the fixed reply still does not match.

structured_output_max_retries sets how many correction turns are allowed per request. It defaults to 1 and can be at most 5, so a request makes at most 6 model calls.

What local repair fixes​

Local repair never invents data. It removes code fences and the prose around the JSON. When that prose has brackets of its own, such as a citation [1] before the real object, every bracketed value is tried and the first one that matches the schema is kept. It also drops trailing commas, accepts single quoted strings, unquoted keys and Python style True, False and None, and turns NaN and Infinity into null. When a reply is cut off, the last incomplete value is dropped and the open objects and arrays are closed. A partially written string or number is never kept, so a cut off reply that loses a required field fails validation and goes on to a retry.

After parsing, values are coerced to the schema type only when the conversion is lossless. "42" becomes 42 for an integer field, "9.5" becomes 9.5 for a number field, "true" becomes true for a boolean field, a whole float such as 7.0 becomes 7 for an integer field, and a number becomes a string for a string field. Ambiguous values such as "yes" or "4.2" for an integer field are left alone and fail validation. Local $ref references, anyOf and oneOf are followed, so Pydantic models with nested models and optional fields are covered. A number string that would overflow, such as "1e400", is left alone. Replies nested more than 64 levels deep are not repaired and fail validation.

What a retry sends​

A retry repeats the original messages and adds two turns. The first is an assistant turn with the reply that failed, and the second is a user turn with the validation error, for example at total: 'abc' is not of type 'number', asking for corrected JSON only. Only the latest failed reply is sent, so the conversation does not grow with every attempt.

Turn it on​

Each field is resolved on its own, and the first value found wins, in this order.

  1. The request body fields structured_output_repair and structured_output_max_retries.
  2. metadata.structured_output_repair and metadata.structured_output_max_retries on the virtual key.
  3. The same fields in the team metadata.
  4. The same fields in the deployment's spanway_params.
  5. spanway_settings.structured_output_repair and spanway_settings.structured_output_max_retries.

A request that sets "structured_output_repair": "off" switches it off even when a key, team, deployment or the gateway turns it on.

structured_output_max_retries on a key or team is also a ceiling. A request can ask for fewer retries but never more, so a team that sets 0 never pays for a correction turn. Deployment and gateway values are defaults only, and a request can raise them up to the cap of 5. Budgets and rate limits are checked once before the first attempt, not again between retries.

Per request​

curl http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_KEY" \
-H "Content-Type: application/json" \
-i \
-d '{
"model": "gpt-5.6",
"structured_output_repair": "repair_and_retry",
"structured_output_max_retries": 2,
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "invoice",
"schema": {
"type": "object",
"properties": {"number": {"type": "string"}, "total": {"type": "number"}},
"required": ["number", "total"],
"additionalProperties": false
}
}
},
"messages": [{"role": "user", "content": "Extract the invoice number and total from: INV-7, total due $120.50"}]
}'

Per key or team​

curl http://localhost:4000/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{"metadata": {"structured_output_repair": "repair_and_retry", "structured_output_max_retries": 2}}'

Team metadata takes the same fields through /team/new and /team/update. Key and team values only apply to chat completion routes. /key/generate, /key/update, /team/new and /team/update refuse an invalid value with a 400 that names the field. If an invalid value was stored before that check existed, only requests that set a response_format fail, with a 400 that names the key or team field, and every other request is unaffected.

Per deployment​

model_list:
- model_name: extraction
spanway_params:
model: openai/gpt-5.6
api_key: os.environ/OPENAI_API_KEY
structured_output_repair: repair_and_retry
structured_output_max_retries: 2

The fields are read by the gateway and never sent to the provider.

For the whole gateway​

spanway_settings:
structured_output_repair: repair
structured_output_max_retries: 1

Admins can also set both fields in the Admin UI under Settings, Router Settings, on the Structured Output tab. Values saved there are stored in the database and reach every worker, and a field set in config.yaml shows as read only with the note "Set in config.yaml, change it there." The Admin UI only accepts the listed values, and an invalid value in config.yaml stops the gateway at startup with an error that names the setting.

What the caller sees​

When repair is on and the reply was checked, the response carries two headers. A reply is checked when it is a single text answer (n unset or 1) to a json_object or json_schema request. Tool call replies, refusals, requests with n above 1 and other response_format values pass through unchecked and get neither header.

HeaderValues
x-spanway-structured-outputvalid when the first reply matched, repaired when it was fixed locally, retried when a correction turn was needed.
x-spanway-structured-output-attemptsThe number of model calls the request used.

When the retry limit runs out, the request fails with status 422 and a StructuredOutputRepairError (a subclass of JSONSchemaValidationError) that names the model, the number of attempts and the last validation error. Because the status is 422, the router does not cool the deployment down or retry the same call on its own, but fallbacks you configure still apply.

Metrics​

Two counters are kept in the default prometheus_client registry whenever prometheus_client is installed, whether or not the Prometheus callback is on. The gateway serves that registry on /metrics once the Prometheus callback is enabled. The model label is the provider model the deployment calls, such as openai/gpt-5.6.

MetricLabelsMeaning
spanway_structured_output_requests_totalmodel, outcomeChecked requests by outcome, one of valid, repaired, retried or failed.
spanway_structured_output_reasks_totalmodelCorrection turns sent to the model.

Cost and limits​

Every correction turn is a full model call. It is billed and logged as its own request in the spend logs, so its cost counts toward key and team budgets and a request that needed two retries shows up as three rows. Set a low structured_output_max_retries for expensive models.

Streaming responses, the Responses API (/v1/responses) and the Anthropic Messages API (/v1/messages) are not covered. Without repair turned on, enable_json_schema_validation keeps its previous behavior and raises JSONSchemaValidationError on the first invalid reply.

Errors​

StatusErrorMeaning and fix
422StructuredOutputRepairError, naming the model, the attempts and the last validation errorThe model kept returning JSON that does not match the schema after every allowed retry. Simplify the schema, raise structured_output_max_retries, or use a stronger model.
422JSONSchemaValidationErrorRepair is off and enable_json_schema_validation is on, so the first invalid reply fails. Turn repair on.
No x-spanway-structured-output headerThe request is streaming, goes to /v1/responses or /v1/messages, asked for n above 1 or a response_format other than json_object or json_schema, or the reply was a tool call or a refusal. None of these are checked.Use a single non-streaming chat completion with a JSON response format.
400 metadata: ... naming structured_output_repair or structured_output_max_retriesA key or team was saved with a value the gateway does not accept.Use one of off, repair, retry, repair_and_retry and a retry count from 0 to 5.

In the Admin UI the gateway default is on the Structured Output tab of Settings, Router Settings.

Logs​

Repair writes no operator log line of its own. Each correction turn shows as its own row on the Logs page and in the spend logs, so a request that needed two retries shows three rows, and the counters under Metrics show the outcomes over time. A change to the gateway default writes an audit row, see audit logs.