Learning Objectives
- Explain how large language models generate text through next-token prediction and autoregressive decoding.
- Define tokens, context windows, sampling, temperature, and non-determinism, and describe how each behaves on Claude models.
- Distinguish zero-shot, single-shot, and multi-shot prompting, and describe Claude's fast, extended, and adaptive thinking modes.
Before you can build reliable applications on Claude, you need a working mental model of what the model is actually doing when it "responds." This guide builds that model from the ground up: how text is generated one unit at a time, what a token really is, why the same prompt can produce different answers, how much text Claude can hold in mind at once, and how to steer its behavior through thinking modes and examples.
Pre-Quiz · Check Your Instincts
How LLMs Work — Before You Read
1. How LLMs Work
Key Points
- Claude is autoregressive: it predicts one token at a time, appends it to the running context, and predicts again in a loop until it emits a stop token or hits
max_tokens.
- Generation samples from a probability distribution using top-p (nucleus) sampling (threshold ~0.99–0.999), not always the single most likely token.
- A raw pretrained model just continues text; Claude is fine-tuned with RLHF to be helpful, honest, and harmless (HHH).
- Tokens are subword units — roughly 3.5 English characters each (varies by language); text is encoded to tokens, reasoned over, and decoded back.
- The newer tokenizer (Opus 4.7+, Sonnet 5, Fable/Mythos 5) emits ~30% more tokens, so recount with the free
count_tokens API for your target model. Outputs are non-deterministic even at temperature 0.
Next-token generation and autoregressive decoding
The single most important idea for a developer is how Claude produces text. Its underlying model is autoregressive: during pretraining it learns "to predict the next word, given the previous context of text." It repeatedly predicts the most likely next unit of text, appends that prediction to the running context, and predicts again — one unit at a time, looping until it decides to stop. "Autoregressive" means regressing on itself: each new piece of output becomes part of the input for the next step.
Analogy — the world's most well-read autocomplete. Like predictive text on your phone, but at vastly larger scale: instead of one suggested word, Claude strings its own predictions together continuously, feeding each prediction back in to predict the next unit.
To avoid nonsense, Claude uses top-p sampling (nucleus sampling): only tokens whose cumulative probability reaches a threshold (~0.99–0.999) are candidates, and it samples from that "nucleus," discarding the long tail. A raw pretrained model "is not inherently good at answering questions or following instructions," so Claude is fine-tuned with RLHF to behave as a helpful assistant aligned to the HHH triad.
Figure 2.1: The autoregressive next-token generation loop
flowchart TD
A["Input context: prompt + tokens generated so far"] --> B["Model computes probability distribution over next token"]
B --> C["Sample one token from the distribution (top-p / nucleus)"]
C --> D["Append sampled token to the running context"]
D --> E{"Stop token or max_tokens reached?"}
E -->|"No"| A
E -->|"Yes"| F["Decode token stream back into text output"]
Animation Slot
Step-through animation: watch a prompt grow token by token as each sampled token is appended to the context and fed back into the model.
Tokens and tokenization
Tokens are "the smallest individual units of a language model" and "can correspond to words, subwords, characters, or even bytes." Text is encoded into tokens before processing; the model reasons entirely in tokens; output is decoded back to text. For Claude, a token approximately represents 3.5 English characters, though this varies by language.
Analogy — LEGO bricks for language. Common words like "the" are single large bricks; a rare word is built from several smaller subword or character bricks. This is why token counts don't map cleanly to word counts.
Figure 2.2: The tokenization pipeline — text in, text out
flowchart LR
A["Raw text: 'I'll meet you at the office'"] --> B["Encode: split into tokens (words, subwords, characters, bytes)"]
B --> C["Token IDs fed to the model as its working units"]
C --> D["Model reasons and generates output tokens"]
D --> E["Decode: token stream back into readable text"]
A cost-relevant change: Opus 4.7+ Opus models, Fable 5, Mythos 5, Mythos Preview, and Sonnet 5 use a newer tokenizer that produces ~30% more tokens for the same text. Do not reuse token counts from older models — recount against the specific model you plan to use. The free token-counting API (POST /v1/messages/count_tokens) returns input tokens before you send, e.g. { "input_tokens": 14 }.
| Property | Detail |
| Result type | An estimate — actual input tokens may differ slightly |
| System-added tokens | May be included, but you are not billed for them |
| Model support | All active models, including Claude Sonnet 5 |
| Cost | Free to use |
| Rate limits (RPM) | Start 2,000 · Build 4,000 · Scale 8,000 — independent of message-creation limits |
Non-determinism and why outputs vary
Because generation samples, running the same prompt twice can produce different text. Even at temperature 0, "the results will not be fully deterministic and identical inputs may produce different outputs across API calls" — on both first-party and third-party inference. Adaptive thinking adds further variation, since thinking-token usage is decided per request. The takeaway is a design principle: do not assume byte-identical outputs; validate structure and meaning, not exact strings.
Key Takeaway: Claude generates text autoregressively, sampling one token at a time and feeding each prediction back in. Tokens are ~3.5-character subword units, and the newer tokenizer emits ~30% more tokens — always recount with the token-counting API. Outputs are non-deterministic even at temperature 0; design for variation.
Post-Quiz · Lock It In
How LLMs Work — After You Read
Pre-Quiz · Check Your Instincts
Context Windows and Sampling — Before You Read
2. Context Windows and Sampling
Key Points
- The context window is Claude's finite working memory: system prompt + all messages + tool definitions/results + generated output (including thinking) all compete for space.
- 1M tokens is the no-beta-header default on Opus 4.6+, Sonnet 5/4.6, and Fable/Mythos 5; older models offer 200K.
- Context rot: as the window fills, accuracy and recall degrade — curating what goes in matters as much as capacity.
- Input alone over the window → 400 error; input +
max_tokens over the window on 4.5+ is accepted and stops with model_context_window_exceeded.
- On the newest models (Fable 5, Mythos 5/Preview, Opus 4.8/4.7, Sonnet 5), non-default temperature / top_p / top_k are rejected with a 400 — steer via prompting and effort instead.
Context window size and limits
The context window is "all the text a language model can reference when generating a response, including the response itself" — a working memory distinct from the training corpus. Everything competes for space: system prompt, every message (tool results, images, documents), tool definitions, and the generated output including extended thinking. Prompt caching changes what you pay, not whether tokens occupy the window.
Analogy — a whiteboard, not a library. Training is a career's worth of knowledge in your head; the context window is the fixed-size whiteboard in front of you during one meeting. When it fills, something must give.
| Context window | Models |
| 1M tokens | Opus 4.8/4.7/4.6, Sonnet 5/4.6, Mythos Preview, Fable 5, Mythos 5 (Claude API, Bedrock, Google Cloud, Microsoft Foundry) |
| 200K tokens | Other Claude models, including Sonnet 4.5 and Haiku 4.5 |
For every 1M-window model, 1M is the default — no beta header required, billed at standard pricing. Fable 5 and Mythos 5 can generate up to 128K output tokens. A single request can include up to 600 images or PDF pages (100 for 200K-window models).
A larger window is not automatically better. Anthropic warns of context rot: as token count grows, "accuracy and recall degrade." A focused 20K-token prompt often outperforms a bloated 500K-token one.
| Situation | Behavior |
| Input alone exceeds the window | 400 invalid_request_error ("prompt is too long") on every model |
Input + max_tokens exceeds window, on Claude 4.5+ | Accepted; generation stops with stop_reason: "model_context_window_exceeded" |
Input + max_tokens exceeds window, earlier models | Validation error (opt into new behavior with the model-context-window-exceeded-2025-08-26 beta header) |
Modern Sonnet/Haiku models track their remaining budget automatically, injecting tags like <budget:token_budget>200000</budget:token_budget> and post-tool updates like <system_warning>Token usage: 35000/200000; 165000 remaining</system_warning>. Developers never send these. Server-side compaction (beta) and context editing help conversations run past the limit.
Animation Slot
Interactive fill-meter: drag documents into the context window and watch accuracy degrade (context rot) as the meter approaches the limit.
Temperature, top-p, and sampling parameters
Temperature controls the randomness of predictions. Higher → more creative/diverse; lower → more conservative/deterministic. top_p (nucleus) and top_k limit which candidates are eligible, before temperature reshapes the odds among them.
Analogy — the creativity dial. Temperature is a dial on how much weight the model gives lower-ranked candidates. Down toward 0 → safe and repetitive; up → creative but prone to wandering.
The critical shift: Fable 5, Mythos 5, Mythos Preview, Opus 4.8, Opus 4.7, and Sonnet 5 reject non-default temperature, top_p, and top_k with a 400 error — on every request. Omit them and steer via prompting and the effort parameter. Porting code that hard-codes temperature: 0.7 onto Sonnet 5 will fail.
| Model group | Temperature / top_p / top_k |
| Fable 5, Mythos 5, Mythos Preview, Opus 4.8/4.7, Sonnet 5 | Non-default values rejected (400) — steer via prompting + effort |
| Older models (Sonnet 4.5, Haiku 4.5) | Accept temperature, top_p, top_k |
Deterministic vs. probabilistic behavior
"Temperature 0" is not "deterministic." Sampling parameters shape the shape of the distribution (peaked vs. spread) but don't eliminate underlying non-determinism. Lower temperature is more consistent, not guaranteed identical. On the newest models, the lever for consistency is a clear, well-structured prompt with examples.
Key Takeaway: The context window is finite working memory holding everything (accuracy degrades as it fills — context rot). 1M windows are the no-beta-header default on the latest models; older models offer 200K. On the newest models, temperature/top_p/top_k are rejected outright — steer through prompting and the effort parameter.
Post-Quiz · Lock It In
Context Windows and Sampling — After You Read
Pre-Quiz · Check Your Instincts
Model Thinking Options — Before You Read
3. Model Thinking Options
Key Points
- Extended thinking gives Claude a private reasoning scratchpad before its final answer — useful for hard, multi-step problems.
- Manual
thinking: {type:"enabled", budget_tokens:N} is deprecated on 4.6 and rejected with a 400 on Fable 5, Mythos 5, Sonnet 5, Opus 4.8/4.7.
- Adaptive thinking (
{type:"adaptive"}) lets Claude decide per request whether/how much to think, and auto-enables interleaved thinking (thinking between tool calls).
- The
effort parameter (low → medium → high-default → xhigh → max) governs token eagerness across text, tool calls, and thinking; high equals omitting it.
display controls only visibility of thinking, not billing — thinking is billed identically under "summarized" or "omitted".
Fast mode and extended thinking
By default Claude answers directly. For hard problems, extended thinking generates internal reasoning — a private scratchpad — before committing to an answer. Historically it was manual: thinking: {type:"enabled", budget_tokens:N}, where budget_tokens is a subset of max_tokens, billed as output, and counts toward rate limits and the context window. Manual thinking is deprecated on Opus 4.6 and Sonnet 4.6 and rejected with a 400 on Fable 5, Mythos 5, Sonnet 5, Opus 4.8, and Opus 4.7.
Adaptive thinking and effort levels
The modern replacement is adaptive thinking (thinking: {type:"adaptive"}, no beta header). Claude evaluates each request's complexity and "determines whether and how much to use extended thinking." At the default effort (high) it almost always thinks; at lower effort it may skip thinking. It is recommended on Opus 4.8/4.7/4.6 and Sonnet 5/4.6, and the only mode on Fable 5 and Mythos 5.
Analogy — an experienced triage nurse. Manual budget_tokens gives every patient exactly ten minutes; adaptive thinking sizes up each case and routes the paper cut through fast while giving the broken leg its time. Adaptive also auto-enables interleaved thinking — Claude can think between tool calls.
Figure 2.3: Adaptive thinking — how Claude decides whether to reason
flowchart TD
A["Request arrives with thinking: {type: 'adaptive'}"] --> B["Claude evaluates request complexity"]
B --> C{"Complex or multi-step task?"}
C -->|"Yes"| D["Allocate extended thinking (private scratchpad)"]
C -->|"No, and effort is lower"| E["Skip thinking, respond directly"]
D --> F{"Tool calls involved?"}
F -->|"Yes"| G["Interleaved thinking between tool calls"]
F -->|"No"| H["Produce final answer"]
G --> H
E --> H
| Model | Adaptive thinking behavior |
| Fable 5 / Mythos 5 | Always on; {type:"disabled"} not supported |
| Opus 4.8 / 4.7 | Adaptive is the only mode; off unless you set {type:"adaptive"}; manual enabled → 400 |
| Sonnet 5 | Adaptive on by default; pass {type:"disabled"} to turn off; manual enabled → 400 |
| Opus 4.6 / Sonnet 4.6 | Adaptive off unless set; manual budget_tokens accepted but deprecated |
Triggering is promptable ("When in doubt, respond directly" reduces thinking; "Think carefully before responding" increases it). The display field controls visibility only: "summarized" returns a readable summary, "omitted" returns empty thinking blocks. On Fable 5, Mythos 5, Sonnet 5, Opus 4.8/4.7, and Mythos Preview the default is "omitted"; on Opus 4.6/Sonnet 4.6 it is "summarized". Display affects visibility, not billing — thinking is billed identically either way.
The effort parameter (output_config: {effort:"..."}) controls "how eager Claude is about spending tokens." It affects all tokens (text, tool calls/arguments, thinking), needs no thinking enabled, and influences the number of tool calls. effort: "high" is the default and equals omitting the parameter.
| Effort | Behavior | Typical use |
max | Absolute max capability, no token constraint; always thinks | Deepest reasoning on frontier problems |
xhigh | Extended for long-horizon work (30+ min, million-token budgets) | Long-running agentic/coding tasks |
high (default) | High capability, equal to omitting; almost always thinks | Complex reasoning, difficult coding, agents |
medium | Balanced; may skip thinking for simple queries | Agentic tasks balancing speed/cost |
low | Most efficient; skips thinking for simple tasks | Classification, quick lookups, subagents |
When thinking improves reasoning quality
Thinking is a tool, not a default virtue — it adds latency and cost. Use adaptive thinking for agentic behavior (multi-step tool use, complex coding, long-horizon loops); use higher effort for complex reasoning where quality outweighs speed; use lower effort for simple, high-volume, latency-sensitive tasks. Think of max_tokens as the hard cap and effort as the soft dial. Debugging rule: if you see stop_reason: "max_tokens", either raise max_tokens or lower effort.
Key Takeaway: Extended thinking is a private scratchpad; modern models replace fixed budget_tokens with adaptive thinking, which decides per request and auto-enables interleaved thinking. The effort dial governs eagerness across text, tool calls, and thinking (high = omitting). Reserve high effort/thinking for genuinely complex, multi-step, agentic work.
Post-Quiz · Lock It In
Model Thinking Options — After You Read
Pre-Quiz · Check Your Instincts
Fundamental Prompting Techniques — Before You Read
4. Fundamental Prompting Techniques
Key Points
- With sampling knobs disappearing on the newest models, prompting is your primary steering wheel.
- Zero-shot: no examples — only role, task, and format; relies on clear, detailed instructions.
- Single-shot: one worked example. Multi-shot / few-shot: multiple examples — ideally 3–5 diverse, relevant ones.
- Wrap examples in
<example> tags and the set in <examples> tags so Claude distinguishes them from instructions.
- Examples are "one of the most reliable ways to steer Claude's output format, tone, and structure," improving both accuracy and consistency.
Zero-shot prompting
In zero-shot prompting you provide no examples — only role, task description, and expected format. Success depends entirely on clear, direct, detailed instructions.
You are a support-ticket classifier. Classify each ticket into exactly one
category: BILLING, TECHNICAL, or ACCOUNT. Respond with only the category name.
Ticket: "My invoice shows a charge I don't recognize from last month."
Fast to write and cheap in tokens; for unambiguous tasks it is often all you need.
Single-shot and multi-shot (few-shot) prompting
Single-shot adds exactly one example; multi-shot / few-shot provides multiple. "A few well-crafted examples can dramatically improve accuracy and consistency."
Analogy — showing versus telling. Zero-shot hands a new hire a written policy and hopes; few-shot shows three completed examples and says "do it like these." Most people — and models — generalize better from concrete demonstrations.
You are a support-ticket classifier. Classify each ticket into exactly one
category: BILLING, TECHNICAL, or ACCOUNT. Respond with only the category name.
<examples>
<example>
Ticket: "I was double-charged for my subscription this month."
Category: BILLING
</example>
<example>
Ticket: "The app crashes every time I upload a photo."
Category: TECHNICAL
</example>
<example>
Ticket: "I need to change the email address on my profile."
Category: ACCOUNT
</example>
</examples>
Ticket: "My invoice shows a charge I don't recognize from last month."
| Guideline | Detail |
| Quantity | Include 3–5 diverse, relevant examples; more helps for complex/format-constrained tasks |
| Two benefits | Accuracy (reduce misinterpretation) and Consistency (uniform structure/style) |
| Relevance | Examples should mirror your actual use case closely |
| Diversity | Cover edge cases; vary enough that Claude doesn't latch onto an unintended pattern |
| Structure | Wrap each in <example> tags and the set in <examples> tags |
| With thinking | Use <thinking> tags inside examples to demonstrate a reasoning pattern |
Sanity check: "Show your prompt to a colleague with minimal context. If they'd be confused, Claude will be too."
Choosing the right technique
| Technique | Examples | Best for | Trade-off |
| Zero-shot | None | Simple, unambiguous tasks; token-sensitive high-volume work | Cheapest/fastest, but most exposed to misinterpretation |
| Single-shot | One | Tasks where one demo removes format ambiguity | Low cost; may under-specify edge cases |
| Multi-shot | 3–5 diverse | Complex tasks, structured output, tone/style consistency | Highest accuracy/consistency; more tokens and authoring effort |
Sound default workflow: start zero-shot; if output is inconsistent or misreads edge cases, add examples — single-shot, then a diverse 3–5 multi-shot set. Because sampling parameters are unavailable on the newest models, few-shot is often the first tool to reach for when tightening reliability.
Key Takeaway: Zero-shot gives no examples and relies on clear instructions; single-shot adds one; multi-shot adds 3–5 diverse examples in <example>/<examples> tags. Examples are the most reliable way to steer format, tone, and structure. Start zero-shot and add examples as reliability demands — especially since sampling-parameter tuning is off the table on the newest models.
Post-Quiz · Lock It In
Fundamental Prompting Techniques — After You Read