Slides · Prompting and structured output

Reasoning models and structured outputs

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:

  1. Explain what a reasoning model does with extra compute, and what it costs.
  2. Decide per task between a reasoning model and a fast one, with measurements.
  3. Choose between prompted JSON, JSON mode, schema-constrained output and tool calling.
  4. 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.

Sources1 Thinking2 Reasoning models

Diagram

Where the time and tokens go

Diagram: A standard model starts streaming its answer straight away.
ModelYour appModelYour appStandard modelReasoning modelreasoning tokens, billed as outputquestionanswer streams straight awayquestionanswer streams after the thinking
Diagram summary: A standard model starts streaming its answer straight away. A reasoning model first generates reasoning tokens, which are billed as output tokens even when the API does not return them, and only then streams the visible answer. Time to the first visible token is longer.

Sources1 Thinking2 Reasoning models

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_tokens caps visible output and reasoning together.
  • If the cap is reached, OpenAI’s response has status set to incomplete, and you can pay for reasoning without getting a visible answer.
  • OpenAI exposes the count in output_tokens_details in the usage data. Watch that number to see what a setting really costs.

Sources1 Thinking2 Reasoning models

Worked example

A small output cap squeezes the answer (illustrative)

Suppose max_tokens is 1,000 and reasoning tokens count against it.

RequestReasoning tokensRoom left for the answerResult
Easy question150850Complete answer
Hard question700300Complete, but short on room
Very hard question1,0000Answer 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 200=1,700 output tokens1,700×5.00106=0.0085\begin{aligned} \text{reasoning } 1{,}500 + \text{answer } 200 &= 1{,}700\ \text{output tokens} \\ \frac{1{,}700 \times 5.00}{10^6} &= 0.0085 \end{aligned}

Same model without thinking, answer only (same price per token assumed):

200×5.00106=0.00100.00850.0010=8.5\frac{200 \times 5.00}{10^6} = 0.0010 \qquad \frac{0.0085}{0.0010} = 8.5

The same visible answer costs 8.5 times as much here. Set the cap from measured usage, with headroom.

Source1 Thinking

Concept

Effort: a knob you set from measurements

  • Both providers let you control how hard the model thinks: output_config.effort at Anthropic, reasoning.effort at 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.

Sources3 Effort2 Reasoning models

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.

Sources4 Reasoning models don't always say what they think1 Thinking

Compare

Other ways to spend inference compute

MethodWhat it doesCost
Chain-of-thought promptingAsks any model to write steps before the answerMore output tokens
Self-consistencySamples N reasoning paths and takes the majority answerAbout N times one call
Best-of-N with a verifierGenerates 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 verificationRuns the code, checks tests, queries the databaseTool 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.

Sources5 Chain-of-Thought Prompting Elicits Reasoning in Large Language Models6 Self-Consistency Improves Chain of Thought Reasoning in Language Models7 Training Verifiers to Solve Math Word Problems

Compare

Reasoning or fast: a starting hypothesis

Use a reasoning modelPrefer a fast model
Multi-step math or logic, hard coding, planning, ambiguous analysisExtraction, classification, rewriting, FAQ, simple retrieval answers
A wrong answer is costly and latency is tolerableStrict 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 max effort 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.

Source3 Effort

Worked example

A routing decision with numbers (illustrative)

A labelled set of 200 tasks, one fast model and one reasoning model.

MeasureFast modelReasoning model
Correct answers150 of 200 (75%)166 of 200 (83%)
p95 latency2 s6 s
Cost per 1,000 requests1.008.50
Cost per 1,000 correct answers1.3310.24
gain=83%−75%=8 pointslatency=6 s2 s=3 timescost per correct=1.000.75=1.33vs8.500.83=10.24\begin{aligned} \text{gain} &= 83\% - 75\% = 8\ \text{points} \\ \text{latency} &= \frac{6\ \text{s}}{2\ \text{s}} = 3\ \text{times} \\ \text{cost per correct} &= \frac{1.00}{0.75} = 1.33 \quad \text{vs} \quad \frac{8.50}{0.83} = 10.24 \end{aligned}
  • 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.250.7 \times 1.00 + 0.3 \times 8.50 = 3.25, not 8.50. You still have to measure quality on each path.

Diagram

Route by task

Diagram: A router sends easy requests to a fast model and hard ones to a reasoning model, and both return through the same output path.

easy: extract, classify, FAQ

hard: multi-step, high stakes

Incoming request

Router

Fast model

Reasoning model

Answer

Diagram summary: A router sends easy requests to a fast model and hard ones to a reasoning model, and both return through the same output path. The routing rule is something you tune from measurements on your own traffic, not a fixed law.

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.000.6 \times 1.00 + 0.4 \times 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

OptionWhat it guaranteesWhat it does not
Prompt for JSON, then parseNothingValid JSON, your fields, your types
JSON modeSyntactically valid JSON, on providers that offer itThat the JSON matches your schema
Schema-constrained outputThe reply conforms to your JSON SchemaTrue values, a complete reply, or a schema-shaped refusal
Tool or function callingThe model proposes a call with arguments you can checkThat 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.

Sources8 Structured model outputs9 Structured outputs

Diagram

Pick by purpose

Diagram: A fixed-shape reply uses schema-constrained output, an action or lookup uses tool calling, and a prototype can get by on prompt-and-parse.

A reply with a fixed shape

The model to do or fetch something

A quick prototype

What do you need?

Schema-constrained output

Tool calling, strict mode if available

Prompt for JSON and parse

Validate anyway

Diagram summary: A fixed-shape reply uses schema-constrained output, an action or lookup uses tool calling, and a prototype can get by on prompt-and-parse. All three end in the same validation step, because none of them guarantees the values are true.

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

Diagram: At each step the model’s scores for every token pass through a mask built from the schema, so only tokens that keep the output valid can be...

Scores for every token

Mask: keep schema-valid tokens

Sample from what is left

Next token, schema-valid

Diagram summary: At each step the model’s scores for every token pass through a mask built from the schema, so only tokens that keep the output valid can be sampled. That is why the shape is guaranteed and why the truth of the values is not.
  • 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.

Sources9 Structured outputs10 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 tokenProbability before maskAllowed by schema?Probability after mask
open0.40yes0.615
closed0.25yes0.385
The0.20no0
pending0.15no0
allowed mass=0.40+0.25=0.65open=0.400.65=0.615closed=0.250.65=0.385\begin{aligned} \text{allowed mass} &= 0.40 + 0.25 = 0.65 \\ \text{open} &= \frac{0.40}{0.65} = 0.615 \\ \text{closed} &= \frac{0.25}{0.65} = 0.385 \end{aligned}
  • The model cannot write pending, so the shape holds.
  • It can still pick closed for an order that is open. The schema controls form, not truth.

Compare

What constrained decoding still leaves to you

FailureWhat happensYour check
TruncationAt the token limit the output can be incomplete and not match the schemaCheck the stop reason or status
RefusalA refusal can come back without following your schemaCheck for it before parsing
Unsupported schema featuresAnthropic lists recursive schemas and numerical constraints such as minimum and maximum as unsupported, and returns a 400 errorKeep range checks in your own code
Enum casingAnthropic does not guarantee the capitalisation of enum valuesCompare case-insensitively
First-request latencyA new schema is processed first, so the first call is slowerWarm up; later calls are not slowed
TruthA well-formed total can be wrongSemantic checks

Anthropic caches compiled grammars for 24 hours from last use.

Sources9 Structured outputs8 Structured model outputs

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.

Source9 Structured outputs

Diagram

Validate, retry, fall back

Diagram: Every reply is checked first by stop reason.

refusal

max_tokens

normal

no

yes

no

yes

yes: retry

no

Model reply

Stop reason?

Fallback: human queue or defined error

Raise the output cap

Retries left?

Parses and fits the schema?

Error message

Semantic checks pass?

Return valid output

Diagram summary: Every reply is checked first by stop reason. A refusal goes straight to the fallback, and a truncated reply is retried with a higher output cap. A normal reply is checked for schema fit, then for meaning (ranges, totals, ids that exist), and a failure there sends the error back, all within a bounded number of retries. When retries run out, a defined fallback takes over, and unvalidated output is never passed on.

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 it
  • model_validate_json raises one ValidationError that 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.
  • Decimal avoids float rounding in money sums.

Sources11 Models9 Structured outputs

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 fail=0.033=0.000027success within 3=1−0.000027=0.999973(99.9973%)expected calls=1+0.03+0.032=1.0309\begin{aligned} \text{all 3 attempts fail} &= 0.03^3 = 0.000027 \\ \text{success within 3} &= 1 - 0.000027 = 0.999973 \quad (99.9973\%) \\ \text{expected calls} &= 1 + 0.03 + 0.03^2 = 1.0309 \end{aligned}
Retries allowedChance the job still failsExpected calls per job
03%1.0000
10.09%1.0300
20.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,0002{,}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)

  1. Thinking (opens in a new tab)

    Anthropic2026Documentation

    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.

  2. Reasoning models (opens in a new tab)

    OpenAI2026Documentation

    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.

  3. Effort (opens in a new tab)

    Anthropic2026Documentation

    Used for Effort is a behavioural signal, not a strict token budget; lower effort saves tokens with some capability loss.

  4. Reasoning models don't always say what they think (opens in a new tab)

    Anthropic (Alignment Science team)2025Article

    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.

  5. 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

    Used for Chain-of-thought prompting as a way to spend inference compute on any model.

References

References & Sources (2 of 3)

  1. 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

    Used for Self-consistency: sample N reasoning paths and take the majority answer.

  2. Training Verifiers to Solve Math Word Problems (opens in a new tab)

    Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian, Mark Chen, et al.2021Preprint

    Used for Training verifiers to rank many sampled solutions, the basis of best-of-N with a verifier.

  3. Structured model outputs (opens in a new tab)

    OpenAI2026Documentation

    Used for JSON mode gives valid JSON; only Structured Outputs ensure schema adherence; refusals, incomplete responses and first-request latency.

  4. Structured outputs (opens in a new tab)

    Anthropic2026Documentation

    Used for Constrained decoding from a compiled grammar; truncation, refusals, unsupported features, enum casing, grammar caching and strict tool use.

  5. Efficient Guided Generation for Large Language Models (opens in a new tab)

    Brandon T. Willard, Rémi Louf2023Preprint

    Used for Guided generation as transitions of a finite-state machine, with an index over the vocabulary.

References

References & Sources (3 of 3)

  1. Models (opens in a new tab)

    Pydantic2026Documentation

    Used for model_validate_json builds a validated model from a JSON string and raises ValidationError listing every failure.