02.8 Reasoning Models

Understand LLMsLesson 8 of 1016,839 words11 parts
Module 02 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

A standard LLM starts writing its answer the moment it receives your prompt, and every token gets the same fixed amount of computation. A reasoning model works differently: before answering, it writes out a private working process of planning, trying approaches, checking its work and backtracking, and only then commits to an answer. That extra work costs tokens, money and time, and on hard problems it buys a large jump in accuracy. Reasoning is now the default in most frontier models, so every applied AI engineer needs to know how it works, how each provider exposes it, what it costs, and when to turn it up, down or off.

What you'll learn

  • What a reasoning model is, what thinking tokens and test-time compute mean, and how this differs from chain-of-thought prompting on a standard model
  • How reasoning models are made (reinforcement learning with verifiable rewards), at the level an engineer needs, and why thinking longer improves accuracy on hard problems
  • How to control reasoning on OpenAI and Anthropic Claude, with a code sample for each, plus optional sections on Google Gemini and OpenRouter and a comparison table
  • What you can and can't see of a model's reasoning, why providers hide or summarize it, and why the reasoning text may not reflect what the model actually did
  • How reasoning affects cost, latency, max_tokens, the context window and sampling parameters
  • When to use reasoning and when not to, including the problem of overthinking
  • How to prompt reasoning models differently from standard models
  • How reasoning works inside tool-using agents (interleaved thinking)
  • How to run a small open reasoning model on your laptop, watch its <think> output, and measure how thinking changes accuracy
  • How to evaluate whether reasoning actually helps on your task, and the main test-time scaling techniques (self-consistency, best-of-n, verifiers)

What you don't need

  • Any maths beyond arithmetic. The training ideas are explained in plain English.
  • API keys for the local demos. Everything in Part 9 and most of the other samples run free on a CPU laptop. The provider samples need keys if you want to run them.

Setup

The local demos need Python 3.11+, PyTorch and Hugging Face Transformers. The first run downloads the Qwen/Qwen3-0.6B model (about 1.5 GB):

bash
uv add torch transformers numpy       # or: pip install torch transformers numpy

First time? Create a project with uv init llm-basics && cd llm-basics, then run scripts with uv run python file.py. The outputs in this lesson were produced with PyTorch 2.15.0 and Transformers 5.22.1. (Transformers 4.x spells the dtype argument torch_dtype; a newer major release may rename things again, so check its changelog if a sample fails.) The scripts use your GPU if you have one and fall back to the CPU. On a recent laptop CPU, this model generates about 20 tokens per second, so expect roughly 3 minutes for 9.2, 10 minutes for 9.3 and 20 minutes for 9.4. An Apple-silicon or NVIDIA GPU is about twice as fast or more, and older CPUs can be several times slower.

The provider samples use the official SDKs and read keys from a .env file:

bash
uv add openai anthropic google-genai python-dotenv httpx
# or, without uv: pip install openai anthropic google-genai python-dotenv httpx

The provider samples were checked against openai 3.x, anthropic 2.x and google-genai 2.x as of November 2026 (Module 03 gives the exact releases). An unversioned install gives you the newest release, and google-genai 3.x changes its default Gemini API version and HTTP library (03.1, 4.5), so if a sample does not match, check the SDK's changelog.

The OpenRouter catalogue lookup in 3.4 uses httpx, which is in the command above because openai 3.x and anthropic 2.x now bring httpx2 instead.

bash
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...        # optional: only for the Gemini sample
OPENROUTER_API_KEY=...    # optional: only for the OpenRouter sample

What you must be able to do after this lesson#

  • Explain what a reasoning model is and how it differs from a standard model
  • Control reasoning effort or budget on each provider
  • Explain what reasoning output you can and cannot see
  • Estimate the cost and latency of reasoning
  • Decide when to use a reasoning model
  • Evaluate reasoning gains on your own task

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"It's a reasoning model: it thinks before it answers." Part 1: What a reasoning model is
"Just add let's think step by step to the prompt." 1.2 Chain-of-thought prompting and Part 7
"Reasoning models are trained with RL on verifiable rewards." Part 2: How reasoning models are made
"Accuracy scales with test-time compute." 2.5 The test-time scaling curve
"Set reasoning.effort to low." / "Use adaptive thinking." / "Set thinking_level." Part 3: Provider controls
"Why can't we see the model's full chain of thought?" Part 4: What you can and can't see
"Our bill tripled after we switched models, but the answers are the same length." 5.1 Reasoning tokens are billed as output
"The API returned an empty answer with status incomplete." 5.3 Reasoning and max_tokens
"We get a 400 error when we set temperature." 5.5 Parameter restrictions
"The chat UI sits frozen for 20 seconds before the answer appears." 5.8 Streaming reasoning
"Do we really need a reasoning model for this classifier?" Part 6: When to use reasoning
"The agent thinks between tool calls." Part 8: Reasoning with tools and agents
"Use self-consistency / best-of-n / a verifier." 11.1 Test-time scaling methods

Part 1: What a reasoning model is#

1.1 The problem: a fixed amount of compute per token#

Recall from lesson 01 that an LLM produces each token with one forward pass through the network, and that a forward pass costs roughly the same amount of arithmetic whatever the token is (7.1). Generating the word "the" and generating the digit that settles a tricky calculation get exactly the same budget.

That's fine for easy text. It's a real limitation for problems that need many dependent steps. Ask a model "What is 17 × 24 − 13 × 9?" and demand the answer as the very first token: the network must do the whole calculation inside a single forward pass. For a person, that's like being asked to answer a long-division problem instantly, without paper.

The fix is the same for people and models: write the intermediate steps down. Every token a model writes is fed back in as input for the next one (lesson 05), so written-out steps act as scratch paper. Each extra token is one more forward pass of computation the model can spend on the problem, and the result of each step stays visible for the steps that follow.

1.2 Chain-of-thought prompting on a standard model#

The first way people exploited this was purely through prompting. In 2022, researchers showed that if you include worked examples with step-by-step reasoning in the prompt, or simply add the phrase "Let's think step by step", large models solve far more maths and logic problems correctly. This is called chain-of-thought (CoT) prompting.

Here is the same question asked two ways to a standard (non-reasoning) model:

text
Prompt A (direct):
  A shop sells pens in packs of 3 for $2. How much do 12 pens cost?
  Answer with just the number.

Prompt B (chain-of-thought):
  A shop sells pens in packs of 3 for $2. How much do 12 pens cost?
  Let's think step by step, then give the final answer.

With prompt B, the model writes something like "12 pens is 12 ÷ 3 = 4 packs. 4 packs × $2 = $8. Final answer: $8." The working is ordinary visible output. You pay for it as output tokens, your user sees it unless you strip it out, and its quality depends on a model that was never specifically trained to reason well. CoT prompting helps, but it's a trick layered on top of a model trained for other things. You'll measure exactly how much it helps a small model in 9.3.

1.3 Reasoning models: trained to think#

A reasoning model (also called a thinking model or large reasoning model, LRM) is an LLM that has been trained to produce a long stretch of reasoning before its answer, and trained in a way that rewards reasoning that actually leads to correct answers (Part 2). The reasoning is generated as tokens like any other, but it's marked as separate from the answer:

flowchart LR
    subgraph std ["Standard model"]
        Q1["Question"] --> A1["Answer tokens<br/>(start answering immediately)"]
    end
    subgraph rsn ["Reasoning model"]
        Q2["Question"] --> T2["Thinking tokens<br/>(plan, try, check, backtrack)"]
        T2 --> A2["Answer tokens<br/>(informed by the thinking)"]
    end

The tokens spent on reasoning are called reasoning tokens or thinking tokens (OpenAI says "reasoning", Anthropic and Google say "thinking"; they mean the same thing). Open-weight reasoning models usually wrap them in <think>...</think> tags. Hosted APIs return them as separate blocks or items, usually summarized or hidden (Part 4).

Spending extra computation while answering, rather than during training, is called test-time compute or inference-time compute ("test time" is ML jargon for "when the trained model is used"). Reasoning models are the main way the industry spends test-time compute today.

Inside a typical thinking trace, you'll see behaviours that a standard model rarely shows unprompted:

  • Restating and decomposing the problem into sub-problems.
  • Trying an approach, noticing it fails, and backtracking ("Wait, that doesn't work because...").
  • Checking intermediate results ("Let me verify: 4 × 2 = 8. Yes.").
  • Considering alternatives and edge cases before committing.

1.4 Chain-of-thought prompting vs reasoning models#

CoT prompting on a standard model Reasoning model
Where the behaviour comes from Your prompt ("think step by step", worked examples) Training: reinforcement learning rewarded reasoning that reached correct answers
Typical reasoning length Short: a few sentences to a paragraph Hundreds to tens of thousands of tokens on hard problems
Self-correction and backtracking Rare Common, learned during training
Where the reasoning appears Mixed into the visible answer In separate thinking blocks or items, often summarized or hidden
How you control the amount Prompt wording only API parameters: effort, thinking level, thinking budget
Billing Normal output tokens Normal output tokens, including hidden ones you never see
Accuracy on hard maths, code and logic Moderate improvement Large improvement
Best use today Cheap models with reasoning switched off, or small local models Hard multi-step tasks and agents

What this means for you as an engineer: chain-of-thought prompting is still a useful, cheap tool for non-reasoning models, for reasoning models with thinking switched off, and for small local models. On a reasoning model, control how much it thinks with the API settings in Part 3, not with prompt phrases.

1.5 A short history#


Part 2: How reasoning models are made#

Deep-dive

Lesson 06 owns training. This part is a short preview of the step that makes a model a reasoning model, followed by the part this lesson owns: why thinking longer helps, and how accuracy scales with it.

2.1 Where it fits in the training pipeline#

A reasoning model starts as an ordinary LLM: pretrained on huge amounts of text to predict the next token, then post-trained to follow instructions (lesson 06). The reasoning ability is mostly added in an extra post-training stage of reinforcement learning (RL), the kind of learning where a reward signal says how good an outcome was (lesson 01, 1.2).

2.2 Reinforcement learning with verifiable rewards#

The model is trained on problems whose answers a program can check automatically: maths problems with known answers, coding tasks with hidden unit tests, logic puzzles with checkable constraints. This is reinforcement learning with verifiable rewards (RLVR), and lesson 06, Part 8 covers it in full, including a runnable reward function.

The one idea you need here: only the outcome is rewarded, never the reasoning itself. The model writes several attempts per problem; attempts that reach the right answer are made more likely, and the rest less likely. Nobody tells the model how to reason, so whatever strategies tend to produce correct answers get reinforced: breaking problems down, checking work, noticing mistakes and trying again. As training goes on, responses grow longer and these behaviours emerge on their own. Lesson 06, 8.3 tells the story of how this produced DeepSeek-R1 and the other reasoning models.

2.3 Distillation: how small reasoning models are made#

Large-scale RL is expensive. A cheaper route to a small reasoning model is distillation: fine-tune a small model to imitate the reasoning traces of a large one (lesson 06, Part 10). DeepSeek released several distilled models this way (for example DeepSeek-R1-Distill-Qwen-1.5B), and small open models such as Qwen3-0.6B, which you'll run in Part 9, were also trained partly by learning from larger models.

What this means for you: small open reasoning models are good enough to experiment with, run privately and fine-tune, but they're much weaker than frontier models, and they're prone to long, rambling or looping reasoning.

2.4 Why longer thinking improves accuracy#

Several things happen when a model is allowed to think longer:

  1. More computation. Every reasoning token is another forward pass applied to the problem (1.1).
  2. Decomposition. A hard problem becomes a chain of easy steps, each well within what one forward pass can do.
  3. Error correction. A mistake written down can be noticed and fixed later. A mistake made silently inside one forward pass can't.
  4. Search. The model can try one approach, abandon it, and try another, a little like a person exploring several routes on scrap paper.

The analogy: an expert answering instantly vs the same expert allowed to use a notepad for ten minutes. The notepad doesn't add knowledge, but it lets the expert use what they know far more reliably.

2.5 The test-time scaling curve#

When OpenAI introduced o1 in September 2024, the central chart showed accuracy on a competition maths benchmark rising steadily as test-time compute increased, with compute on a logarithmic axis. Many papers since have found the same shape:

  • Accuracy rises with thinking tokens, with diminishing returns. Each doubling of the thinking budget tends to buy a similar-sized gain, so going from 1,000 to 2,000 tokens may help as much as going from 16,000 to 32,000, which costs 16 times more.
  • The curve flattens and can turn down. Beyond some point, extra thinking stops helping, and on some tasks longer reasoning makes answers worse (see 6.2).
  • The shape depends on the task. Hard multi-step problems gain a lot. Simple lookups, extraction and classification gain almost nothing.

What this means for you as an engineer: "more thinking" is a dial with a cost curve, not a free upgrade. Your job is to find the point on the curve where extra accuracy is still worth the extra cost and latency for your task, which is exactly what Part 10 teaches you to measure.


Part 3: Controlling reasoning across providers#

Every provider exposes reasoning through the same four concerns, with different names:

Concern The question it answers Example parameter names
Amount How hard should the model think? reasoning.effort, output_config.effort, thinking_level, thinking_budget
Visibility What do I get to see of the thinking? reasoning.summary, thinking.display, include_thoughts, reasoning.exclude
Accounting How many tokens did the thinking use? reasoning_tokens, thinking_tokens, thoughts_token_count
Continuity How do I hand the thinking back on the next call (especially with tools)? encrypted reasoning items, thinking-block signature, thought signatures, reasoning_details

All four samples below ask the same classic trick question (the bat and ball: the intuitive answer, $0.10, is wrong; the correct answer is $0.05). These samples need your API keys, so they were checked against each provider's official documentation and SDK and syntax-checked, but not run. Their output blocks are labelled illustrative.

3.1 OpenAI: reasoning effort and reasoning summaries#

Current OpenAI models (the GPT-5.x and GPT-6 families) are reasoning models. OpenAI recommends the Responses API for them: Chat Completions still works, but Responses gives better results and is required for some features, including tool calling with several of the newest models.

Amount: reasoning.effort. Possible values are none, minimal, low, medium, high, xhigh and max, but each model supports a different subset and has its own default. As of November 2026, for example:

Model Supported effort values Default
gpt-6-luna (cheapest, high volume) none, low, medium, high, xhigh, max medium
gpt-6.1-terra none, low, medium, high, xhigh, max medium
gpt-6.1-sol (balanced) low, medium, high, xhigh, max (no none or minimal) medium
gpt-6-astra (most capable) low, medium, high, xhigh, max (none returns a 400 error) Not stated on its model page, so set it explicitly

OpenAI's guidance per level, in short: none for latency-critical tasks such as voice, fast retrieval and classification; low for efficient reasoning with tools and chat; medium as the balanced default; high for hard debugging, deep planning and agentic coding; xhigh and max only when your evaluations show a clear benefit. With Chat Completions the parameter is spelled reasoning_effort. Effort controls how much the model thinks, not how long its answer is; OpenAI's separate length control, verbosity, is covered in lesson 05, 6.4.

Visibility: reasoning summaries. OpenAI never returns raw reasoning tokens. You can opt in to a summary with reasoning.summary set to "auto", "concise" or "detailed" (auto picks the most detailed summarizer the model supports). Your organization may need to complete verification before summaries work on the newest models.

Accounting: usage.output_tokens_details.reasoning_tokens (Responses) or usage.completion_tokens_details.reasoning_tokens (Chat Completions). These tokens are already included in output_tokens.

python
# openai_reasoning.py
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()  # reads OPENAI_API_KEY

response = client.responses.create(
    model="gpt-6-luna",                 # cheapest current GPT-6 model; reasoning by default
    reasoning={
        "effort": "high",               # none | low | medium (default) | high | xhigh | max
        "summary": "auto",              # opt in to a readable summary of the reasoning
    },
    max_output_tokens=25_000,           # caps reasoning + visible answer together
    input="A bat and a ball cost $1.10 in total. The bat costs $1.00 more "
          "than the ball. How much does the ball cost? Reply with just the amount.",
)

# The output is a list of items: reasoning item(s), then the assistant message.
for item in response.output:
    if item.type == "reasoning":
        for part in item.summary:
            print("Reasoning summary:", part.text)

if response.status == "incomplete":
    print("Stopped early:", response.incomplete_details.reason)
print("Answer:", response.output_text)

usage = response.usage
print("Input tokens:    ", usage.input_tokens)
print("Output tokens:   ", usage.output_tokens, "(billed at the output rate)")
print("  of which reasoning:", usage.output_tokens_details.reasoning_tokens)
Example output · illustrative7 lines
Reasoning summary: **Solving the bat-and-ball equation**

If the ball costs x, the bat costs x + 1.00, so 2x + 1.00 = 1.10 and x = 0.05. The tempting answer of $0.10 would make the total $1.20.
Answer: $0.05
Input tokens:     41
Output tokens:    412 (billed at the output rate)
  of which reasoning: 398

Notice the last two lines: the visible answer is a handful of tokens, but you pay for over 400 output tokens.

Other OpenAI reasoning features you'll meet:

  • reasoning.mode (standard or pro) on GPT-5.6 and GPT-6 models: pro performs substantially more model work for hard tasks, billed at the model's normal token rates but using many more tokens. It's independent of effort.
  • Carrying reasoning between calls. With store left on, pass previous_response_id and the server reuses earlier reasoning. In stateless mode (store=False, or zero data retention, an account setting where the provider stores nothing), reasoning items come back by default with an encrypted_content field: these encrypted reasoning items are opaque, and you pass them back yourself. reasoning.context (auto, current_turn, all_turns) controls whether reasoning from earlier turns is shown to the model again; GPT-5.6 models default to all_turns, earlier models to current_turn. Reasoning can only be reused within the same model family.
  • Changing effort mid-conversation. Changing the request-level effort breaks the prompt cache (5.6). On supported GPT-6 and later models, OpenAI lets you insert a configuration_update item into the conversation instead. It works in standard, single-agent mode, and OpenAI says not to combine it with automatic compaction or automatic truncation.

3.2 Anthropic Claude: adaptive thinking and effort#

Claude's reasoning is called thinking (older documentation and blog posts say extended thinking). The current API shape, as of November 2026, has two separate controls:

  • thinking chooses the thinking mode and what you see. The current mode is adaptive thinking, {"type": "adaptive"}: Claude decides per request whether to think and how much, and may skip thinking entirely on easy requests.
  • output_config.effort sets how much work Claude puts into the whole response, including how often and how deeply it thinks: low, medium, high, xhigh or max. It sits inside output_config, not inside thinking.

Defaults and on/off behaviour depend on the model:

Model Thinking by default? Can you turn thinking off? Default effort
claude-fable-5-2 (most capable; the older claude-fable-5-1 behaves the same) Yes (adaptive) No: {"type": "disabled"} and {"type": "between_tools"} both return a 400 error. Lower the effort instead. high
claude-opus-5-5 Yes (adaptive) No: {"type": "disabled"} returns a 400 error. Lower the effort instead. medium
claude-sonnet-5-5 Yes (adaptive) Up-front thinking only, with {"type": "between_tools"} at effort high or below high
claude-haiku-5-5 Yes (adaptive) Yes, {"type": "disabled"} at effort high or below medium

Visibility: thinking.display. You never get Claude's raw reasoning. With "display": "summarized" you get a readable summary; with "omitted" (the default on all current Claude models) thinking blocks come back with an empty text field. A beta value, "updates", returns only short progress notes the model writes between tool calls. Billing is identical under every setting.

Accounting: usage.output_tokens_details.thinking_tokens, which is included in usage.output_tokens.

python
# anthropic_thinking.py
import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

response = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=16_000,                  # hard cap on thinking + answer together
    thinking={"type": "adaptive", "display": "summarized"},  # default display is "omitted"
    output_config={"effort": "high"},   # low | medium (Haiku 5.5 default) | high | xhigh | max
    messages=[{
        "role": "user",
        "content": "A bat and a ball cost $1.10 in total. The bat costs $1.00 more "
                   "than the ball. How much does the ball cost? Reply with just the amount.",
    }],
)

if response.stop_reason == "refusal":   # always check before reading content
    raise SystemExit("The request was declined.")

for block in response.content:
    if block.type == "thinking":
        print("Thinking summary:", block.thinking)
        print("Signature (opaque, pass back unchanged):", block.signature[:20], "...")
    elif block.type == "text":
        print("Answer:", block.text)

print("Stop reason:  ", response.stop_reason)   # "max_tokens" means it was cut off
print("Output tokens:", response.usage.output_tokens, "(billed at the output rate)")
details = response.usage.output_tokens_details
print("  of which thinking:", details.thinking_tokens if details else 0)
Example output · illustrative6 lines
Thinking summary: Let the ball be x. Then the bat is x + 1.00 and 2x + 1.00 = 1.10, so x = 0.05. Check: 0.05 + 1.05 = 1.10. The intuitive 0.10 is wrong.
Signature (opaque, pass back unchanged): EqQBCkYIBRgCKkCx3Q ...
Answer: $0.05
Stop reason:   end_turn
Output tokens: 236 (billed at the output rate)
  of which thinking: 221

A response's content is a list of blocks. A thinking block has a thinking field (the summary text, or empty) and a signature: an encrypted copy of the full reasoning that the API uses to verify and reconstruct the thinking when you send the block back. Occasionally you may also see a redacted_thinking block, whose data field is encrypted with no readable text; treat it the same way and pass it back unchanged.

3.3 Google Gemini: thinking levels and thought summaries#

All current Gemini models (the 4, 3 and 2.5 series) are thinking models. Gemini 4 and 3.x models think by default at a per-model default level (usually medium; minimal on 3.5 Flash-Lite). Gemini 2.5 models use a dynamic token budget by default, except 2.5 Flash-Lite, where thinking is off unless you set a budget. There are two parameter generations:

  • thinking_level (Gemini 4 and Gemini 3): minimal, low, medium or high. Required for Gemini 4, recommended for Gemini 3.
  • thinking_budget (Gemini 2.5, legacy): a token count. -1 means dynamic, and 0 switches thinking off where allowed (2.5 Flash and 2.5 Flash-Lite; 2.5 Pro can't switch it off). On Gemini 4 Argon it's deprecated, and sending both thinking_budget and thinking_level returns a 400 error.

Supported levels and defaults vary, as of November 2026:

Model minimal low medium high
gemini-4-argon error ✅ ✅ default ✅
gemini-3.8-flash error ✅ ✅ default ✅
gemini-3.6-flash ✅ ✅ ✅ default ✅
gemini-3.5-flash-lite ✅ default ✅ ✅ ✅

minimal is the closest Gemini 3 gets to "off", and Google warns it doesn't guarantee zero thinking. Gemini 4 Argon can't switch thinking off at all.

Visibility: thought summaries. Set include_thoughts=True. Response parts with part.thought == True are summaries; the others are the answer. Thinking levels control the raw thoughts, not the length of the summary.

Accounting: usage_metadata.thoughts_token_count, billed at the output rate alongside candidates_token_count.

python
# gemini_thinking.py
from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()  # reads GEMINI_API_KEY

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="A bat and a ball cost $1.10 in total. The bat costs $1.00 more "
             "than the ball. How much does the ball cost? Reply with just the amount.",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level="high",      # low | medium (default) | high on this model
            include_thoughts=True,      # return thought summaries
        ),
    ),
)

for part in response.candidates[0].content.parts:
    if not part.text:
        continue
    if part.thought:                    # True for thought-summary parts
        print("Thought summary:", part.text)
    else:
        print("Answer:", part.text)

usage = response.usage_metadata
print("Thinking tokens:", usage.thoughts_token_count, "(billed at the output rate)")
print("Answer tokens:  ", usage.candidates_token_count)
Example output · illustrative6 lines
Thought summary: **Setting up the equation**

I'm defining the ball's price as x, which makes the bat x + 1.00. Together they total 1.10, so 2x = 0.10 and the ball is $0.05, not the intuitive $0.10.
Answer: $0.05
Thinking tokens: 287 (billed at the output rate)
Answer tokens:   5

Continuity: thought signatures. Gemini returns thought signatures, encrypted representations of its reasoning state, attached to response parts. With function calling they're required in the next request. The official SDK handles them automatically if you pass the model's full response content back into the history. You only manage them yourself if you edit history or call the REST API directly. Don't merge or split parts that carry signatures. Signatures you send back count as input tokens.

3.4 OpenRouter: one reasoning parameter for every model#

OpenRouter normalizes the different provider controls into one reasoning object, sent through the OpenAI SDK as extra_body because it isn't part of OpenAI's own schema:

json
"reasoning": {
  "effort": "high",      // max | xhigh | high | medium | low | minimal | none  (OpenAI-style)
  "max_tokens": 2000,    // OR a token budget (Anthropic/Gemini-2.5-style), not both
  "exclude": false,      // true = reason internally but don't return it (Chat Completions only)
  "enabled": true        // switch reasoning on at default settings
}

How OpenRouter maps it (as of November 2026, per its documentation):

You send OpenAI models Gemini 3 models Claude models Models with token budgets (e.g. some Qwen)
effort Passed as reasoning effort Mapped to thinkingLevel (xhigh becomes high; unsupported levels map to the nearest) Turned into a thinking budget (max(min(max_tokens × ratio, 128,000), 1,024), with the same ratios as the last column) on models that take budgets, or translated to the model's supported efforts on models that take efforts Converted into a budget as a share of max_tokens (about 95% for max/xhigh, 80% high, 50% medium, 20% low, 10% minimal)
max_tokens Converted to an effort level Passed as thinkingBudget, which Google maps to a level (so no precise control) Used directly as the thinking budget (minimum 1,024) on models that accept one Passed as the budget
exclude: true Reasoning still happens and is billed; it just isn't returned same same same

For Claude models that support thinking.display, OpenRouter defaults to summarized thinking, unlike Anthropic's own default of omitted.

Visibility: the reasoning text appears in message.reasoning (a string; reasoning_content is accepted as an alias, and it's the name you'll see in DeepSeek, vLLM and many framework examples), and the full structure in message.reasoning_details, a list of objects of type reasoning.summary, reasoning.encrypted or reasoning.text. Pass reasoning_details back unchanged in multi-turn and tool-use conversations, just as you would with the native APIs. Note that exclude only works on the Chat Completions endpoint; OpenRouter's Responses API ignores it and always returns reasoning items.

Accounting: usage.completion_tokens_details.reasoning_tokens.

python
# openrouter_reasoning.py
import os

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
)

question = ("A bat and a ball cost $1.10 in total. The bat costs $1.00 more "
            "than the ball. How much does the ball cost? Reply with just the amount.")

# One request shape, three providers: OpenRouter translates "effort"
# into each provider's own parameter.
for model in ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5", "google/gemini-3.8-flash"]:
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": question}],
        max_tokens=16_000,
        extra_body={"reasoning": {"effort": "high"}},  # or {"max_tokens": 4000}, {"exclude": True}
    )
    message = response.choices[0].message
    reasoning = getattr(message, "reasoning", None)  # OpenRouter-specific field
    usage = response.usage
    print(f"== {model}")
    print("Reasoning returned:", (reasoning or "")[:80].replace("\n", " "), "...")
    print("Answer:", message.content)
    print("Reasoning tokens:", usage.completion_tokens_details.reasoning_tokens,
          "of", usage.completion_tokens, "completion tokens")
Example output · illustrative12 lines
== openai/gpt-6-luna
Reasoning returned: **Solving for the ball's price** Let the ball cost x. Then the bat costs x + 1 ...
Answer: $0.05
Reasoning tokens: 384 of 391 completion tokens
== anthropic/claude-haiku-5.5
Reasoning returned: Let the ball be x, bat x + 1.00, so 2x + 1.00 = 1.10, x = 0.05. ...
Answer: $0.05
Reasoning tokens: 205 of 212 completion tokens
== google/gemini-3.8-flash
Reasoning returned: **Defining the variables** I'm setting the ball's price as x and the bat's as ...
Answer: $0.05
Reasoning tokens: 301 of 306 completion tokens

OpenRouter also tells you, per model, which reasoning settings it accepts. This runs without an API key, so you can try it now:

python
# or_reasoning_options.py
import httpx

# Public endpoint: no API key needed to list models.
resp = httpx.get("https://openrouter.ai/api/v1/models", timeout=30)
models = {m["id"]: m for m in resp.json()["data"]}

for model_id in [
    "openai/gpt-6-luna",
    "anthropic/claude-haiku-5.5",
    "anthropic/claude-sonnet-5.5",
    "google/gemini-3.8-flash",
    "google/gemini-3.5-flash-lite",
    "deepseek/deepseek-v4.1-flash",
]:
    r = models[model_id].get("reasoning") or {}
    print(f"{model_id:30s} efforts={r.get('supported_efforts')} "
          f"default={r.get('default_effort')} mandatory={r.get('mandatory')}")

The values below were read from OpenRouter's public model list on 3 November 2026; the list changes as models are added.

Example output · illustrative6 lines
openai/gpt-6-luna              efforts=['max', 'xhigh', 'high', 'medium', 'low', 'none'] default=medium mandatory=False
anthropic/claude-haiku-5.5     efforts=['max', 'xhigh', 'high', 'medium', 'low', 'none'] default=medium mandatory=False
anthropic/claude-sonnet-5.5    efforts=['max', 'xhigh', 'high', 'medium', 'low'] default=high mandatory=True
google/gemini-3.8-flash        efforts=['high', 'medium', 'low'] default=medium mandatory=True
google/gemini-3.5-flash-lite   efforts=['high', 'medium', 'low', 'minimal'] default=minimal mandatory=True
deepseek/deepseek-v4.1-flash   efforts=['max', 'high', 'low', 'none'] default=high mandatory=False

mandatory=True means reasoning can't be switched off for that model, so sending effort: "none" is rejected. Use this endpoint to drive effort pickers in your UI and to validate configuration before deploying.

3.5 Side-by-side comparison#

As of November 2026:

OpenAI (Responses API) Anthropic (Messages API) Gemini (generate_content, optional) OpenRouter (chat completions, optional)
Name for it Reasoning Thinking (adaptive thinking) Thinking Reasoning
Amount control reasoning.effort: none to max (model-dependent) output_config.effort: low to max thinking_level: minimal to high (Gemini 3/4); thinking_budget (2.5) reasoning.effort or reasoning.max_tokens
Token-budget control No Legacy only (budget_tokens, rejected on current models) thinking_budget on 2.5 (deprecated on Gemini 4) reasoning.max_tokens, mapped per model
Switch it off effort: "none" on models that support it (not Astra or 6.1 Sol) {"type": "disabled"} on some models only (not Fable 5.2, Fable 5.1 or Opus 5.5) thinking_budget=0 on 2.5 Flash; minimal is near-off on models that accept it (not 3.8 Flash); not on Gemini 4 Argon effort: "none" or enabled: false where not mandatory
Raw reasoning visible? Never Never Never Only for open models whose providers return it
Summaries reasoning.summary: auto/concise/detailed (opt in) thinking.display: summarized / omitted (default) include_thoughts=True Returned by default in reasoning / reasoning_details; exclude: true to hide
Usage field output_tokens_details.reasoning_tokens output_tokens_details.thinking_tokens usage_metadata.thoughts_token_count completion_tokens_details.reasoning_tokens
Billed as Output tokens Output tokens Output tokens Output tokens
Continuity token Reasoning items (encrypted_content) or previous_response_id signature on thinking blocks Thought signatures on parts reasoning_details
Interleaved with tools Yes Yes, automatic with adaptive thinking Yes Depends on the underlying model
Truncation signal status: "incomplete", reason max_output_tokens stop_reason: "max_tokens" Finish reason MAX_TOKENS finish_reason: "length"

3.6 Writing provider-neutral code#

If your application supports several providers, keep one reasoning setting in your own configuration and translate it at the edge. The catch is that the translation depends on the model, not just the provider: "off" is effort: "none" on gpt-6-luna but a 400 error on gpt-6-astra, and Gemini's near-off minimal is an error on gemini-3.8-flash. So this helper looks up each model's lowest supported setting in a small table and treats "off" as "as little as this model allows". It only builds the arguments, so it runs without keys:

python
# effort_adapter.py
import json

# The lowest reasoning setting each model accepts, from its documentation.
# Keep this table in configuration and fill it from the providers' docs or
# capability endpoints (see 3.7). One mapping per provider isn't enough.
LOWEST = {
    "gpt-6-luna": "none",                 # OpenAI: effort "none" switches reasoning off
    "gpt-6-astra": "low",                 # "none" returns a 400 error on this model
    "claude-haiku-5-5": "disabled",       # thinking can be switched off (at effort high or below)
    "claude-sonnet-5-5": "between_tools", # up-front thinking off; still thinks between tool calls
    "claude-opus-5-5": "low",             # thinking can't be switched off: use the lowest effort
    "gemini-3.5-flash-lite": "minimal",   # near-off, but not guaranteed zero thinking
    "gemini-3.8-flash": "low",            # "minimal" returns an error on this model
}

def reasoning_kwargs(model: str, level: str) -> dict:
    """Map an app-level setting ("off", "low", "medium", "high") to one model's parameters."""
    assert level in {"off", "low", "medium", "high"}
    if level == "off":
        level = LOWEST[model]             # "off" means "as little as this model allows"
    if model.startswith("gpt-"):          # OpenAI Responses API
        return {"reasoning": {"effort": level}}
    if model.startswith("claude-"):       # Anthropic Messages API
        if level in {"disabled", "between_tools"}:   # these modes take no other thinking fields
            return {"thinking": {"type": level}}
        return {"thinking": {"type": "adaptive", "display": "summarized"},
                "output_config": {"effort": level}}
    if model.startswith("gemini-"):       # google-genai generate_content config
        return {"thinking_config": {"thinking_level": level, "include_thoughts": True}}
    raise ValueError(f"Unknown model: {model}")

for model in LOWEST:
    for level in ["off", "high"]:
        print(f"{model:22s} {level:4s} -> {json.dumps(reasoning_kwargs(model, level))}")
Output14 lines
gpt-6-luna             off  -> {"reasoning": {"effort": "none"}}
gpt-6-luna             high -> {"reasoning": {"effort": "high"}}
gpt-6-astra            off  -> {"reasoning": {"effort": "low"}}
gpt-6-astra            high -> {"reasoning": {"effort": "high"}}
claude-haiku-5-5       off  -> {"thinking": {"type": "disabled"}}
claude-haiku-5-5       high -> {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "high"}}
claude-sonnet-5-5      off  -> {"thinking": {"type": "between_tools"}}
claude-sonnet-5-5      high -> {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "high"}}
claude-opus-5-5        off  -> {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "low"}}
claude-opus-5-5        high -> {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "high"}}
gemini-3.5-flash-lite  off  -> {"thinking_config": {"thinking_level": "minimal", "include_thoughts": true}}
gemini-3.5-flash-lite  high -> {"thinking_config": {"thinking_level": "high", "include_thoughts": true}}
gemini-3.8-flash       off  -> {"thinking_config": {"thinking_level": "low", "include_thoughts": true}}
gemini-3.8-flash       high -> {"thinking_config": {"thinking_level": "high", "include_thoughts": true}}

Three things to notice:

  • "Off" means different things per model. It's a real off switch on Luna and Haiku, "no up-front thinking" on Sonnet 5.5, and merely the lowest effort or level on Astra, Opus 5.5 and Gemini 3.8 Flash. Those models will still think, and you'll still pay for it.
  • The table is configuration, not code. In production, fill it from each provider's documentation or capability endpoints (3.7): Anthropic's Models API reports which thinking modes each model supports, and OpenRouter's supported_efforts (3.4) gives the same information for every model it serves.
  • The same word can mean different amounts of thinking on different models. Treat the mapping as configuration you test per model (Part 10), not as a guarantee of equivalent behaviour. Module 03 builds a fuller multi-provider client.

3.7 Keeping up to date#

Reasoning APIs have changed more often than any other part of the provider APIs: token budgets became effort levels, effort levels gained xhigh and max, defaults moved, and "off" disappeared on some models. Before you ship:

  1. Read the model's page, not just the feature guide: supported effort values and defaults are listed per model (OpenAI's and Gemini's model pages, Anthropic's thinking guide table).
  2. Query capabilities programmatically where you can: OpenRouter's /api/v1/models reasoning object (3.4) and Anthropic's Models API (client.models.retrieve(...)) report what each model supports.
  3. Lock your SDK versions (commit the lockfile) and read the changelog when you upgrade.
  4. Re-run your evaluation when you change model or effort. A model upgrade can change what each effort level actually does.

Part 4: What you can and can't see#

4.1 Raw, summarized, hidden and encrypted reasoning#

There are four forms in which you can encounter a model's reasoning:

Form What you get Where you see it
Raw The exact reasoning tokens the model generated Open-weight models you run yourself (<think>...</think>), and some open models served through gateways
Summarized A shorter, readable account of the reasoning, written by a summarizer OpenAI reasoning.summary, Claude display: "summarized", Gemini include_thoughts, OpenRouter reasoning for closed models
Hidden (omitted) Nothing, or an empty field; only the token count in usage OpenAI by default, Claude's default display: "omitted", Gemini without include_thoughts
Encrypted An opaque blob you can't read but must pass back OpenAI encrypted_content, Claude signature and redacted_thinking, Gemini thought signatures

No major closed provider returns raw reasoning through its standard API as of November 2026. (Anthropic's documentation says access to full thinking output is available only in rare cases, by arrangement with its sales team.) When you see a "thinking" panel in a chat product, you're almost always looking at a summary. Don't try to get round this by prompting for the reasoning instead: on current Claude flagship models, a request that tries to make the model reproduce its internal reasoning in the answer may be refused (7.2).

4.2 Why providers hide or summarize reasoning#

Providers give overlapping reasons:

  • Competitive protection. Raw reasoning traces are valuable training data. As 2.3 showed, a strong model's traces can be used to distill a competitor's model.
  • Safety and monitoring. When OpenAI introduced o1, it argued that a hidden chain of thought lets the model "think freely" without its reasoning being trained to look nice, which keeps it useful for monitoring the model for misbehaviour. Showing it to users would create pressure to make it presentable rather than honest.
  • Misuse prevention. Anthropic describes summarized thinking as giving "the full intelligence benefits of thinking while preventing misuse". Raw reasoning may contain content the final answer deliberately avoids.
  • Product quality. Raw traces are long, repetitive and full of dead ends; a summary is easier for users to read.

4.3 Reasoning text is not a faithful explanation#

This is the most important idea in this part. The reasoning a model writes is not guaranteed to be the real reason it gave its answer. Researchers call this the question of chain-of-thought faithfulness.

The evidence:

  • Turpin et al. (2023), "Language Models Don't Always Say What They Think": when a bias was planted in the prompt (for example, every example answer in the prompt was "(A)"), models followed the bias but wrote plausible step-by-step explanations that never mentioned it. Lesson 10, 6.5 covers this as a failure mode of explanations in general.
  • Lanham et al. (Anthropic, 2023), "Measuring Faithfulness in Chain-of-Thought Reasoning": editing or truncating a model's reasoning sometimes didn't change its final answer at all, which shows the answer didn't depend on the written reasoning. How much it depended varied by task and model.
  • Chen et al. (Anthropic, 2025), "Reasoning Models Don't Always Say What They Think": reasoning models were slipped a hint pointing to an answer. When they used the hint, Claude 3.7 Sonnet mentioned it in its reasoning only about 25% of the time, and DeepSeek R1 about 39% of the time. Unfaithful reasoning was, on average, longer than faithful reasoning, so length is no sign of honesty, and outcome-based RL training improved faithfulness only modestly before plateauing.
  • Baker et al. (OpenAI, 2025), on monitoring reasoning models for misbehaviour: reading the chain of thought was effective for catching a model "reward hacking" (exploiting flaws in its tests), but when training penalized bad thoughts, the model learned to hide its intent while continuing to misbehave.

On top of this, the summaries you receive from hosted APIs are produced by a separate summarizer, which adds another step between you and the actual computation.

What this means for you as an engineer:

  • ✅ Use reasoning summaries for debugging and UX. They're often a useful clue to where the model went wrong (a misread constraint, a wrong assumption), and showing progress during a long wait improves the user experience.
  • ❌ Don't present reasoning as an audit trail or explanation of a decision ("the AI rejected your loan because..."). It may not be the real reason. If you need a justification, ask the model to produce one in the answer and verify it independently, or make the decision with rules and evidence you control.
  • ❌ Don't parse answers out of the thinking. Read only the final answer. Thinking is free-form, may contain abandoned wrong answers, and its format can change at any time.
  • ❌ Don't treat a confident trace as a correct one. Check outputs with tests, validators and evaluation (Part 10).

Part 5: Cost, latency and limits#

5.1 Reasoning tokens are billed as output#

On every provider covered here, reasoning tokens are billed at the output-token rate, whether you see them or not. With summaries, you pay for the full reasoning, not the shorter summary. With hidden reasoning, you pay for tokens you never see. Output tokens are usually several times more expensive than input tokens, so reasoning can dominate your bill. Lesson 09, 6.4 covers the billing rules and how each provider reports reasoning tokens on the invoice; this section shows the effect.

Here's what that does to the cost of an otherwise identical request:

python
# cost_calc.py
# Example prices in US dollars per million tokens. NOT real prices: look up
# your model's current prices on the provider's pricing page.
INPUT_PRICE = 1.00
OUTPUT_PRICE = 5.00   # reasoning tokens are billed at this output rate

def request_cost(input_tokens, visible_output_tokens, reasoning_tokens):
    billed_output = visible_output_tokens + reasoning_tokens
    return (input_tokens * INPUT_PRICE + billed_output * OUTPUT_PRICE) / 1_000_000

# The same request (1,500 input tokens, a 200-token visible answer)
# with different amounts of hidden reasoning.
scenarios = [
    ("No reasoning", 0),
    ("Low effort", 800),
    ("Medium effort", 3_000),
    ("High effort", 12_000),
]
baseline = request_cost(1_500, 200, 0)
for name, reasoning in scenarios:
    cost = request_cost(1_500, 200, reasoning)
    per_million_requests = cost * 1_000_000
    print(f"{name:14s} reasoning={reasoning:>6,}  cost/request=${cost:.4f}  "
          f"x{cost / baseline:5.1f}  per 1M requests=${per_million_requests:>9,.0f}")
Output4 lines
No reasoning   reasoning=     0  cost/request=$0.0025  x  1.0  per 1M requests=$    2,500
Low effort     reasoning=   800  cost/request=$0.0065  x  2.6  per 1M requests=$    6,500
Medium effort  reasoning= 3,000  cost/request=$0.0175  x  7.0  per 1M requests=$   17,500
High effort    reasoning=12,000  cost/request=$0.0625  x 25.0  per 1M requests=$   62,500

The visible answer is the same 200 tokens in every row, yet high effort costs 25 times as much as no reasoning. The reasoning-token counts here are invented for illustration; real counts vary enormously by model, task and effort, from zero on easy prompts to tens of thousands on hard ones. Measure yours from the usage fields in Part 3.

5.2 Latency#

Reasoning adds latency in a specific way:

  • Time to first visible token goes up. The model must finish (or largely finish) thinking before it writes the answer. If a model thinks for 3,000 tokens at 100 tokens per second, the user waits 30 seconds before seeing anything.
  • Total time goes up roughly in proportion to the extra tokens generated.
  • Latency becomes less predictable, because adaptive models think more on some requests than others. Monitor percentiles such as p95 and p99 (the latency that 95% or 99% of requests beat), not just averages.

What you can do about it:

Technique How it helps
Lower the effort, or switch reasoning off for that route Fewer tokens to generate
Stream the response and show thinking summaries or progress updates (5.8) The wait feels shorter, and users see that work is happening
Hide thinking you don't display (Anthropic display: "omitted") Anthropic notes this gives a faster time to the first answer token when streaming, because thinking text isn't streamed
Ask for a short preamble first OpenAI suggests asking the model for a brief preamble before deeper reasoning, for faster first visible output. On GPT-5.5 and GPT-5.4, mark such preambles with the assistant-message field phase: "commentary" (and the real answer with "final_answer") when you replay history; a missing phase can make a preamble count as the final answer
Move slow work to the background Run high-effort jobs asynchronously or in batch, and notify the user when done
Use a faster serving tier Several providers sell faster output speeds at a premium

5.3 Reasoning and the output-token cap#

The output-token cap (max_output_tokens on OpenAI Responses, max_completion_tokens on OpenAI Chat Completions, where the older max_tokens doesn't work with reasoning models, max_tokens on Anthropic and OpenRouter, max_output_tokens on Gemini) limits reasoning and visible answer together. That creates a nasty failure mode: if the model spends the whole allowance thinking, you get an empty or truncated answer and still pay for all the reasoning.

Provider How you detect truncation
OpenAI response.status == "incomplete" and response.incomplete_details.reason == "max_output_tokens", possibly with no output text at all
Anthropic response.stop_reason == "max_tokens"
Gemini The candidate's finish reason is MAX_TOKENS
OpenRouter finish_reason == "length", often with empty content. Compare reasoning_tokens with completion_tokens

Guidance:

  • Set the cap with reasoning in mind. OpenAI recommends reserving at least 25,000 tokens for reasoning and output when you start experimenting, then tuning down once you know your typical usage. A cap sized for a 300-token answer is far too small for a reasoning model.
  • Handle truncation explicitly in code: detect it, log it, and decide whether to retry with a higher cap or lower effort.
  • Lower effort rather than squeezing the cap when cost is the problem. A tight cap doesn't make the model think efficiently; it just cuts it off.
  • Large caps mean long requests: use streaming for big outputs to avoid HTTP timeouts (the Anthropic SDK, for example, requires streaming for very large max_tokens values).

5.4 Reasoning and the context window#

Reasoning tokens occupy space in the context window (lesson 07) just like any other tokens:

flowchart LR
    subgraph win ["One request's context window"]
        I["Input tokens<br/>system + history + new message"]
        T["Thinking tokens<br/>(this turn)"]
        O["Visible answer tokens"]
    end
    I --> T --> O
    MT["max output tokens cap"] -. "limits" .-> T
    MT -. "limits" .-> O
  • This turn's reasoning always takes up room, so a very long input plus a high reasoning effort can hit the window limit.
  • Earlier turns' reasoning depends on the provider and model. Current Claude models keep prior thinking blocks in context and bill them as input tokens; older ones strip them. OpenAI's reasoning.context decides whether earlier reasoning is shown again (GPT-5.6 models default to all turns). Gemini's thought signatures count as input tokens when sent back.
  • Long agent sessions accumulate reasoning. Budget for it, and use the provider's context-management features (compaction, clearing old thinking blocks) covered in lesson 07, 4.5 and Module 08A.

5.5 Parameter restrictions on reasoning models#

Reasoning models restrict several generation settings you met in lesson 05. Lesson 05, 6.2 has the full per-provider matrix; these are the restrictions that trip people up when they move to a reasoning model (as of November 2026):

Setting OpenAI Anthropic Gemini
temperature, top_p, top_k Must be removed when reasoning.effort isn't none 400 error for non-default values on current models (Fable 5.2, Opus 5.5, Sonnet 5.5, Haiku 5.5 and others), thinking or not. Since API version 2026-10-21, sending temperature, top_p or top_k at all returns a 400, even at the parameter's default value, so don't assume top_p=1 is safe: omit them (lesson 05, 6.2) Silently ignored on Gemini 3.5 Flash-Lite, 3.6 Flash, 3.8 Flash, Gemini 4 and newer, with errors announced for a future generation. For earlier Gemini 3 models, Google recommended keeping temperature at its default of 1.0
Log probabilities logprobs and top_logprobs only with effort none Not offered See lesson 05's matrix
Assistant prefill (writing the start of the answer for the model; not the prefill phase of lesson 05) Not offered Rejected (400) on Claude 4.6 and later A request whose last turn has role: "model" is rejected on Gemini 3.6 Flash and later
Forcing a specific tool call Supported tool_choice any/tool rejected on Fable 5.2, Opus 5.5 and Sonnet 5.5; use auto with strict tools or structured outputs Supported

Why? Providers say their reasoning models are optimized for the default sampling settings, and that you should steer them with effort, prompting and structured outputs instead. A plausible technical reason, discussed in lesson 05, 6.1, is that long reasoning chains are prone to repetition loops at low temperature. Turning the temperature down to 0 wouldn't make a reasoning model deterministic anyway. Control effort, not temperature. If you need reproducibility, store outputs; don't expect identical regenerations (lesson 01, 7.5).

5.6 Reasoning and prompt caching#

Prompt caching (lesson 07, Part 7; production use in Module 11B) gives a large discount on repeated prompt prefixes. Reasoning settings interact with it: on Anthropic, the effort level (and thinking configuration) is part of the cached prefix, so changing effort between requests invalidates the cache (one of the cache-busting changes listed in lesson 07, 7.4). Anthropic's documentation demonstrates a full cache miss after changing effort from medium to low. Pick an effort per conversation and keep it; if some turns need more or less thinking, use the providers' per-message mechanisms instead (OpenAI's configuration_update items, Anthropic's per-message effort in beta) or steer with prompt wording.

5.7 Budgeting reasoning in production#

  1. Set effort per route, not globally. A support-chat route and a code-review route need different settings (Part 6).
  2. Log reasoning tokens from usage on every request, alongside latency and outcome. Track the reasoning share of output tokens per route.
  3. Alert on drift. A model upgrade or prompt change can double reasoning usage overnight with no visible change in answers.
  4. Cap the damage. Use output-token caps sized from measured p99 usage, and, for agents, per-task token or step budgets.
  5. Use batch or flex processing for non-urgent reasoning-heavy jobs where providers offer discounts.
  6. Re-check the trade-off with your evaluation set whenever prices, models or prompts change (Part 10).

5.8 Streaming reasoning#

Lesson 05, Part 8 explains streaming. With a reasoning model, the stream starts with thinking, so the first events you receive usually aren't answer text. Even hidden thinking produces events, and a long hidden think looks to the user like a pause before anything appears.

Provider Thinking arrives as Continuity data in the stream When thinking is hidden
OpenAI (Responses) response.reasoning_summary_text.delta events, only if you requested reasoning.summary The reasoning output item (with encrypted_content in stateless mode) No reasoning text events, just a pause before the first response.output_text.delta
Anthropic A content_block_start for a thinking block, then content_block_delta events whose delta.type is "thinking_delta" One signature_delta just before the thinking block closes With display: "omitted": one thinking_delta with an empty string, then the signature_delta; answer text starts sooner
Gemini Streamed chunks (generate_content_stream) whose parts have part.thought == True, with include_thoughts=True Thought signatures attached to parts No thought parts, just a pause before the answer text
OpenRouter (Chat Completions) reasoning_details entries in each chunk's choices[0].delta reasoning.encrypted entries in reasoning_details With exclude: true, no reasoning fields

This Claude sample streams the same question twice, printing thinking and answer as they arrive, and measures the time to the first answer token:

python
# anthropic_stream.py
import time

import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()

for display in ["summarized", "omitted"]:
    print(f"===== display={display}")
    start, first_answer_token = time.time(), None
    with client.messages.stream(
        model="claude-haiku-5-5",
        max_tokens=16_000,
        thinking={"type": "adaptive", "display": display},
        output_config={"effort": "high"},
        messages=[{"role": "user",
                   "content": "Is 391 a prime number? Answer in one sentence."}],
    ) as stream:
        for event in stream:
            if event.type == "content_block_start":           # a new block begins
                print(f"\n[{event.content_block.type}] ", end="")
            elif event.type == "content_block_delta":
                if event.delta.type == "thinking_delta":     # empty text when display="omitted"
                    print(event.delta.thinking, end="", flush=True)
                elif event.delta.type == "text_delta":       # the visible answer
                    if first_answer_token is None:
                        first_answer_token = time.time() - start
                    print(event.delta.text, end="", flush=True)
        final = stream.get_final_message()
    if final.stop_reason == "refusal":
        raise SystemExit("The request was declined.")
    print(f"\nTime to first answer token: {first_answer_token:.1f}s | "
          f"output tokens: {final.usage.output_tokens}")
Example output · illustrative10 lines
===== display=summarized

[thinking] To check 391, test prime divisors up to √391 ≈ 19.8. Not divisible by 2, 3, 5, 7, 11 or 13. 17 × 23 = 391, so it's composite.
[text] No: 391 = 17 × 23, so it isn't prime.
Time to first answer token: 3.9s | output tokens: 231
===== display=omitted

[thinking] 
[text] No: 391 = 17 × 23, so it isn't prime.
Time to first answer token: 3.1s | output tokens: 224

What this means for your UI:

  • Show something during the thinking phase: a summary stream, progress updates, or at least a "thinking…" indicator driven by the thinking events. Otherwise users see a frozen screen.
  • Route events by type. Render thinking deltas in a collapsible panel and text deltas as the answer; never concatenate them into one string.
  • Measure time to the first answer token, not the first event, when you compare settings. Hiding thinking you don't display shortens it; it doesn't reduce the tokens you pay for.

Part 6: When to use reasoning, and when not to#

6.1 A decision table#

Task Reasoning? Why
Multi-step maths, quantitative analysis ✅ High Many dependent steps; checking catches arithmetic slips
Writing or debugging non-trivial code ✅ Medium–high Planning, edge cases and self-checking pay off
Planning, scheduling, constraint satisfaction ✅ Medium–high Needs search and backtracking
Agentic tasks with many tool calls ✅ Medium–high Deciding what to do next after each tool result is reasoning (Part 8)
Complex document analysis (contracts, policies, comparing sources) ✅ Medium Cross-referencing and careful reading benefit
Hard classification with subtle rules ⚖️ Test it Sometimes helps; measure before paying for it
Simple extraction (names, dates, fields into JSON) ❌ Off / low No multi-step reasoning involved
Simple classification (sentiment, topic, routing) ❌ Off / low Fast pattern recognition, not reasoning
Chit-chat, rewriting, translation, summarizing short text ❌ Off / low Fluency matters, not deliberation
Latency-critical UX (autocomplete, voice, live suggestions) ❌ Off / minimal Users can't wait for thinking
Very high-volume, low-value requests ❌ Off / low Cost multiplies by volume
Questions needing facts the model lacks ❌ Won't help Reasoning can't create missing knowledge; use RAG or tools (11.3)

6.2 Overthinking#

More thinking isn't just wasteful on easy problems; it can be harmful.

  • Wasted tokens. Research titled "Do NOT Think That Much for 2+3=?" (Chen et al., December 2024) showed early reasoning models spending hundreds of tokens, with repeated re-checking, on trivial arithmetic.
  • Worse answers. "Inverse Scaling in Test-Time Compute" (Gema et al., 2025) built tasks where longer reasoning lowered accuracy: models were distracted by irrelevant details, latched onto spurious patterns, or lost track of constraints as their reasoning grew.
  • Second-guessing. Long traces sometimes reach the right answer, then "correct" it into a wrong one. The same happens when you ask a model "are you sure?" without giving it new information: self-correction without external feedback often flips right answers to wrong (lesson 10, 6.6).

Adaptive thinking (3.2) and dynamic thinking (3.3) were introduced partly to reduce this: the model decides how much to think per request. They reduce the problem but don't remove it, which is why effort is still yours to set.

6.3 Routing patterns#

Most production systems don't pick one setting for everything. Common patterns:

flowchart TD
    R["Incoming request"] --> C{"Route by task type"}
    C -- "extraction, classification,<br/>chit-chat, autocomplete" --> L["Reasoning off or low effort<br/>(fast, cheap)"]
    C -- "multi-step maths, code,<br/>planning, agents" --> H["Medium or high effort"]
    L --> V{"Output passes<br/>validation?"}
    V -- "yes" --> OK["Return answer"]
    V -- "no" --> H
    H --> OK
  • Static routing: each endpoint or feature has its own model and effort, chosen by evaluation. Simple and predictable; start here.
  • Classifier routing: a cheap model or rules decide whether a request is "hard" and route it accordingly.
  • Escalation: try a cheap, low-effort call first; escalate to high effort only if the output fails validation (a schema check, a unit test, a confidence check). Great when most requests are easy and failures are detectable.
  • Planner–executor: a high-effort model plans the work once; low-effort or non-reasoning models execute the individual steps (Module 08A).

Before building a multi-model cascade, test the simpler option: the strongest model at a lower effort. Providers report that newer models at low effort often match older models at high effort, and one model keeps your prompt cache and your code simpler.


Part 7: Prompting reasoning models#

Deep-dive

Module 04 owns prompt engineering. This part covers only what changes when the model reasons.

7.1 Give goals and constraints, not step-by-step scripts#

With standard models, prompts often spell out a procedure: "First do X. Then do Y. Then check Z." Reasoning models plan for themselves, and they usually do better when you describe what you want and let them work out how. OpenAI's guidance for its reasoning models is to give "a clear goal, strong constraints, and an explicit output contract without prescribing every intermediate step".

Before (scripted, written for a standard model):

text
Step 1: Read the error log below.
Step 2: List every exception.
Step 3: For each exception, find the line of code that caused it.
Step 4: Think step by step about the root cause.
Step 5: Write a fix.

After (goal, constraints and output contract):

text
Goal: find the root cause of the failing checkout job and propose the smallest safe fix.

Context: <error log> and <relevant source files> are below.
Constraints:
- Don't change the public API of PaymentClient.
- The fix must be backwards compatible with v2 webhooks.
Done means: you can name the root cause, point to the exact lines, and explain why
the fix resolves it without breaking the constraints.

Output format:
ROOT CAUSE: <one paragraph>
FIX: <unified diff>
RISKS: <bullet list, or "none">

The second prompt tells the model what success looks like and how you'll check it, which is exactly the information a reasoning model uses to direct its thinking.

7.2 Don't script the thinking#

  • Don't add "think step by step" or "explain your reasoning". OpenAI's guidance says this is "unnecessary" for reasoning models and may not help ("and can sometimes hinder it"). The model already reasons; asking for it in the answer makes it write reasoning twice, and you pay twice.
  • Don't ask for the reasoning in the output if you don't need it. If you do need an explanation for users, ask for a short, specific justification section, and remember it's an answer the model wrote, not a transcript of its thinking (4.3).
  • Use plain-language steering sparingly. Phrases such as "This is a hard problem; think carefully" or "Answer directly without deliberating" can shift how much a model thinks, but effort settings are the more reliable control (3.2).

7.3 Be explicit about the output format#

Reasoning models put their effort into the problem, and can be loose about presentation unless told. Specify the format precisely:

  • Give an output contract: exact sections, labels or JSON schema, length limits.
  • For machine-readable output, use structured outputs (JSON schemas enforced by the API) rather than asking nicely (Module 03 and Module 04).
  • Put the final answer where code can find it reliably, never "somewhere in the reasoning".
  • OpenAI notes that its reasoning models avoid Markdown in API responses by default; if you want Markdown, include the line Formatting re-enabled at the start of your developer message.

7.4 Other differences worth knowing#

  • Try zero-shot first. Reasoning models often need no examples. If you add examples, make sure they match your instructions exactly, since a reasoning model will notice and try to reconcile inconsistencies.
  • Use clear delimiters (headings, XML-style tags, Markdown sections) to separate instructions, context and data.
  • Developer and system messages still set the rules (Module 04). In OpenAI's APIs, put those rules in the instructions parameter or a developer message.
  • Tell agents what "done" means and how to verify their work. A reasoning model will use a stated verification step ("run the tests before finishing").
  • Prompts written for older models can be too prescriptive. Providers' migration guides repeatedly note that newer reasoning models follow instructions more literally, so heavy-handed "YOU MUST ALWAYS..." prompts tuned for older models can now cause over-application. Simplify when you migrate, and re-evaluate.

Part 8: Reasoning with tools and agents#

Deep-dive

Module 08A owns tool use and agents in depth. Here's what reasoning changes.

8.1 Interleaved thinking#

In an agent loop, the model calls a tool, your code runs it, and you send the result back (Module 08A). With interleaved thinking, the model thinks between tool calls as well as before the first one, reasoning about each result before deciding what to do next:

sequenceDiagram
    participant App as Your app
    participant LLM as Reasoning model
    App->>LLM: User request + tool definitions
    Note over LLM: think: plan which data is needed
    LLM-->>App: thinking block + tool call (get_order A17)
    App->>LLM: full assistant turn (thinking included) + tool result
    Note over LLM: think again: interpret the result, decide next step
    LLM-->>App: thinking block + tool call (get_order B22)
    App->>LLM: full history + tool result
    Note over LLM: think: combine both results
    LLM-->>App: final answer

This is what makes reasoning models good agents: an unexpected tool result (an error, an empty search, a surprising value) gets thought about rather than blindly passed along. All four providers support it with their current reasoning models; on Anthropic it's automatic with adaptive thinking, with no extra configuration.

8.2 Pass the reasoning back#

From the model's point of view, a tool-use loop is one assistant turn that you happen to split across several API calls. To continue its reasoning where it left off, the model needs its earlier reasoning back. That's what the encrypted continuity tokens from 3.5 are for:

Provider What to pass back in the next request
OpenAI (Responses) All output items since the last user message, including reasoning items, function calls and function outputs; or simply previous_response_id
Anthropic The whole assistant content list, unchanged, including thinking and redacted_thinking blocks with their signatures
Gemini The model's full response content (the SDK keeps thought signatures attached); never merge or split signed parts
OpenRouter The assistant message's reasoning_details array, unchanged
Open-weight models you host (Qwen3, DeepSeek-R1 and others) Usually nothing: their raw reasoning isn't signed, and model cards such as Qwen3's say past turns should contain only the final answer. Servers such as vLLM return the reasoning in a separate reasoning_content field that you normally don't replay. Check the model card for tool-calling exceptions

Within a tool-use turn vs across completed turns. The hosted-API rule above is strict inside a tool loop: until the model gives its final answer, send its reasoning back unchanged. Once a turn is complete, the rules relax. Anthropic says sending back earlier turns' thinking is only strictly necessary with tools; you can pass it all back and let the API keep or strip it per model (which is the simplest correct approach), and when you trim history, removing all thinking blocks is allowed (lesson 07, 4.2). OpenAI and Gemini behave similarly with their own continuity data. Open-weight chat templates go the other way and expect old reasoning removed (9.5).

Here's a complete Claude tool loop that does this correctly:

python
# anthropic_tools_thinking.py
import json

import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()

tools = [{
    "name": "get_order",
    "description": "Look up an order by ID. Returns status and delivery date.",
    "input_schema": {
        "type": "object",
        "properties": {"order_id": {"type": "string"}},
        "required": ["order_id"],
    },
}]

def get_order(order_id: str) -> dict:          # a fake backend for the demo
    orders = {"A17": {"status": "delayed", "eta": "2026-11-04"},
              "B22": {"status": "delivered", "eta": "2026-10-28"}}
    return orders.get(order_id, {"error": "not found"})

messages = [{"role": "user",
             "content": "Which of my orders A17 and B22 still needs attention, and why?"}]

for step in range(10):                          # never let an agent loop run forever
    response = client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=16_000,
        thinking={"type": "adaptive", "display": "summarized"},
        output_config={"effort": "medium"},
        tools=tools,
        messages=messages,
    )
    if response.stop_reason == "refusal":       # check before reading content
        raise SystemExit("The request was declined.")
    for block in response.content:
        if block.type == "thinking" and block.thinking:
            print("[thinking]", block.thinking[:100].replace("\n", " "), "...")
        elif block.type == "tool_use":
            print("[tool call]", block.name, block.input)
        elif block.type == "text":
            print("[answer]", block.text)

    if response.stop_reason != "tool_use":
        break

    # Append the WHOLE assistant turn, thinking blocks included, unchanged.
    messages.append({"role": "assistant", "content": response.content})
    results = [{"type": "tool_result", "tool_use_id": b.id,
                "content": json.dumps(get_order(**b.input))}
               for b in response.content if b.type == "tool_use"]
    messages.append({"role": "user", "content": results})   # all results in one message
else:
    raise RuntimeError("Step limit reached without a final answer.")
Example output · illustrative5 lines
[thinking] I need the status of both orders. I'll look them up in parallel. ...
[tool call] get_order {'order_id': 'A17'}
[tool call] get_order {'order_id': 'B22'}
[thinking] A17 is delayed with a new ETA of 4 November; B22 was delivered on 28 October. ...
[answer] Order A17 needs attention: it's delayed and now expected on 4 November. Order B22 was delivered on 28 October, so there's nothing to do there.

The one line that matters most is messages.append({"role": "assistant", "content": response.content}). A common bug is to append only the text, or to rebuild the assistant message from the tool calls alone, which silently throws away the reasoning (or triggers a validation error).

Anthropic's preserved-thinking rules. On Claude 5.1 and later models (Fable 5.2, Fable 5.1, Opus 5.5, Sonnet 5.5 and Haiku 5.5 among them), each thinking block is bound to everything before it: the system prompt, the tool list and every earlier message. When you send a thinking block back, the API checks that its prefix is unchanged. As of November 2026:

Question Rule
What breaks the binding? Editing, reordering or deleting earlier messages, changing the system prompt or the tool list, or shortening an earlier tool result, and then sending a later thinking block back. Removing a thinking block from the middle of the sequence also invalidates every thinking block after it
What is allowed? Appending; removing the oldest thinking blocks, the newest, or all of them (the model just loses that reasoning); and Anthropic's server-side compaction and context editing (lesson 07, 4.5), which the check accepts
What happens when it breaks? For accounts created on or after 31 August 2026 (that includes every new learner), and for every account on Fable 5.2, the API rejects the request with a 400 invalid_request_error that names the first failing block. For older accounts on Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1, enforcement varies by account, so a clean run isn't proof
Can I change that? Yes, with thinking.block_binding.prefix_mismatch_behavior (beta header thinking-binding-controls-2026-08-01). "error" always returns the 400. "drop_block" drops each failing block and every thinking block after it, and the request succeeds: the model answers without that reasoning, which usually costs extra output tokens, and the prompt cache restarts at the edit. Anthropic calls drop_block a stopgap; fix the edit instead

A clean run on an older account doesn't prove your code keeps the prefix intact, so test history trimming on a new account or with "error" set. Lesson 07, 4.2 shows which history-management strategies stay compatible.

8.3 Design implications for agents#

  • Effort per step. The first call after a user message usually carries most of the planning; follow-up calls that only digest tool results often need less. Providers increasingly let you change effort mid-conversation without breaking the cache (5.6).
  • Show progress. Agents with reasoning can run for minutes. Surface thinking summaries or progress updates (for example Anthropic's display: "updates" beta) so users know what's happening.
  • Budget whole tasks, not just requests. A per-request max_tokens doesn't limit a 40-step loop. Add step limits, total-token budgets and timeouts in your agent code (Module 08A).
  • Reasoning doesn't make tools safe. A reasoning agent can still be tricked by malicious text inside a tool result (prompt injection) or reason its way into a harmful action. Keep permissions narrow and confirmations in place (Module 12).

Part 9: Run a reasoning model on your laptop#

Deep-dive

Hosted APIs hide the raw reasoning. Open-weight models don't, so a small local model is the best way to see what thinking looks like and to measure its effect for free.

9.1 The model: Qwen3-0.6B, a hybrid thinking model#

Qwen/Qwen3-0.6B is a 0.6-billion-parameter open model from Alibaba's Qwen3 family (April 2025), small enough to run on a laptop CPU. Like the rest of the family, it's a hybrid model: one set of weights that can either think or answer directly, controlled by an enable_thinking switch in its chat template. When thinking is on, the model writes its reasoning between <think> and </think> tags before the answer.

Other small open reasoning models you can try the same way: deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B (always thinks), and larger Qwen3 sizes. Tools such as Ollama and llama.cpp run quantized versions (Module 11C).

9.2 Watch it think#

This script asks two questions, each with thinking off and then on, and separates the reasoning from the answer. It uses your GPU if you have one (NVIDIA or Apple silicon) and falls back to the CPU, which is slower but works. Long reasoning is trimmed to its start and end so the output stays readable:

python
# local_think.py
import time

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL = "Qwen/Qwen3-0.6B"            # a small open "hybrid" model: thinking can be switched on/off
tokenizer = AutoTokenizer.from_pretrained(MODEL)
device = ("cuda" if torch.cuda.is_available()          # NVIDIA GPU
          else "mps" if torch.backends.mps.is_available()  # Apple silicon GPU
          else "cpu")
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32).to(device)
END_THINK = tokenizer.convert_tokens_to_ids("</think>")

def ask(question: str, thinking: bool):
    messages = [{"role": "user", "content": question}]
    prompt = tokenizer.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True,
        enable_thinking=thinking,         # the switch
    )
    inputs = tokenizer(prompt, return_tensors="pt").to(device)
    torch.manual_seed(0)
    start = time.time()
    out = model.generate(**inputs, max_new_tokens=2048, do_sample=True,
                         temperature=0.6, top_p=0.95, top_k=20)   # Qwen's recommended thinking settings
    seconds = time.time() - start
    new_ids = out[0][inputs.input_ids.shape[1]:].tolist()
    # Everything up to the last </think> token is reasoning; the rest is the answer.
    if END_THINK in new_ids:
        split = len(new_ids) - new_ids[::-1].index(END_THINK)
    else:                                 # no </think>: all reasoning (or, if thinking is off, all answer)
        split = len(new_ids) if thinking else 0
    reasoning = tokenizer.decode(new_ids[:split], skip_special_tokens=True).strip()
    answer = tokenizer.decode(new_ids[split:], skip_special_tokens=True).strip()
    return reasoning, answer, split, len(new_ids) - split, seconds

questions = [
    "Is 391 a prime number? Answer yes or no, with a one-line reason.",
    "I have 3 boxes of 12 eggs. I drop 2 boxes, and half the eggs in each dropped box break. How many unbroken eggs do I have?",
]
for question in questions:
    print("#" * 20, question)
    for thinking in [False, True]:
        reasoning, answer, n_reason, n_answer, secs = ask(question, thinking)
        print(f"===== thinking={thinking}  ({n_reason} reasoning + {n_answer} answer tokens, {secs:.1f}s)")
        if reasoning:                     # long traces: show the start and the end
            shown = reasoning if len(reasoning) < 1500 else reasoning[:900] + "\n[...]\n" + reasoning[-500:]
            print("--- reasoning ---\n" + shown)
        print("--- answer ---\n" + (answer or "(none: thinking hit the token limit)"))
Output · on an Apple-silicon laptop GPU; your text and timings will differ72 lines
#################### Is 391 a prime number? Answer yes or no, with a one-line reason.
===== thinking=False  (0 reasoning + 12 answer tokens, 0.6s)
--- answer ---
Yes, 391 is a prime number.
===== thinking=True  (584 reasoning + 28 answer tokens, 14.5s)
--- reasoning ---
<think>
Okay, so I need to figure out if 391 is a prime number. Let me start by recalling what a prime number is. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. So, the main thing I need to check is whether 391 has any divisors besides 1 and itself.

First, I should check if it's even. The number ends with a 1, so it's odd. That means it's not divisible by 2. Next, check divisibility by 3. Adding the digits: 3 + 9 + 1 = 13. Since 13 isn't divisible by 3, 391 isn't divisible by 3 either.

Now, check for divisibility by 5. The number ends with 1, so it's not divisible by 5. What about 7? Let me try dividing 391 by 7. 7 times 50 is 350, so subtract that from 391: 391 - 350 = 41. Now, 41 divided by 7 is about 5.857, so not a whole number. So 7 doesn't divide 391.

Next, check 11. The alternating sum of the digits: 3 - 9 + 1 = -5. Since -5 isn
[...]
 leaves a remainder of 1, which means 13 doesn't divide 391.

What about 17? Let me see. 17 times 23 is 391. Wait, 17 times 20 is 340, plus 17 times 3 is 51, so 340 + 51 = 391. Oh! So 17 times 23 equals 391. That means 391 is not a prime number because it's divisible by 17 and 23. 

But wait, let me double-check that multiplication. 17 multiplied by 23: 10*23=230, 7*23=161, so 230+161=391. Yep, that's correct. So 391 is not prime. 

So the answer should be no, 391 is not a prime number.
</think>
--- answer ---
Answer: No, 391 is not a prime number. It is divisible by 17 and 23.
#################### I have 3 boxes of 12 eggs. I drop 2 boxes, and half the eggs in each dropped box break. How many unbroken eggs do I have?
===== thinking=False  (0 reasoning + 198 answer tokens, 4.5s)
--- answer ---
We are given:

- 3 boxes of 12 eggs each = **36 eggs total**
- We drop **2 boxes**
- Each of the **2 dropped boxes** has **half the eggs broken**

Let’s calculate the number of **unbroken eggs**:

### Step 1: Total eggs
- 3 boxes × 12 eggs = **36 eggs**

### Step 2: Eggs broken from dropped boxes
- Each of the **2 dropped boxes** has **half the eggs broken**
- So, 2 boxes × 12 eggs = **24 eggs**
- Half of 24 eggs = **12 eggs broken**

### Step 3: Total eggs broken = 12

### Step 4: Unbroken eggs = Total eggs - Broken eggs
- 36 eggs - 12 broken = **24 unbroken eggs**

### ✅ Final Answer: **24 unbroken eggs**.
===== thinking=True  (2048 reasoning + 0 answer tokens, 56.3s)
--- reasoning ---
<think>
Okay, let's try to figure out this problem step by step. So, the problem says there are 3 boxes of 12 eggs each. I drop 2 boxes, and half the eggs in each dropped box break. We need to find out how many unbroken eggs I have left. 

First, let me make sure I understand the problem correctly. There are 3 boxes, each with 12 eggs. So, initially, there are 3 boxes multiplied by 12 eggs per box, which is 36 eggs in total. 

Now, the problem says I drop 2 boxes. Let me think about what happens to those boxes. Each box that is dropped has half the eggs breaking. Since each box has 12 eggs, half of that would be 6 eggs breaking. So, if I drop 2 boxes, each with 12 eggs, then each box loses half its eggs, meaning 6 eggs break. 

But wait, does that mean each box that is dropped has 12 eggs, and half of them break? So, if I drop two boxes, each of which originally had 12 eggs, then each of
[...]
 interpretation. 

Alternatively, maybe when you drop the boxes, you don't remove the eggs, but you just have the boxes in the system, and half of the eggs in each box break. 

So, for example, if you drop a box, you have 12 eggs in it, and half break. So, 6 eggs remain. Therefore, the number of eggs remaining in the box is 6. 

So, if you drop two boxes, each with 12 eggs, then each box has 6 eggs left. Therefore, total eggs remaining is 2*6=12. 

But original total was 36. Therefore, 36 - 24 =
--- answer ---
(none: thinking hit the token limit)

These two questions show the best and worst of reasoning in one run:

  • 391 is where thinking pays off. With thinking off, the model answers instantly and wrongly ("Yes, 391 is a prime number"). With thinking on, it works through divisibility checks one prime at a time, discovers 17 × 23 = 391, double-checks the multiplication, and answers correctly. You can see trial-and-error, verification and self-correction, the behaviours from 1.3, in a 0.6B model, at the cost of 584 reasoning tokens and about 15 seconds instead of under 1.
  • The eggs question is where thinking fails. With thinking off, the model gets the right answer, 24. With thinking on, it reaches the right idea early but keeps second-guessing what "dropping a box" means, loops between interpretations, and runs into the 2,048-token cap without ever answering. That's overthinking and truncated reasoning at once: on a hosted API you'd pay for 2,048 output tokens and get nothing.
  • The raw <think> text is visible here because this is an open model running on your machine. Hosted APIs would show you a summary at most (Part 4).

9.3 Measure it: direct vs CoT prompting vs thinking#

Now a small benchmark. problems.py holds 12 multi-step word problems with known answers (see the Exercises for extending it), and an instruction to end with Answer: <number>:

python
# problems.py
# Small multi-step word problems with known answers.
PROBLEMS = [
    ("Mia has 3 boxes with 12 crayons each. She gives away 9 crayons and then buys 2 packs of 8 crayons. How many crayons does she have now?", 43),
    ("A shirt costs $40. It is discounted by 25%, and then a $5 coupon is applied. What is the final price in dollars?", 25),
    ("Tom is 4 times as old as his son. In 6 years, Tom will be 3 times as old as his son. How old is Tom now?", 48),
    ("A tank holds 120 litres and is 3/4 full. 15 litres are used each day. After how many days is it empty?", 6),
    ("What is the sum of all even numbers from 2 to 40, inclusive?", 420),
    ("A recipe needs 250 g of flour for 10 cookies. How many grams of flour are needed for 36 cookies?", 900),
    ("Three friends split a $96 bill. Ana pays twice what Ben pays, and Cleo pays $16 more than Ben. How many dollars does Ana pay?", 40),
    ("How many minutes are there in 3.5 days?", 5040),
    ("A rectangle has a perimeter of 46 cm, and its length is 5 cm more than its width. What is its area in square cm?", 126),
    ("If 5 machines make 5 widgets in 5 minutes, how many minutes do 100 machines take to make 100 widgets?", 5),
    ("A number is doubled, then 7 is subtracted, and the result is 29. What was the number?", 18),
    ("A car travels 150 km in 2.5 hours. At the same speed, how many km does it travel in 4 hours?", 240),
]
INSTRUCTION = "\nEnd your reply with a final line of the form 'Answer: <number>'."

The benchmark runs every problem in four modes:

  • direct: thinking off, and the model must reply with only Answer: <number> (capped at 32 tokens), like Prompt A in 1.2. No room for any working.
  • no_think: thinking off, but nothing stops the model writing some working before its answer. Small chat models often do this unprompted.
  • cot_prompt: thinking off, plus "Let's think step by step", the 1.2 technique.
  • thinking: the model's trained reasoning mode. If thinking hits the 2,048-token cap without finishing, the problem counts as wrong (the truncated column), because there's no answer to score.
python
# local_bench.py
import re
import time

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

from problems import INSTRUCTION, PROBLEMS

MODEL = "Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
device = ("cuda" if torch.cuda.is_available()          # NVIDIA GPU
          else "mps" if torch.backends.mps.is_available()  # Apple silicon GPU
          else "cpu")
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32).to(device)

MODES = {  # name: (thinking switch, text added after the question, max new tokens)
    "direct":     (False, "\nReply with only one line: 'Answer: <number>'.", 32),  # no room to work
    "no_think":   (False, INSTRUCTION, 2048),                                     # thinking off, unprompted
    "cot_prompt": (False, "\nLet's think step by step." + INSTRUCTION, 2048),    # chain-of-thought prompting
    "thinking":   (True, INSTRUCTION, 2048),                                      # trained thinking mode
}

def final_number(text: str):
    m = re.findall(r"Answer:\s*\$?\s*(-?[\d,]*\.?\d+)", text)
    nums = m or re.findall(r"-?\d[\d,]*\.?\d*", text)    # fall back to the last number
    return float(nums[-1].replace(",", "")) if nums else None

def run(question: str, mode: str):
    thinking, suffix, max_new = MODES[mode]
    prompt = tokenizer.apply_chat_template(
        [{"role": "user", "content": question + suffix}], tokenize=False,
        add_generation_prompt=True, enable_thinking=thinking)
    inputs = tokenizer(prompt, return_tensors="pt").to(device)
    sampling = (dict(temperature=0.6, top_p=0.95, top_k=20) if thinking
                else dict(temperature=0.7, top_p=0.8, top_k=20))   # Qwen's recommended settings
    torch.manual_seed(0)
    start = time.time()
    out = model.generate(**inputs, max_new_tokens=max_new, do_sample=True, **sampling)
    new_ids = out[0][inputs.input_ids.shape[1]:]
    text = tokenizer.decode(new_ids, skip_special_tokens=True)
    if thinking and "</think>" not in text:          # thinking hit the cap: no answer at all
        return None, len(new_ids), time.time() - start, True
    return final_number(text.split("</think>")[-1]), len(new_ids), time.time() - start, False

print(f"{'mode':11s} {'correct':>8s} {'avg tokens':>11s} {'avg seconds':>12s} {'truncated':>10s}")
for mode in MODES:
    correct, tokens, seconds, truncated = 0, [], [], 0
    for question, expected in PROBLEMS:
        got, n_tokens, secs, cut = run(question, mode)
        correct += got is not None and abs(got - expected) < 1e-6
        tokens.append(n_tokens)
        seconds.append(secs)
        truncated += cut
    print(f"{mode:11s} {correct:>5d}/{len(PROBLEMS)} {sum(tokens)/len(tokens):>11.0f} "
          f"{sum(seconds)/len(seconds):>12.1f} {truncated:>10d}")
Output · on an Apple-silicon laptop GPU; timings will differ on your machine5 lines
mode         correct  avg tokens  avg seconds  truncated
direct          0/12           8          0.3          0
no_think        8/12         110          2.6          0
cot_prompt     12/12         162          3.8          0
thinking       12/12         756         20.4          0

What the numbers say:

  • Writing steps out is what makes the difference. Forced to answer immediately, the model got 0 of 12: it produced plausible-looking but wrong numbers (30 for 43, 1,200 for 420). Allowed to write some working of its own accord (no_think), it got 8. Prompted to think step by step, or thinking in its trained mode, it got all 12. That's the scratch-paper effect from 1.1 in action.
  • On problems this easy, CoT prompting was just as accurate and far cheaper. Thinking mode generated nearly 5 times as many tokens as CoT prompting (756 vs 162 on average) and took more than 5 times as long, for no extra accuracy. These are short school-level problems, and most of the extra thinking re-checked work that was already right. Harder problems (competition maths, multi-file debugging, long plans) are where trained reasoning pulls clearly ahead of CoT prompting, which is why you should measure on your task rather than assume (Part 10).
  • No thinking run hit the cap here, unlike the eggs question in 9.2. On a larger or harder set you'd see some, and counting them as failures (rather than scoring whatever number appears last in an unfinished trace) is the honest way to report them.
  • Cost scales with tokens, not with correctness. On a hosted API, thinking mode would cost several times more per request than CoT prompting for the same 12/12. That's 5.1 in miniature.

9.4 The scaling curve on your laptop: budget forcing#

Finally, the test-time scaling curve from 2.5. This script gives the model a thinking budget: it may think for at most N tokens. If it hasn't finished by then, we cut the thinking off, append the closing </think> tag with a short "answer now" note (the approach Qwen's documentation suggests), and make it answer. This is the "budget forcing" idea from the s1 paper, in its crudest form: a hard cut-off followed by a forced answer. Hosted thinking budgets aren't like this. Claude's legacy budget_tokens and Gemini's thinking_budget were soft targets that the models were trained to respect (and could overshoot or undershoot), so a hosted model plans within its budget instead of being interrupted mid-sentence.

To keep the comparison fair, every row uses the same two-step pipeline and the same 2,048-token allowance for the answer, and budget 0 means thinking switched off:

python
# local_budget.py
import re

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

from problems import INSTRUCTION, PROBLEMS

MODEL = "Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
device = ("cuda" if torch.cuda.is_available()          # NVIDIA GPU
          else "mps" if torch.backends.mps.is_available()  # Apple silicon GPU
          else "cpu")
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32).to(device)
END_THINK = tokenizer.convert_tokens_to_ids("</think>")
# If thinking hits the budget, we cut it off and force the model to answer.
FORCE = "\n\nConsidering the limited time, I have to give the solution based on the thinking directly now.\n</think>\n\n"

def final_number(text):
    m = re.findall(r"Answer:\s*\$?\s*(-?[\d,]*\.?\d+)", text) or re.findall(r"-?\d[\d,]*\.?\d*", text)
    return float(m[-1].replace(",", "")) if m else None

def generate(text, max_new_tokens):
    inputs = tokenizer(text, return_tensors="pt").to(device)
    torch.manual_seed(0)
    out = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=True,
                         temperature=0.6, top_p=0.95, top_k=20)
    return out[0][inputs.input_ids.shape[1]:].tolist()

def solve(question, budget):
    prompt = tokenizer.apply_chat_template(
        [{"role": "user", "content": question + INSTRUCTION}], tokenize=False,
        add_generation_prompt=True, enable_thinking=budget > 0)  # budget 0 = thinking off
    if budget == 0:
        thought_text, used = "", 0
    else:
        thought = generate(prompt, budget)                      # phase 1: think, up to the budget
        if END_THINK in thought:                                # finished thinking within budget
            cut = thought.index(END_THINK) + 1
            thought_text, used = tokenizer.decode(thought[:cut]), cut
        else:                                                   # budget exhausted: force an answer
            thought_text, used = tokenizer.decode(thought) + FORCE, len(thought)
    answer_ids = generate(prompt + thought_text, 2048)          # phase 2: answer, same cap for every row
    return final_number(tokenizer.decode(answer_ids, skip_special_tokens=True)), used, len(answer_ids)

print(f"{'budget':>7s} {'correct':>8s} {'avg thinking tokens':>20s} {'avg answer tokens':>18s}")
for budget in [0, 32, 128, 512, 2048]:
    correct, used, answered = 0, [], []
    for question, expected in PROBLEMS:
        got, n_think, n_answer = solve(question, budget)
        correct += got is not None and abs(got - expected) < 1e-6
        used.append(n_think)
        answered.append(n_answer)
    print(f"{budget:>7d} {correct:>5d}/{len(PROBLEMS)} {sum(used)/len(used):>20.0f} "
          f"{sum(answered)/len(answered):>18.0f}")
Output · on an Apple-silicon laptop GPU6 lines
 budget  correct  avg thinking tokens  avg answer tokens
      0     8/12                    0                109
     32     7/12                   32                101
    128     6/12                  128                 93
    512    11/12                  486                 78
   2048    12/12                  681                 79

This is the test-time scaling curve from 2.5, measured on your laptop:

  • Enough thinking helps; a little doesn't. With thinking off, the model got 8/12. With 512 tokens of thinking it got 11/12, and with 2,048 it got 12/12.
  • Cutting thinking off early bought nothing. At 32 and 128 tokens the model scored 7/12 and 6/12, no better than with thinking off (8/12). The one- or two-point dip is within the noise of a 12-problem set, so don't read it as "short thinking hurts"; read it as "a reasoning model interrupted mid-thought doesn't gain anything". Notice the last column too: when thinking was cut short, the model wrote longer answers (about 100 tokens), carrying on its working in the answer instead. If you need a very tight budget, switching thinking off is simpler and costs the same. Measure both.
  • The model often stops before the budget runs out. With 2,048 tokens allowed, it used 681 on average: it finished thinking on its own for most problems. Effort and budget settings set a ceiling and a tendency, not an exact spend (Part 3).
  • Returns diminish. Quadrupling the budget from 512 to 2,048 tokens bought one more correct answer, and the model needed only about 200 extra tokens on average to get it.

9.5 Multi-turn conversations with a local reasoning model#

Hosted APIs want reasoning passed back inside tool loops (8.2). Open-weight reasoning models usually want the opposite across turns: Qwen3's model card says the conversation history should contain only each reply's final answer, not its thinking, and its chat template enforces this. You can see it without loading the model, using only the tokenizer:

python
# local_history.py
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")   # the tokenizer only: no model needed

messages = [
    {"role": "user", "content": "Is 391 prime?"},
    {"role": "assistant",                                       # last turn's reply, reasoning included
     "content": "<think>\nTry small primes... 17 × 23 = 391.\n</think>\n\nNo: 391 = 17 × 23."},
    {"role": "user", "content": "And 397?"},
]
prompt = tokenizer.apply_chat_template(messages, tokenize=False,
                                       add_generation_prompt=True, enable_thinking=True)
print(prompt)
Output7 lines
<|im_start|>user
Is 391 prime?<|im_end|>
<|im_start|>assistant
No: 391 = 17 × 23.<|im_end|>
<|im_start|>user
And 397?<|im_end|>
<|im_start|>assistant

The <think> block from the earlier reply is gone: the template kept only No: 391 = 17 × 23. This keeps the context short and matches how the model was trained. If you build prompts yourself instead of using the chat template (or call a server such as vLLM, which returns the reasoning separately as reasoning_content), store and resend only the final answers.


Part 10: Evaluating reasoning gains on your task#

Benchmarks tell you that reasoning helps on benchmarks. Only your own evaluation tells you whether it helps on your task enough to justify the cost. Module 10A teaches evaluation properly; here's how to apply it to the reasoning decision.

10.1 What to measure#

For every configuration (model × effort level):

Metric Why
Quality (accuracy, pass rate, rubric score) Does reasoning actually improve results on your cases?
Reasoning tokens and total output tokens (mean and p95) Drives cost and latency
Cost per request and cost per successful task Retries and failures cost money too
Latency: time to first token and total, p50 and p95 User experience
Truncation rate How often thinking hits the output cap (5.3)
Failure modes Overthinking, format errors, wrong tool calls, loops

10.2 The procedure#

  1. Build an evaluation set of real, representative inputs with known good outputs or a grading rubric. Include easy and hard cases in realistic proportions.
  2. Pick candidate configurations: for example, your current model with reasoning off, low, medium and high, plus one cheaper and one stronger model.
  3. Run every configuration on the full set, with the same prompts, logging quality, tokens, cost and latency per case. Use several samples per case for noisy tasks.
  4. Plot quality against cost and find the Pareto frontier: configurations that no other configuration beats on both quality and cost at once.
  5. Choose the cheapest configuration that meets your quality bar and latency limit.
  6. Slice the results by difficulty or task type: reasoning may only pay off on a subset, which suggests routing (6.3).
  7. Re-run whenever models, prices or prompts change.

Here's step 4–5 on a set of example measurements:

python
# pick_config.py
# Example measurements from running one eval set (200 cases) through six
# configurations. Replace them with your own numbers.
results = [
    # (config,                    accuracy, cost per 1k requests ($), p95 latency (s))
    ("small model, effort none",   0.71,  0.40,  1.1),
    ("small model, effort low",    0.83,  0.90,  3.2),
    ("small model, effort high",   0.86,  3.10, 14.0),
    ("large model, effort low",    0.88,  4.20,  5.5),
    ("large model, effort medium", 0.91,  9.80, 12.5),
    ("large model, effort high",   0.91, 21.00, 31.0),
]

def pareto(rows):
    """Keep configs that no other config beats on accuracy AND cost at the same time."""
    keep = []
    for name, acc, cost, lat in rows:
        dominated = any(a >= acc and c <= cost and (a > acc or c < cost)
                        for n, a, c, l in rows if n != name)
        if not dominated:
            keep.append((name, acc, cost, lat))
    return keep

print("Pareto frontier (accuracy vs cost):")
for name, acc, cost, lat in pareto(results):
    print(f"  {name:28s} acc={acc:.0%}  ${cost:5.2f}/1k  p95={lat:4.1f}s")

QUALITY_BAR, LATENCY_LIMIT = 0.85, 15.0
ok = [r for r in results if r[1] >= QUALITY_BAR and r[3] <= LATENCY_LIMIT]
best = min(ok, key=lambda r: r[2])
print(f"\nCheapest config with accuracy >= {QUALITY_BAR:.0%} and p95 <= {LATENCY_LIMIT:.0f}s: {best[0]}")
Output8 lines
Pareto frontier (accuracy vs cost):
  small model, effort none     acc=71%  $ 0.40/1k  p95= 1.1s
  small model, effort low      acc=83%  $ 0.90/1k  p95= 3.2s
  small model, effort high     acc=86%  $ 3.10/1k  p95=14.0s
  large model, effort low      acc=88%  $ 4.20/1k  p95= 5.5s
  large model, effort medium   acc=91%  $ 9.80/1k  p95=12.5s

Cheapest config with accuracy >= 85% and p95 <= 15s: small model, effort high

Read the result carefully:

  • "Large model, effort high" drops off the frontier. It costs twice as much as medium for the same 91%: the scaling curve has flattened (2.5).
  • The winner depends on your constraints. With an 85% bar, "small model, effort high" is cheapest, but its p95 latency of 14 seconds is close to the limit. "Large model, effort low" costs a little more and is far faster. That's a product decision, which you can now make with data.
  • The biggest single jump is from "none" to "low" (71% to 83%) for $0.50 more per 1,000 requests. That's common: a little reasoning often buys most of the gain.

Part 11: Going deeper#

Deep-dive

11.1 Test-time scaling methods#

"Thinking longer" is one way to spend compute at test time. There are two families:

flowchart TB
    subgraph seq ["Sequential scaling: think longer"]
        S1["One reasoning chain"] --> S2["...more steps, checks,<br/>backtracking..."] --> S3["One answer"]
    end
    subgraph par ["Parallel scaling: think wider"]
        P0["Same question"] --> P1["Chain 1 → 42"]
        P0 --> P2["Chain 2 → 42"]
        P0 --> P3["Chain 3 → 17"]
        P1 & P2 & P3 --> PV["Aggregate: majority vote,<br/>verifier or judge picks best"]
        PV --> P4["Final answer: 42"]
    end
Method How it works Needs Good for
Longer chain of thought One chain, more thinking (effort, budgets) A reasoning model Default choice
Self-consistency (majority voting) Sample N independent answers; return the most common one Answers you can compare (numbers, labels, short strings) Maths, classification, extraction
Best-of-N with a verifier Sample N answers; a checker scores each; return the best A verifier: unit tests, a schema, a rule engine, or a reward model Code (run the tests), structured output
LLM-as-judge selection Sample N; another model picks the best A reliable judge prompt Open-ended text, where nothing can be checked automatically
Search over steps Expand promising partial solutions, prune bad ones (beam or tree search with a step scorer) A process reward model or step checker Research systems; rarely hand-built in apps
Provider "pro" modes The provider runs more model work per request internally (for example OpenAI's reasoning.mode: "pro") Budget and patience High-value single requests

Parallel methods multiply cost by N, but they parallelize, so latency grows much less than cost. They also only help when the model's errors are varied. This simulation shows why:

python
# majority_vote.py
import numpy as np

rng = np.random.default_rng(seed=0)

def vote_accuracy(p_correct, wrong_weights, n_samples, trials=20_000):
    """Simulate self-consistency: sample n answers, return the most common one.
    Answer 0 is correct; answers 1..k are wrong, chosen with wrong_weights."""
    wrong = np.array(wrong_weights) / sum(wrong_weights)
    probs = np.concatenate([[p_correct], (1 - p_correct) * wrong])
    wins = 0
    for _ in range(trials):
        answers = rng.choice(len(probs), size=n_samples, p=probs)
        counts = np.bincount(answers, minlength=len(probs))
        winners = np.flatnonzero(counts == counts.max())
        wins += rng.choice(winners) == 0          # break ties at random
    return wins / trials

cases = {
    "A: right 60%, mistakes scattered": (0.60, [1, 1, 1, 1]),
    "B: right 35%, mistakes scattered": (0.35, [1, 1, 1, 1, 1, 1]),
    "C: right 35%, one popular mistake (50%)": (0.35, [0.50 / 0.65, 0.15 / 0.65]),
}
print(f"{'samples:':42s}", "  ".join(f"{n:>5}" for n in [1, 3, 5, 9, 15]))
for name, (p, wrong_weights) in cases.items():
    accs = [vote_accuracy(p, wrong_weights, n) for n in [1, 3, 5, 9, 15]]
    print(f"{name:42s}", "  ".join(f"{a:5.0%}" for a in accs))
Output4 lines
samples:                                       1      3      5      9     15
A: right 60%, mistakes scattered             60%    72%    84%    94%    99%
B: right 35%, mistakes scattered             35%    40%    51%    63%    76%
C: right 35%, one popular mistake (50%)      35%    33%    32%    30%    26%

The numbers are simulated (20,000 trials per cell), so a different NumPy version or seed can move any cell by a point or so. The pattern is what matters:

  • Case A: a model that's usually right becomes almost always right with 15 votes.
  • Case B: even a model that's right only 35% of the time improves a lot, as long as its wrong answers disagree with each other: the correct answer is still the most common single answer.
  • Case C: when the model has a systematic misconception (one wrong answer more popular than the right one), voting makes things worse, converging confidently on the wrong answer. That's the bat-and-ball problem for models: more samples of the same mistake don't fix the mistake.

What this means for you: use voting or best-of-N for checkable outputs where errors are random-ish, and prefer a real verifier (tests, schemas, rules) whenever you have one. A verifier turns "probably right" into "checked".

11.2 Hybrid models and thinking toggles#

A hybrid reasoning model can either think or answer directly with the same weights. You've seen the controls:

Control Examples
Template switch Qwen3's enable_thinking=True/False (Part 9)
In-prompt soft switch Qwen3 also documents /think and /no_think tags in user messages for turn-by-turn switching in multi-turn chats
API effort none / disabled OpenAI effort: "none", Claude Haiku 5.5 thinking: {"type": "disabled"}, Gemini 2.5 Flash thinking_budget=0
Partial off Claude Sonnet 5.5 between_tools (no up-front thinking, still reasons between tool calls); Gemini 3 minimal
Adaptive The model decides per request (Claude adaptive thinking, Gemini dynamic thinking, OpenAI's adaptive reasoning within an effort level)

The industry trend is clear: separate "reasoning" and "chat" model lines have merged into single models with a dial, and the frontier is moving towards always-on adaptive thinking where you control the dial but can't always switch it off. Design your code so effort is a configuration value per route, and you'll handle whichever direction a provider takes next.

11.3 The limits of reasoning#

Reasoning is powerful, but it isn't magic. It doesn't:

  • Add knowledge. Thinking reorganizes what the model knows; it can't produce facts it never learned, or anything after its knowledge cutoff (lesson 01, 7.3). A reasoning model asked about your company's refund policy will reason fluently and still be wrong. Supply the facts with RAG (Module 07) or tools (Module 08A).
  • Guarantee correctness. Models can reason step by step, confidently, to a wrong answer, and a long, careful-sounding trace makes the error more persuasive. Lesson 10, Part 6 catalogues these failure modes.
  • Remove hallucination. Reasoning reduces some errors (arithmetic, logic) but models still invent facts, citations and tool results.
  • Make outputs deterministic. Sampling still happens (lesson 05), and reasoning paths can differ run to run.
  • Make the model safe by itself. Prompt injection and harmful actions remain possible; long reasoning can even rationalize a bad action (Module 12).
  • Help every task. On simple tasks it adds cost and latency for nothing, and sometimes hurts (6.2).

The engineering stance: treat reasoning as a quality dial you pay for, and keep verification, retrieval, guardrails and evaluation around it.


Common misconceptions#

Misconception Reality
"A reasoning model is a different kind of neural network." It's the same transformer architecture. What's different is the training (RL that rewards reasoning which reaches correct answers) and the interface (separate thinking, effort controls).
"The thinking I see is what the model actually thought." Hosted APIs show a summary written by a summarizer, or nothing. And even raw reasoning isn't guaranteed to reflect the real cause of the answer (4.3).
"If the API hides the reasoning, I'll just prompt the model to write it out in the answer." You pay for the reasoning twice, the result isn't the real reasoning, and on current Claude flagships the request may be refused with the reasoning_extraction category (7.2). Read the thinking summaries instead.
"If I can't see the reasoning, I don't pay for it." Hidden reasoning is billed in full at the output rate. Summaries are billed at the full reasoning length, not the summary length.
"Higher effort is always better." Returns diminish, and on some tasks longer reasoning lowers accuracy (6.2). Measure.
"Adding 'think step by step' improves any model." It helps standard models somewhat. On reasoning models it's redundant and can hurt (7.2).
"Reasoning fixes hallucination." It reduces some reasoning errors but adds no knowledge. Missing or recent facts still need RAG or tools (11.3).
"Set temperature to 0 to make a reasoning model consistent." Reasoning models either reject sampling settings with a 400 error (Anthropic, OpenAI) or silently ignore them (new Gemini models). Control effort instead (5.5).
"max_tokens only limits the answer." It limits reasoning plus answer. Set it too low and you get an empty answer and a bill for the reasoning (5.3).
"Effort low means no thinking." Low effort means less thinking, decided adaptively. "Off" is a separate setting, and some models don't offer it at all.
"Thinking blocks must always be sent back" or "they can always be dropped". It depends on where you are. Within a tool-use turn, pass them back unchanged, or the model loses its reasoning and the API may reject the request. Across completed turns, hosted APIs keep or strip them per model, so pass them back and let the API decide (removing all of them when trimming is allowed). Open-weight chat templates expect old reasoning removed (8.2, 9.5).
"Voting over many samples always helps." Only when mistakes vary. A systematic mistake gets amplified (11.1).

Key takeaways#

  • A reasoning model generates thinking tokens before its answer, spending test-time compute to plan, check and backtrack. It's the same kind of transformer, trained with reinforcement learning on verifiable rewards to make that reasoning effective.
  • Chain-of-thought prompting asks a standard model to show steps; a reasoning model has been trained to reason, does it in separate blocks, and is far stronger on hard multi-step problems.
  • Accuracy rises with thinking roughly logarithmically, with diminishing returns, and can fall on some tasks (overthinking).
  • Every provider exposes amount (OpenAI reasoning.effort, Claude output_config.effort with adaptive thinking, Gemini thinking_level, OpenRouter reasoning), visibility (summaries), accounting (reasoning-token usage fields) and continuity (encrypted reasoning you pass back). Values and defaults are model-specific and change often: check model pages.
  • Raw reasoning is hidden by closed providers; you get summaries at most. Reasoning text is not a faithful explanation of the model's decision, so don't use it as an audit trail or parse answers from it.
  • Reasoning tokens are billed as output tokens, including hidden ones. They count against the output cap (truncation gives empty answers) and occupy the context window. Reasoning models restrict temperature and related settings.
  • Use reasoning for hard multi-step maths, code, planning and agents; switch it off or down for extraction, classification, chit-chat and latency-critical UX. Route by task.
  • Prompt reasoning models with goals, constraints and an output contract, not step-by-step scripts or "think step by step".
  • In agents, models think between tool calls; pass the whole assistant turn, reasoning included, back unchanged.
  • Decide effort with your own evaluation: measure quality, tokens, cost and latency per configuration and pick from the Pareto frontier.

Terms introduced in this lesson#

Term One-line definition
Reasoning model (thinking model, LRM) An LLM trained to generate a reasoning process before its final answer
Reasoning tokens / thinking tokens Tokens the model generates while reasoning, separate from the visible answer and billed as output
Test-time compute (inference-time compute) Computation spent while answering a request, rather than during training
Test-time scaling Improving results by spending more compute at answer time (longer thinking or more samples)
Chain-of-thought (CoT) prompting Prompting a model to write out intermediate steps, e.g. "Let's think step by step"
Reinforcement learning with verifiable rewards (RLVR) RL training on problems whose answers can be checked automatically, such as correct answers or passing tests (defined in lesson 06)
GRPO (group relative policy optimization) An RL algorithm for reasoning training that scores each attempt against the other attempts at the same problem, with no separate value model
Distillation Training a smaller student model to imitate a larger teacher model, here its reasoning traces (defined in lesson 06 as knowledge distillation)
Reasoning effort / thinking level An API setting that guides how much a model reasons (e.g. low, medium, high)
Thinking budget A cap or target on the number of thinking tokens (legacy on most current APIs)
Adaptive thinking Anthropic's mode in which Claude decides per request whether and how much to think
Reasoning summary / thought summary A readable condensed version of hidden reasoning, produced by a summarizer
Thinking block / signature Claude's response block for reasoning, carrying an encrypted signature to pass back unchanged
Preserved thinking Anthropic's rule that each thinking block is bound to the model and to everything before it, so history must be append-only (rules in 8.2; history strategies in lesson 07, 4.2)
Thought signature Gemini's encrypted representation of its reasoning state, attached to response parts
Encrypted reasoning item OpenAI's opaque reasoning output (encrypted_content) for continuing reasoning across calls
Interleaved thinking Reasoning between tool calls within one assistant turn
Hybrid reasoning model One model that can either think or answer directly, controlled by a switch
Chain-of-thought faithfulness Whether written reasoning reflects the actual cause of a model's answer (see "unfaithful explanation" in lesson 10)
Overthinking Spending excessive reasoning on easy problems, wasting tokens or lowering accuracy
Budget forcing Controlling thinking length by cutting it off or extending it during generation
Self-consistency (majority voting) Sampling several reasoning paths and taking a majority vote over their final answers (defined here in 11.1; previewed in lessons 05 and 10)
Best-of-N / verifier Generating several samples and picking one with a scorer, test suite or verifier (also in lesson 05)
Pareto frontier The set of options not beaten on all measured criteria (e.g. quality and cost) by any other

All terms are also collected in the glossary.


Exercises#

  1. Watch it think (9.2): change the question to one with a trap, such as the bat-and-ball problem. Run with thinking on and off several times with different seeds. How often does each mode fall for the trap? Read the reasoning: does the model notice the trap?
  2. Benchmark (9.3): add eight problems of your own, including two very easy ones ("What is 7 + 5?"). Compare the token counts of thinking mode on easy vs hard problems. Is there overthinking?
  3. Budget curve (9.4): run the budget script with budgets of 16 and 4096 added. Where does the curve flatten for this model? Plot accuracy against the logarithm of the budget.
  4. Self-consistency (11.1): take one problem the model gets wrong in 9.3, sample it nine times with different seeds in thinking mode, and take a majority vote. Did voting fix it? Which case (A, B or C) does it resemble?
  5. Cost (5.1): look up the real input and output prices of two reasoning models on their providers' pricing pages. Using cost_calc.py, compute the cost of one million requests at 0, 1,000 and 10,000 reasoning tokens for each.
  6. OpenRouter discovery (3.4): extend or_reasoning_options.py to list every model whose reasoning.mandatory is true, and every model that advertises supports_max_tokens.
  7. Provider samples (Part 3, needs API keys): run the OpenAI and Anthropic samples (and the Gemini sample if you use it) at two effort levels each. Record reasoning tokens, answer and latency. Then set the output-token cap to 50 and observe how each provider signals truncation.
  8. Prompt rewrite (Part 7): take a long, step-by-step prompt from a project of yours and rewrite it as goal, constraints, definition of done and output contract. Compare both versions on five inputs with a reasoning model.
Hints and what you should see
  1. Seed the run with torch.manual_seed(seed) before each generate call and loop over, say, five seeds per mode. Count how many answers say $0.10 against $0.05. Small models fall for the trap often with thinking off; in thinking mode, look in the <think> text for a moment where the model re-reads "$1.00 more than the ball" and corrects itself. Report your own counts rather than expecting a fixed number: five runs is only a hint.
  2. Compare reasoning tokens for the trivial questions with those for the hard ones. A small model often spends hundreds of tokens re-verifying 7 + 5, which is the overthinking pattern from 6.2; if yours doesn't, say so, because it depends on the seed and the model version.
  3. A budget of 16 behaves like thinking switched off, because the cut-off comes almost immediately. A budget of 4,096 mostly just raises the ceiling: in the lesson's run the model used about 680 thinking tokens on average even with 2,048 allowed, so expect the curve to flatten somewhere between 512 and 2,048. Print a text table of budget against accuracy (or use a plotting library if you have one installed) and put the budget on a logarithmic axis.
  4. Run solve-style generation nine times with seeds 0 to 8, extract each final number, and use collections.Counter(...).most_common(1). If the wrong answers are all different, voting should help (cases A and B). If one wrong number keeps coming back, voting will not fix it (case C): that points to a systematic misconception, which needs a better prompt, a tool or a stronger model.
  5. Cost per request is (input × input_price + (visible + reasoning) × output_price) / 1,000,000. As a check, with the lesson's example prices ($1 and $5 per million tokens, 1,500 input and 200 visible tokens) one million requests cost about $2,500 at 0 reasoning tokens, $7,500 at 1,000 and $52,500 at 10,000. Replace the prices with the real ones you looked up.
  6. Print models["openai/gpt-6-luna"].get("reasoning") first to see the exact field names, then filter with m.get("reasoning", {}).get("mandatory"). If a field you were told about is missing, say so rather than guessing: the list is a live catalogue and fields can change.
  7. Expect the truncation signals from the table in 5.3: OpenAI status: "incomplete" with incomplete_details.reason: "max_output_tokens", Anthropic stop_reason: "max_tokens", Gemini finish reason MAX_TOKENS, OpenRouter finish_reason: "length". With a cap of 50 you will often get no visible answer text at all.
  8. Compare both prompts on accuracy, reasoning tokens and answer format. A good rewrite is shorter, states what "done" means, and should not lower quality; if it does, note which constraint you lost.

Check yourself#

  1. Why does writing out intermediate steps let a model solve harder problems, given that each token gets the same amount of computation?
  2. What's the difference between chain-of-thought prompting and a reasoning model?
  3. In reinforcement learning with verifiable rewards, what is rewarded, and what is not graded?
  4. What does "test-time compute" mean, and what does the typical scaling curve look like?
  5. Name the parameter that controls reasoning amount on OpenAI, Anthropic, Gemini 3 and OpenRouter.
  6. Your Claude code sends thinking={"type": "enabled", "budget_tokens": 8000} to claude-sonnet-5-5 and gets a 400 error. Why, and how do you fix it?
  7. A response shows a 120-token reasoning summary and a 30-token answer, but usage reports 2,400 output tokens. Is something wrong?
  8. An OpenAI request returns status: "incomplete" and empty output text. What happened, and what are two ways to fix it?
  9. Why might a provider hide raw reasoning? Give two reasons.
  10. Why shouldn't you show a model's reasoning to a customer as the explanation for a decision?
  11. Your migration to a reasoning model fails with a 400 error mentioning temperature. What should you do?
  12. For which of these would you enable reasoning: (a) extracting invoice fields to JSON, (b) planning a multi-city trip under budget and time constraints, (c) autocomplete suggestions while typing?
  13. In a tool-use loop, what must you send back to the model after it calls a tool, and why?
  14. When does majority voting make results worse?
  15. How would you decide between effort medium and high for a production feature?

Further resources#

  • OpenAI, Learning to Reason with LLMs (September 2024): the o1 announcement, with the test-time compute scaling charts and the rationale for hiding the chain of thought.
  • OpenAI API docs: Reasoning models and Reasoning best practices: current effort values, summaries, reasoning items and prompting advice.
  • Anthropic docs: Thinking, Steering thinking and Effort: adaptive thinking, display options, pricing and tool use.
  • Google Gemini API docs: Gemini thinking: thinking levels, budgets, thought summaries and signatures.
  • OpenRouter docs: Reasoning Tokens: the unified reasoning parameter and per-provider mapping.
  • Wei et al., Chain-of-Thought Prompting Elicits Reasoning in Large Language Models (2022, arXiv:2201.11903), and Wang et al., Self-Consistency Improves Chain of Thought Reasoning in Language Models (2022, arXiv:2203.11171).
  • DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning (2025, arXiv:2501.12948): the most detailed public account of training a reasoning model.
  • Muennighoff et al., s1: Simple test-time scaling (2025, arXiv:2501.19393): budget forcing and a small open reasoning recipe.
  • Chen et al. (Anthropic), Reasoning Models Don't Always Say What They Think (2025, arXiv:2505.05410; blog post), and Turpin et al., Language Models Don't Always Say What They Think (2023, arXiv:2305.04388): chain-of-thought faithfulness.
  • Gema et al., Inverse Scaling in Test-Time Compute (2025, arXiv:2507.14417): when longer reasoning hurts.
  • The Qwen3-0.6B model card on Hugging Face: thinking and non-thinking modes, and recommended sampling settings.

← 02.7 — Context Windows | Module 02 overview | 02.9 — Model Landscape →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close