Slides · Prompting and structured output
Reasoning models and structured outputs
1 / 28
Reasoning models and structured outputs
When to pay for thinking, how to get output a program can read, and what to do on the days it is still wrong.
Concept
Two decisions in almost every LLM feature
- Aarav’s order system wanted order number, status, date and reason, one line each. It got a paragraph about the festival rush and rejected the whole reply.
- Which model and setting handle this request? Thinking can be much better on hard problems and wasteful on easy ones, and you pay for it either way.
- How do you get output a program can parse? “The model usually returns valid JSON” is not a reliability story. A parse error is an outage for the feature.
Four things you will be able to do:
- Explain what a reasoning model does with extra compute, and what it costs.
- Decide per task between a reasoning model and a fast one, with measurements.
- Choose between prompted JSON, JSON mode, schema-constrained output and tool calling.
- Design a validate, bounded-retry and fallback loop.
Concept
A reasoning model works on scratch paper first
- A standard model answers from instinct. A reasoning model writes out intermediate work before the visible answer, and spends more inference-time compute (test-time compute) on harder problems.
- Anthropic describes the model working through the problem in its own words: it rephrases the task, tries different approaches, tests partial results and abandons dead ends.
- It is chain-of-thought built into the model: you switch it on, or it is on by default, instead of asking for steps in your prompt.
- Because the model already does the step-by-step work, OpenAI advises giving a clear goal, constraints and output format rather than scripting every step. That is why “think step by step” adds less here than on a model that does not reason on its own.
Mental model: scratch paper helps on math, code, planning and multi-step logic. On an obvious question it only adds delay and cost.
Diagram
Where the time and tokens go
Concept
You pay for thinking you cannot see
- Anthropic: you are charged for thinking at the output-token rate whether or not the thinking text comes back, and it uses up part of
max_tokens. - OpenAI: reasoning tokens are not visible through the API but occupy context and are billed as output tokens.
max_output_tokenscaps visible output and reasoning together. - If the cap is reached, OpenAI’s response has
statusset toincomplete, and you can pay for reasoning without getting a visible answer. - OpenAI exposes the count in
output_tokens_detailsin the usage data. Watch that number to see what a setting really costs.
Worked example
A small output cap squeezes the answer (illustrative)
Suppose max_tokens is 1,000 and reasoning tokens count against it.
| Request | Reasoning tokens | Room left for the answer | Result |
|---|---|---|---|
| Easy question | 150 | 850 | Complete answer |
| Hard question | 700 | 300 | Complete, but short on room |
| Very hard question | 1,000 | 0 | Answer cut off or missing |
Now the cost. A hard request thinks for 1,500 tokens and writes a 200-token answer, so the cap must be raised to at least 1,700 (say 2,000). With an illustrative output price of 5.00 per million tokens:
reasoning 1,500+answer 2001061,700×5.00=1,700 output tokens=0.0085Same model without thinking, answer only (same price per token assumed):
106200×5.00=0.00100.00100.0085=8.5The same visible answer costs 8.5 times as much here. Set the cap from measured usage, with headroom.
Source[1] Thinking
Concept
Effort: a knob you set from measurements
- Both providers let you control how hard the model thinks:
output_config.effortat Anthropic,reasoning.effortat OpenAI. - Effort applies to all output tokens, with or without thinking. Lower effort favours speed and fewer tokens, with some loss of capability on hard tasks. Anthropic calls effort “a behavioral signal, not a strict token budget”.
- Allowed values, defaults and which models accept them are model-dependent and change often. Read the docs for the model you actually call.
- OpenAI’s guidance: treat effort as a tuning knob, not the main way to recover quality from a weak prompt.
Prompting a reasoning model: give a clear goal, strong constraints and an explicit output format. Do not script every intermediate step.
Concept
The visible reasoning is a clue, not an audit trail
- Anthropic gave models a hint and checked whether the written reasoning admitted using it. Averaged over hint types, it did in 25% of cases for Claude 3.7 Sonnet and 39% for DeepSeek R1.
- The setup was contrived: multiple-choice quizzes, a limited range of hints, two model families. The authors note faithfulness was lower on average when questions were harder.
- Anthropic’s docs also say the thinking text you see is a summary of the model’s reasoning, never the raw chain of thought.
Consequence: do not treat reasoning text as the official record of why a decision was made. Log the inputs, the output and the checks you ran.
Sources[4] Reasoning models don't always say what they think[1] Thinking
Compare
Other ways to spend inference compute
| Method | What it does | Cost |
|---|---|---|
| Chain-of-thought prompting | Asks any model to write steps before the answer | More output tokens |
| Self-consistency | Samples N reasoning paths and takes the majority answer | About N times one call |
| Best-of-N with a verifier | Generates N answers and keeps the one a checker or reward model scores highest (Cobbe et al. trained verifiers to rank sampled math solutions) | N calls plus the verifier |
| Tool-assisted verification | Runs the code, checks tests, queries the database | Tool time plus an extra step |
- The first two come from the papers by Wei et al. and Wang et al. Tool-assisted verification is this lesson’s definition.
- These work with non-reasoning models too. A reasoning model is the version of the first idea that ships inside the model.
Sources[5] Chain-of-Thought Prompting Elicits Reasoning in Large Language Models[6] Self-Consistency Improves Chain of Thought Reasoning in Language Models[7] Training Verifiers to Solve Math Word Problems
Compare
Reasoning or fast: a starting hypothesis
| Use a reasoning model | Prefer a fast model |
|---|---|
| Multi-step math or logic, hard coding, planning, ambiguous analysis | Extraction, classification, rewriting, FAQ, simple retrieval answers |
| A wrong answer is costly and latency is tolerable | Strict latency target or high volume |
- This table is where you start, not what you ship.
- Decide by running both on a labelled set of your own tasks and comparing the quality gain with the extra latency and cost.
- More thinking does not always mean a better answer. In Anthropic’s guidance for Claude Opus 4.7, the
maxeffort level adds cost for small gains on most workloads and can lead to overthinking on some structured-output or less intelligence-sensitive tasks. Easy tasks gain little.
Source[3] Effort
Worked example
A routing decision with numbers (illustrative)
A labelled set of 200 tasks, one fast model and one reasoning model.
| Measure | Fast model | Reasoning model |
|---|---|---|
| Correct answers | 150 of 200 (75%) | 166 of 200 (83%) |
| p95 latency | 2 s | 6 s |
| Cost per 1,000 requests | 1.00 | 8.50 |
| Cost per 1,000 correct answers | 1.33 | 10.24 |
- For a nightly report, 8 points may be worth the wait and the money. For a chat reply, a tripled p95 may not be.
- Routing can beat one choice for everything: if 70% of traffic is easy and goes to the fast model, cost per 1,000 requests is 0.7×1.00+0.3×8.50=3.25, not 8.50. You still have to measure quality on each path.
Diagram
Route by task
Check yourself
Check: the routing arithmetic
Using the cost figures from the routing slide (1.00 per 1,000 requests on the fast model, 8.50 on the reasoning model), 60% of your traffic is easy and 40% is hard. What is the cost per 1,000 requests if you route, compared with sending everything to the reasoning model? What must you still measure?
Show the answer
Routed: 0.6×1.00+0.4×8.50=0.60+3.40=4.00. All reasoning: 8.50. Routing saves 4.50, about 53%.
The saving only counts if quality holds. Measure accuracy on each path, and how often the router sends a hard request to the fast model by mistake.
Compare
Four ways to ask for structure
| Option | What it guarantees | What it does not |
|---|---|---|
| Prompt for JSON, then parse | Nothing | Valid JSON, your fields, your types |
| JSON mode | Syntactically valid JSON, on providers that offer it | That the JSON matches your schema |
| Schema-constrained output | The reply conforms to your JSON Schema | True values, a complete reply, or a schema-shaped refusal |
| Tool or function calling | The model proposes a call with arguments you can check | That the call is the right action, or the arguments true |
- OpenAI: both JSON mode and Structured Outputs give valid JSON, but only Structured Outputs ensure schema adherence. OpenAI recommends Structured Outputs over JSON mode where possible.
- Anthropic: strict tool use validates tool parameters, and JSON outputs control the response format. They can be used independently or together.
- These are different tools, not a ladder from bad to good.
Diagram
Pick by purpose
Strict tool use schema-checks arguments, so the two overlap. The purpose differs: one shapes a reply, the other triggers an action.
Diagram
How the guarantee is made
- Anthropic describes compiling your JSON schema into a grammar that constrains sampling.
- Willard and Louf describe the same family of idea: treat generation as moving between states of a finite-state machine and index the vocabulary so allowed tokens are cheap to find.
Sources[9] Structured outputs[10] Efficient Guided Generation for Large Language Models
Worked example
One masked step, with numbers (illustrative)
Schema field: status must be open or closed. The model is about to write the value. These probabilities are made up for the example.
| Candidate token | Probability before mask | Allowed by schema? | Probability after mask |
|---|---|---|---|
open | 0.40 | yes | 0.615 |
closed | 0.25 | yes | 0.385 |
The | 0.20 | no | 0 |
pending | 0.15 | no | 0 |
- The model cannot write
pending, so the shape holds. - It can still pick
closedfor an order that is open. The schema controls form, not truth.
Compare
What constrained decoding still leaves to you
| Failure | What happens | Your check |
|---|---|---|
| Truncation | At the token limit the output can be incomplete and not match the schema | Check the stop reason or status |
| Refusal | A refusal can come back without following your schema | Check for it before parsing |
| Unsupported schema features | Anthropic lists recursive schemas and numerical constraints such as minimum and maximum as unsupported, and returns a 400 error | Keep range checks in your own code |
| Enum casing | Anthropic does not guarantee the capitalisation of enum values | Compare case-insensitively |
| First-request latency | A new schema is processed first, so the first call is slower | Warm up; later calls are not slowed |
| Truth | A well-formed total can be wrong | Semantic checks |
Anthropic caches compiled grammars for 24 hours from last use.
Concept
Design the schema to help the model
- Keep schemas simple. Use descriptive field names and enums rather than free text.
- Leave a short explanation or notes field, placed before the answer fields, so a strict schema does not squeeze out the model’s working.
- The field-order advice is common practice, not provider guidance. Test it on your own cases.
- Anthropic warns that a property that asks for the model’s step-by-step thinking might lead to a refusal, and suggests asking for a short explanation instead.
Source[9] Structured outputs
Diagram
Validate, retry, fall back
Code
The loop in Python
Python
from decimal import Decimal
from pydantic import BaseModel, ValidationError
class InvoiceLine(BaseModel):
name: str
amount: Decimal
class Invoice(BaseModel):
vendor: str
lines: list[InvoiceLine]
total: Decimal
MAX_RETRIES = 2
def semantic_errors(inv: Invoice) -> list[str]:
if sum(item.amount for item in inv.lines) != inv.total:
return ["line amounts do not add up to total"]
return []
def extract(document, call_model):
# call_model(messages, max_tokens) stands in for your provider call and
# returns {"text": ..., "stop_reason": ...}. Real field names differ.
messages = [{"role": "user", "content": f"<document>{document}</document>"}]
max_tokens = 1000
for attempt in range(1 + MAX_RETRIES):
reply = call_model(messages, max_tokens)
if reply["stop_reason"] == "refusal":
return None # retrying will not help: fall back
if reply["stop_reason"] == "max_tokens":
max_tokens *= 2 # retry with room, same messages
continue
try:
inv = Invoice.model_validate_json(reply["text"])
problems = semantic_errors(inv)
if not problems:
return inv
error = "; ".join(problems)
except ValidationError as exc:
error = str(exc)
messages += [
{"role": "assistant", "content": reply["text"]},
{"role": "user", "content": f"Fix this and return corrected JSON only: {error}"},
]
return None # caller routes to a human queue and logs itmodel_validate_jsonraises oneValidationErrorthat lists every failure, and its text goes back to the model.- The sum check is a semantic rule the schema cannot express.
- Truncation is retried with a larger output cap, because the same cap fails the same way. A refusal goes straight to the fallback, since asking for corrected JSON does not fix it.
Decimalavoids float rounding in money sums.
Worked example
What a retry budget buys (illustrative)
Suppose 3% of replies fail validation on any one attempt, and attempts fail independently.
all 3 attempts failsuccess within 3expected calls=0.033=0.000027=1−0.000027=0.999973(99.9973%)=1+0.03+0.032=1.0309| Retries allowed | Chance the job still fails | Expected calls per job |
|---|---|---|
| 0 | 3% | 1.0000 |
| 1 | 0.09% | 1.0300 |
| 2 | 0.0027% | 1.0309 |
- Bounded retries are cheap on average. The cost is the worst case: three calls and added delay.
- Independence is optimistic. A hard input tends to fail again, so measure the real failure rate after retries.
- Log the failure type and rate, so you notice when a model or prompt change breaks things.
- A valid-looking wrong answer passes this loop. That is what semantic checks and your labelled set are for.
Check yourself
Check: what the schema cannot do
An extractor returns refund as a number, and the refund must never exceed the order total, which comes from your database. Why does this check stay in your own code, and why can a retry loop not fix every failure?
Show the answer
The schema cannot know the order total, which is runtime data. Anthropic also lists numerical constraints such as minimum and maximum as unsupported in its strict mode, so range checks stay in your code anyway.
A retry sends the error back and asks for corrected output, which helps with a wrong or malformed value. It does not help with a refusal (go to the fallback) or with truncation at the cap (raise the cap).
Check yourself
Check: size the cap from the logs
Your logs show that 40% of failed validations are replies stopped at the output limit, which is set to 2,500. When you re-run a sample of those requests without the tight cap, they use up to 2,600 reasoning tokens and answers of up to 400 tokens. What is the smallest cap that fits, and why is a higher retry count the wrong first fix?
Show the answer
2,600+400=3,000 tokens is the least that fits, so pick a cap above it with headroom (3,500, for example) and keep watching the usage data.
Retrying at 2,500 repeats the same cut-off and adds cost and delay. The cap itself, or the effort setting, is what has to change.
Summary
Recap
- Reasoning models spend extra inference compute: better on hard multi-step tasks, slower and costlier, with reasoning tokens billed as output.
- The visible reasoning is a clue, not an audit trail.
- Decide fast versus reasoning by measuring quality, latency and cost on your own tasks, and route by task.
- JSON mode gives valid JSON. Schema-constrained outputs give schema-conformant JSON. Tool calling is for actions.
- Constrained decoding guarantees form, not truth. Handle truncation and refusals, validate meaning, retry a bounded number of times, and have a fallback.
References
References & Sources (1 of 3)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/thinking
Used for Thinking tokens are billed as output tokens even when not returned, count toward max_tokens, and the visible thinking text is a summary.
Reasoning models (opens in a new tab)
OpenAI2026Documentation
https://developers.openai.com/api/docs/guides/reasoning
Used for Reasoning tokens are billed as output, count toward max_output_tokens, can leave a response incomplete, and are reported in usage details; prompting guidance for reasoning models.
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/effort
Used for Effort is a behavioural signal, not a strict token budget; lower effort saves tokens with some capability loss.
Reasoning models don't always say what they think (opens in a new tab)
Anthropic (Alignment Science team)2025Article
https://www.anthropic.com/research/reasoning-models-dont-say-think
Used for Visible reasoning mentioned a used hint in 25% (Claude 3.7 Sonnet) and 39% (DeepSeek R1) of cases on average, in contrived tests.
Chain-of-Thought Prompting Elicits Reasoning in Large Language Models (opens in a new tab)
Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, et al.2022NeurIPS 2022Paper
arXiv 2201.11903 (opens in a new tab)https://arxiv.org/abs/2201.11903
Used for Chain-of-thought prompting as a way to spend inference compute on any model.
References
References & Sources (2 of 3)
Self-Consistency Improves Chain of Thought Reasoning in Language Models (opens in a new tab)
Xuezhi Wang, Jason Wei, Dale Schuurmans, Quoc Le, et al.2023ICLR 2023Paper
arXiv 2203.11171 (opens in a new tab)https://arxiv.org/abs/2203.11171
Used for Self-consistency: sample N reasoning paths and take the majority answer.
Training Verifiers to Solve Math Word Problems (opens in a new tab)
Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian, Mark Chen, et al.2021Preprint
arXiv 2110.14168 (opens in a new tab)https://arxiv.org/abs/2110.14168
Used for Training verifiers to rank many sampled solutions, the basis of best-of-N with a verifier.
Structured model outputs (opens in a new tab)
OpenAI2026Documentation
https://developers.openai.com/api/docs/guides/structured-outputs
Used for JSON mode gives valid JSON; only Structured Outputs ensure schema adherence; refusals, incomplete responses and first-request latency.
Structured outputs (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/structured-outputs
Used for Constrained decoding from a compiled grammar; truncation, refusals, unsupported features, enum casing, grammar caching and strict tool use.
Efficient Guided Generation for Large Language Models (opens in a new tab)
Brandon T. Willard, Rémi Louf2023Preprint
arXiv 2307.09702 (opens in a new tab)https://arxiv.org/abs/2307.09702
Used for Guided generation as transitions of a finite-state machine, with an index over the vocabulary.
References
References & Sources (3 of 3)
Pydantic2026Documentation
https://pydantic.dev/docs/validation/latest/concepts/models/
Used for model_validate_json builds a validated model from a JSON string and raises ValidationError listing every failure.
Keys: ← → move, Home End first and last, F full screen.