LP-GE-10 Structured output instead of parse-and-re-ask

Skill
generation-economy
Saves
Generation
Severity
high
Applies to
openai, anthropic, gemini, openrouter, deepinfra, vllm, lm-warden, sglang, any
Evidence
[object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object]

Rule

When code needs to parse the model's answer, request structured output with a schema (or a strict tool call) instead of asking for JSON in prose, parsing it, and asking again when parsing fails.

Why

A parse failure throws away a whole generated answer and pays for another, and the re-ask usually carries the failed answer and an error message too. Constrained decoding prevents the failure instead of repairing it. What each provider offers (providers/openai.md, providers/anthropic.md, providers/gemini.md, providers/openrouter.md, providers/deepinfra.md, providers/vllm.md, providers/sglang.md):

  • OpenAI: json_schema with strict: true (Responses text.format, Chat Completions response_format). Only Structured Outputs ensure schema adherence; JSON mode only ensures valid JSON. Refusals come back in a separate refusal field.
  • Anthropic: output_config.format with a JSON schema, and strict: true on tools; the docs say no retries are needed for schema violations. Some schema features are not supported (400). Changing the format invalidates the prompt cache for that conversation.
  • Gemini: a JSON schema with application/json; output is valid JSON, but some constraints are stripped rather than enforced, and the docs say to validate values in the app.
  • OpenRouter: response_format json_schema on models with the structured-outputs capability.
  • DeepInfra: json_object or json_schema with strict; the docs warn that a length stop can leave the JSON incomplete.
  • vLLM, SGLang: response_format json_schema, plus regex, choice and grammar constraints.

Documented, not yet measured here.

Detect in code

Python:

rg -n 'json\.loads\(|JSONDecodeError|ValidationError|model_validate_json|re\.search\(r?["'"'"']```json' -g '*.py'
rg -n 'response_format|output_config|json_schema|strict' -g '*.py'

Shapes: try: json.loads(text) except JSONDecodeError: ask again with "That was not valid JSON"; re.sub(r"<think>.*?</think>", "", text, flags=re.S) before parsing, which means the server returns thinking inside the answer (no reasoning parser; see Don't break meaning); a regex that strips a ```json fence before parsing; a prompt line "Respond only with JSON in this format: ..." and no response_format; response_format={"type": "json_object"} where the code depends on specific fields.

TS/JS:

rg -n 'JSON\.parse\(|SyntaxError|safeParse\(|zod|response_format|json_schema' -g '*.{ts,tsx,js,mjs}'

Shapes: try { JSON.parse(text) } catch { return retryWithError(...) }; a zod safeParse failure that triggers a re-ask; text.replace(/<think>[\s\S]*?<\/think>/, "") before JSON.parse (thinking inside the answer).

Thinking inside the answer, any language:

rg -n '<think>|</think>|reasoning_content' .

Go:

rg -n 'json\.Unmarshal\(|ResponseFormat|JSONSchema' -g '*.go'

Shapes: if err := json.Unmarshal([]byte(content), &out); err != nil { /* re-ask */ }.

Fix

# before
resp = client.chat.completions.create(model=MODEL, messages=msgs + [{"role": "user", "content": "Reply only with JSON: {\"label\": ..., \"confidence\": ...}"}])
try:
    out = json.loads(resp.choices[0].message.content)
except json.JSONDecodeError:
    out = reask(msgs, resp)          # pays for another answer

# after
schema = {
    "type": "object",
    "properties": {"label": {"type": "string", "enum": LABELS}, "confidence": {"type": "number"}},
    "required": ["label", "confidence"],
    "additionalProperties": False,
}
resp = client.chat.completions.create(
    model=MODEL, messages=msgs,
    response_format={"type": "json_schema", "json_schema": {"name": "label", "strict": True, "schema": schema}},
)
msg = resp.choices[0].message
if msg.refusal:
    handle_refusal(msg.refusal)
out = json.loads(msg.content)        # schema-constrained

Keep validating the values in code (ranges, cross-field rules) where the provider does not enforce them, and keep the schema fixed for the life of a cached conversation.

Don't break meaning

The schema must let the model say what it would have said in prose: allow null or an "unknown" value where the answer can be missing, and include a reasoning field before the answer field if the prose form relied on the model explaining first and model thinking is off. With thinking on, a reasoning field makes the model reason twice into one output limit; decide which one stays under LP-GE-03. A schema that forbids those forces an answer that may be wrong.

A self-hosted reasoning model whose thinking arrives inside the answer. vLLM can keep a schema off the thinking only when it knows where the thinking ends: a server started with a reasoning parser (--reasoning-parser) returns the thinking in a separate reasoning field, and the structured-output manager starts the constraint after the end of reasoning (vLLM reasoning outputs, vLLM structured outputs, checked 2026-11-26; providers/vllm.md). Without a reasoning parser the thinking comes back inside content (<think>...</think> before the answer), nothing marks where it ends, and it follows that the schema applies to the thinking as well: the model cannot write the thinking it would have written, which can change its answers. Not yet measured here. So, before adding a schema on such a server, either confirm that the server splits reasoning out (a test request returns a non-empty reasoning field and content without thinking text), or decide under LP-GE-03 to turn thinking off for this call and run the answer check on the fixed inputs with thinking off before adding the schema. Do not add a schema while thinking still arrives in content. Size the output limit for the whole object (LP-GE-03), since a cut-off object is still invalid. Run the answer check on a fixed set of inputs before and after.

Verify

(a) Provider usage: on a self-hosted reasoning model, first send one test request with the schema and check that the response carries the thinking in a separate reasoning field and none in content; if the thinking is in content, the server has no reasoning parser and the fix waits for the LP-GE-03 thinking decision (Don't break meaning). Then: finish_reason / stop_reason is stop / end_turn and the content parses on every call; no follow-up call after a parse failure; output_tokens / completion_tokens per task falls by the re-asks removed. On OpenAI, read refusal separately.

(b) leanprompt usage record: no records with flags.parse_failed, and no flags.retry_of records following one. Before the fix, each parse failure shows as a record with flags.parse_failed and a re-ask record pointing at it.

Waste signal

Measured: output tokens of answers discarded after a parse failure (flags.parse_failed) count as generation waste. Static: severity high for a parse-and-re-ask loop; medium for JSON requested in the prompt with no schema on a provider that supports one. On a self-hosted server that returns thinking inside content, the finding stands, but record the fix as waiting on the LP-GE-03 thinking decision.

Edit this page on GitHub