Temperature, Top-p, and the Knobs That Matter

Demystify the five sampling parameters every LLM API exposes — temperature, top-p, top-k, max_tokens, and stop sequences — with interactive intuition for when to turn each one up or down.

Estimated time
~14 min
Difficulty
intermediate
Sources
4 sources

In the previous lesson on prompt engineering you built a production-grade stacked prompt — a system message, a few-shot chain-of-thought example, and a structured output fence — to reliably extract structured data from messy text. That prompt controls what you say to the model. This lesson covers the other half: the numerical knobs that control how the model answers.

You hand two writers the same brief. One works with a sharp, decisive editorial voice; the other experiments freely, chasing unusual angles. You didn’t change the brief — you changed something about the writer. LLM sampling parameters are that “something”.

What happens the instant before a token is chosen

Every LLM generates text one token at a time. Before each token is selected, the model produces a logit — a raw score — for every token in its vocabulary (often 50 000+ tokens). The raw scores are meaningless on their own; the model converts them into a probability distribution through a function called softmax.

Softmax def.

A function that converts a vector of arbitrary real numbers (logits) into a probability distribution where all values are positive and sum to 1. For logit vector z with temperature T: P(token i) = exp(z_i / T) / Σ exp(z_j / T).

The key insight is what happens inside that formula when you divide by T before taking the exponential:

  • Divide by a small T → differences between logits are amplified → winner-take-all distribution
  • Divide by large T → differences shrink → flatter, more uniform distribution
  • T = 1 → raw softmax, the model’s “natural” distribution

You saw this logit-to-probability step described in “How LLMs Work” — now you’re getting the dial that reshapes it.

Temperature: sharpness, not intelligence

Temperature is the most-used and most-misunderstood parameter. Move the slider and watch the distribution reshape in real time.

Token probabilities at varying temperatures. The bars represent the same 12 tokens; only the temperature changes.

Common misconception

Higher temperature makes the model smarter or more creative.

What's actually true

Temperature doesn’t add knowledge or creativity — it redistributes probability mass. A high-temperature model that writes an evocative metaphor was drawing on patterns already learned during training. The same model at T=0 would simply always choose the statistically safest continuation. Creativity is an emergent property of which tokens get considered, not a separate resource that temperature unlocks. Cranking temperature above ~1.5 typically produces incoherent text, not richer ideas.

When to lower temperature (toward 0)

  • JSON extraction, structured output
  • Code that must compile
  • Factual Q&A where hallucination risk is high
  • Classification tasks

When to raise temperature (toward 1–1.3)

  • Brainstorming, creative writing, marketing copy
  • Paraphrase generation (you want variety)
  • Generating multiple diverse candidates for a downstream ranker

Temperature in practice

Prompt: “Write an opening sentence for a product description of a standing desk.”

T = 0.1: “The ErgoLift standing desk is designed to help you work comfortably throughout the day.” T = 0.9: “Your spine called — it wants its life back.” T = 1.8: “Furniture liminal the productivity sunrise ergonomic standing desk today.”

The first is safe and generic. The second is memorable. The third is noise.

Check your understanding

A developer sets temperature=2.0 to get 'smarter' answers from the model. What will most likely happen?

Top-p: cutting the long tail

Even at a sensible temperature, the probability distribution has a long tail: hundreds of tokens with tiny but non-zero probabilities. If the model samples that tail too often, outputs drift toward incoherence. Top-p sampling (also called nucleus sampling) fixes this.

Top-p (nucleus) sampling def.

A sampling strategy that, at each decoding step, retains only the smallest set of tokens whose cumulative probability mass meets or exceeds p. All other tokens are zeroed out before sampling. Introduced by Holtzman et al. (2020).

[The Curious Case of Neural Text Degeneration]

The elegant property: the nucleus automatically shrinks when the model is confident and expands when it’s uncertain. If the top token has 90% probability, the nucleus at p=0.9 contains just that one token. If probability is spread across 30 tokens, the nucleus contains all 30.

Left: which tokens are inside the nucleus (green) vs excluded (dark). Right: cumulative probability curve — the yellow line is your top-p cutoff.

Practical guidance

  • p = 0.9–0.95 is the community default for conversational tasks
  • p = 1.0 disables top-p filtering; temperature alone governs selection
  • p = 0.1–0.5 for very structured outputs where you want a tight nucleus

Top-p and temperature interact multiplicatively. Temperature reshapes the distribution first; top-p then slices it. Anthropic’s Claude defaults to top-p=1 and uses temperature as the primary knob. OpenAI recommends altering temperature or top-p, not both simultaneously — tuning both makes it hard to know which caused a change.

Check your understanding

You're using top-p=0.9. The model is highly confident about the next word (one token has 95% probability). How many tokens are in the nucleus?

Top-k: a hard vocabulary cap

Top-k sampling def.

A sampling strategy that retains only the k highest-probability tokens at each decoding step, regardless of their actual probability values.

Top-k is a blunter instrument than top-p:

  • Advantage: fully predictable computational cost — always exactly k candidates
  • Disadvantage: fixed k=40 treats a near-uniform distribution (where 40 tokens are plausible) the same as a peaked distribution (where 40 tokens includes a lot of garbage)

Top-k and top-p are usually applied together. The order is: apply top-k first (drop everything outside the k best), then apply top-p (drop everything outside the nucleus), then sample with temperature-scaled probabilities. This means each constraint can only make the effective vocabulary smaller, never larger.

When top-k matters most

  • When your API exposes top-k as the primary diversity knob (some local model runtimes)
  • As a safety net paired with a loose top-p — for example, top-k=100, top-p=0.95
  • k=1 means greedy decoding — same effect as temperature=0
Creative writing JSON extraction Code generation Chat
Temperature 1.0–1.30.00.1–0.30.7–0.9
Top-p 0.951.0 (no-op)0.950.9
Top-k 501 (greedy)4040
Max tokens 512–204864–256256–1024150–300
Stop sequences none or \n\n} or ]\n\n or EOF markernone
Typical parameter settings by task type

Check your understanding

You set top-k=5 and top-p=0.9. The model has 3 tokens with probability [0.4, 0.35, 0.2] and the rest near-zero. How many tokens end up in the final sampling pool?

Max tokens and stop sequences: the budget and the brake

Two parameters control when the model stops rather than what it samples:

max_tokens

The hard ceiling on output length. The model cannot exceed it. Setting this too low truncates answers mid-sentence; setting it too high wastes compute and (in pay-per-token APIs) money.

Token budgeting

Budget for the maximum expected output, not the average. A model generating SQL might almost always produce 50 tokens, but occasionally generate 400 for a complex query. Set max_tokens to the 95th-percentile output length for your task, not the median.

Stop sequences

An array of strings that, when generated, cause the model to stop immediately (the stop string itself is discarded). This is how you enforce output fences from the previous lesson’s prompt templates:

api-call.ts Stop sequences for a JSON extraction task
const response = await client.messages.create({
  model: "claude-opus-4-5",
  max_tokens: 256,
  stop_sequences: ["```"],   // stop when the model tries to close the code fence
  messages: [{ role: "user", content: prompt }],
});

Stop sequence as a structural guarantee

You ask the model to output JSON inside a markdown fence:

\`\`\`json
{ "name": "Alice", "age": 30 }
\`\`\`

Without a stop sequence, the model might continue after the closing fence with an explanation: “Note that the age field may need verification…” — now your parser fails.

Set stop_sequences: [" ``` "] (the closing fence) and the model halts the moment it would generate it. Your parser receives clean JSON.

Check your understanding

A model keeps truncating its answers before finishing. Which parameter is most likely misconfigured?

Putting it together: a preset comparison

The interactions between parameters are where practitioners get confused. This widget lets you explore four canonical presets and then build your own combination.

Show the mental model for picking parameters from scratch

Work through these questions in order:

  1. Is correctness binary? (The output either parses or it doesn’t; the SQL either runs or it doesn’t.) → Start at T=0, top-k=1. Add stop sequences. You’re done.
  2. Do I want diverse outputs? (Multiple paraphrase candidates, brainstorming lists) → Raise temperature to 0.8–1.2. Widen top-p to 0.95.
  3. Is the long tail dangerous? (Medical advice, legal summaries) → Tighten top-p to 0.5–0.7 even at moderate temperature. This keeps diversity among the plausible tokens while cutting the tail where dangerous suggestions live.
  4. How long should the output be? → Set max_tokens to 1.5× the expected maximum. Add stop sequences if the output has a natural terminator (closing bracket, sentinel phrase).
  5. Tune from there. One knob at a time. Log inputs and outputs. A/B a single variable.

Check your understandingQ 1 / 5

Which parameter controls how sharply the model favors its top-ranked token at each step?