Chapter 3 · Templates, Multimodal and Settings
Sampling and Reasoning Controls: Temperature, Top-p, Effort and Repeatability
- Page 13 of 24
- 14 min read
Many guides say "set the temperature low for accurate answers". That advice is out of date, and it mixes up two different things: how random the model's choices are, and whether the answer is true. This page separates them. You will see what a prompt can control and what a setting controls, what temperature and top-p do, why a setting may be missing or rejected, and how to measure repeatability instead of assuming it.
The code uses the standard library and promptlab. The sampler in it is a toy provider, a stand-in with invented scores, so that the effect of a setting can be shown repeatably. It is not a real model and its numbers say nothing about one. Real models are less predictable, which is why you measure them yourself.
What you will learn
- The difference between prompt instructions and inference settings, and why a sentence in a prompt cannot change a setting.
- What temperature and top-p change in a sampler, and what they cannot change.
- Why randomness is not accuracy, and how to compare repeatability across runs.
- How reasoning-effort controls and output-length limits relate, and why you must not assume two models offer the same parameters.
- How to read the provider's current documentation before changing a setting.
Prompt instructions versus inference settings
A prompt instruction is text the model reads: the task, the format, the rules. An inference setting is a value sent next to the prompt, in the request or in the app's controls: how randomly to choose tokens, how long the output may be, how much to deliberate. The model cannot read a setting, and settings cannot be changed from inside a prompt.
Weak prompt:
Use temperature 0 and top-p 0.1 and give me the most accurate answer.This prompt changes nothing about the sampling. The model just reads the words, and "most accurate" is an empty request. Say what you need in the task itself, and set the knobs where they live.
Better prompt:
Classify the review as POSITIVE, NEGATIVE or MIXED. Reply with the label only.
If the review has both praise and a complaint, the label is MIXED.
### REVIEW
The screen is great, but the battery lasts half a day.| You want | Use a prompt instruction | Use an inference setting |
|---|---|---|
| A fixed label set and format | Yes: list the labels, give the rule | No |
| A shorter answer | Yes: "at most 50 words" | An output cap cuts text off; it does not make it shorter or better |
| More varied wording | Ask for several different options | Sampling randomness, where the model allows it |
| More deliberation on a hard task | Goals and constraints | A reasoning-effort setting, where offered |
Temperature and top-p as sampling controls
A model scores every possible next token, and a sampler picks one. Temperature rescales the scores before the pick: a low value makes the highest-scoring choices more dominant, a high value spreads probability onto the others. Top-p (also called nucleus sampling) keeps only the smallest group of top choices whose probabilities add up to p and drops the rest. Both change which tokens can be chosen; neither adds knowledge. The toy below makes the mechanics visible. Its scores are invented, and for the first question they put a wrong answer on top, as a model that has learned a common mistake might.
import math, random
from collections import Counter
from promptlab import Client, ProviderError
SCORES = { # invented raw scores of a toy "model" for each candidate answer
"capital of Australia": {"Sydney": 2.0, "Canberra": 1.6, "Melbourne": 0.5, "Perth": -1.0},
"capital of France": {"Paris": 3.0, "Lyon": 1.0, "Marseille": 0.5, "Nice": 0.0},
}
TRUTH = {"capital of Australia": "Canberra", "capital of France": "Paris"}
def probs(scores, temperature=1.0, top_p=1.0):
"""Softmax with temperature, then keep the smallest top set whose probability reaches top_p."""
if temperature <= 0:
return {max(scores, key=scores.get): 1.0}
weights = {k: math.exp(v / temperature) for k, v in scores.items()}
total = sum(weights.values())
kept, mass = {}, 0.0
for k in sorted(weights, key=weights.get, reverse=True):
kept[k] = weights[k] / total
mass += kept[k]
if mass >= top_p:
break
norm = sum(kept.values())
return {k: v / norm for k, v in kept.items()}
def toy_sampler(messages, temperature=1.0, top_p=1.0, seed=0, **settings):
"""Stand-in model: samples one answer from the toy scores. It has no idea what is true."""
p = probs(SCORES[messages[-1]["content"]], temperature, top_p)
return random.Random(seed).choices(list(p), weights=list(p.values()))[0]
client = Client(toy_sampler)
def run(question, n=200, **settings):
return Counter(client.complete([{"role": "user", "content": question}], seed=i, **settings).text for i in range(n))
print(f"{'question':22} {'temp':>4} {'top_p':>5} {'correct':>7} {'most common answer (share)'}")
for q in SCORES:
for t, tp in [(0, 1.0), (0.3, 1.0), (1.0, 1.0), (1.0, 0.5), (2.0, 1.0)]:
c = run(q, temperature=t, top_p=tp)
top, k = c.most_common(1)[0]
print(f"{q:22} {t:>4} {tp:>5} {c[TRUTH[q]] / 200:7.0%} {top} ({k / 200:.0%})")question temp top_p correct most common answer (share)
capital of Australia 0 1.0 0% Sydney (100%)
capital of Australia 0.3 1.0 21% Sydney (79%)
capital of Australia 1.0 1.0 31% Sydney (54%)
capital of Australia 1.0 0.5 0% Sydney (100%)
capital of Australia 2.0 1.0 34% Sydney (41%)
capital of France 0 1.0 100% Paris (100%)
capital of France 0.3 1.0 100% Paris (100%)
capital of France 1.0 1.0 80% Paris (80%)
capital of France 1.0 0.5 100% Paris (100%)
capital of France 2.0 1.0 57% Paris (57%)Randomness is not factual accuracy
Read the table by question. For France the favourite is right, so lower randomness gives a right answer more often. For Australia the favourite is wrong: at temperature 0 the toy gives the wrong answer 200 times out of 200, perfectly repeatable and perfectly wrong. Raising the temperature makes the right answer appear sometimes, but only because the wrong favourite is weaker; for France the same change makes answers worse. Top-p 0.5 cuts off the tail and also removes the right answer for Australia. The lesson is not "raise the temperature". It is that a sampling setting changes variability, and truth comes from the model's knowledge, your sources and your checks.
Two corrections to common advice. Lower temperature does not make answers truer. And temperature 0 does not guarantee identical output on a real service: lower randomness makes outputs more similar, and providers do not promise word-for-word repeatability. Check your provider's wording.
When sampling controls are unsupported or restricted
Some models, especially reasoning models, reject or ignore sampling settings. Your code must expect that: a setting is a request that may fail.
Provider note (as of 2026-10-12): OpenAI's latest-model guide says to remove
temperature,top_pandtop_logprobswhen reasoning effort is notnone; some models in the family do not accept effortnone, so for them these are always unavailable. Anthropic's migration guide says that on current models a non-defaulttemperature,top_portop_kreturns a 400 error; remove them. Google's Gemini 3 documentation strongly recommends keeping them at their default values and says a temperature below 1.0 can cause looping. These statements are per model and change; older reference pages may still list the parameters as ordinary. Check the current documentation.
A small wrapper makes this explicit: try the setting, and if the call is rejected, retry without it and record what was dropped. The restricted provider here is a stand-in for a model that rejects the parameters.
def toy_restricted(messages, **settings):
"""Stand-in for a model that rejects sampling settings, like a 400 error."""
bad = sorted(set(settings) & {"temperature", "top_p", "top_k"})
if bad:
raise ValueError(f"unsupported parameter(s): {', '.join(bad)}")
return "Canberra"
def call_with_fallback(client, messages, **settings):
"""Try with the settings; if rejected, retry once without them and report what was dropped."""
try:
return client.complete(messages, **settings).text, []
except ProviderError:
return client.complete(messages).text, sorted(settings)
print(call_with_fallback(Client(toy_restricted), [{"role": "user", "content": "capital of Australia"}], temperature=0.2, top_p=0.9))
print(call_with_fallback(Client(toy_sampler), [{"role": "user", "content": "capital of France"}], temperature=0.2))('Canberra', ['temperature', 'top_p'])
('Paris', [])The first line shows the answer and the two dropped settings; the second shows that nothing was dropped. Log the dropped list with the result, because "the run used default sampling" is part of what you tested.
Compare repeatability across runs
Repeatability is how often repeated runs of the same prompt agree. Measure it: run the prompt several times, normalise the output (trim, lower-case, extract the label), and count the most common answer's share. In the first table the last column is exactly that. At temperature 0.3 the Australia answer agreed 79% of the time in the toy; at 2.0 it was 41%. For a real model, three to ten runs per case is a cheap start.
To raise repeatability, set a narrow task rather than relying on a knob: a fixed label list, a fixed output format, a schema-constrained output where offered, and examples. One provider's consistency guidance also points to fixed formats, examples, structured outputs, retrieval and chaining rather than sampling settings. Prompt Chaining: Stages, Fixed Schemas and the promptlab Helper showed the chaining side of this.
Example reply (illustrative; yours will differ):
Run 1: MIXED
Run 2: MIXED
Run 3: Mixed - praise for the screen, a complaint about the battery.
Run 4: MIXEDWhat to notice: run 3 has the same meaning but a different shape. A plain equality check would count it as a disagreement. Normalise first, then compare, and decide whether extra words are a failure of the format rule.
Reasoning-effort controls and output budgets
Some models let you set how much they deliberate before answering. This is a reasoning-effort control: a dial between speed and cost on one side and quality on hard tasks on the other. It is not a sampling control and it does not guarantee a better answer. Use it as you would any setting: measure on your own cases, and change one thing at a time.
Deliberation produces hidden or summarised reasoning tokens. They are usually billed as output and occupy space in the context window, while the visible answer may be short. So a visible length and a reasoning budget are different things, and an output cap may apply to both together. If the cap is too small for the deliberation, the answer can come back empty or cut off. The toy below uses invented sizes to show the effect.
def toy_effort(effort, cap=600):
"""Stand-in: hidden reasoning tokens use the same output budget as the visible answer (invented sizes)."""
reasoning = {"low": 50, "medium": 300, "high": 900}[effort]
visible = max(0, min(250, cap - reasoning))
return {"effort": effort, "reasoning": reasoning, "visible": visible, "complete": visible == 250}
for e in ("low", "medium", "high"):
print(toy_effort(e)){'effort': 'low', 'reasoning': 50, 'visible': 250, 'complete': True}
{'effort': 'medium', 'reasoning': 300, 'visible': 250, 'complete': True}
{'effort': 'high', 'reasoning': 900, 'visible': 0, 'complete': False}With the same cap, the highest effort leaves no room for the visible answer. Always check the stop status (a cut-off reply is reported separately from a normal finish) before you use the text.
Provider note (as of 2026-10-12): OpenAI exposes
reasoning.effortwith several levels that differ per model, and reasoning tokens are reported in the usage details. Anthropic documents adaptive thinking plus aneffortsetting; manualbudget_tokensis deprecated and returns a 400 error on the newest models, and thinking can be always on for some models. Google usesthinking_level(older documents described a token budget). Check the current documentation for your model.
Do not assume every model exposes the same parameters
| Concept | Do not assume | Do this |
|---|---|---|
| Randomness | Every model accepts temperature, top-p and top-k | Wrap the call, as above, and log what was applied |
| Deliberation | One name and one scale for effort | Keep a per-provider settings map in your config, not in your prompt |
| Output length | One cap means the same thing everywhere | Check whether reasoning counts toward it |
| Seeds | A seed gives identical output | Even where a seed exists, do not rely on it; measure |
Read current provider documentation before changing settings
A short routine before you touch a setting:
- Open the page of your exact model; guides for another model can be wrong for yours.
- Find: which parameters are accepted, their defaults, and any note saying "remove" or "recommended default".
- Record the model identifier, the setting and the date in your experiment notes.
- Change one setting, rerun the same cases several times, compare. Prompt Caching and Cost: Stable Prefixes, Usage Data and Estimates builds that experiment.
Where this shows up at work
Teams that classify tickets want the same label every time. Writers want varied options. Analysts want a model to think longer on a hard problem. Each need maps to a different tool: a narrow prompt and a format for consistency, an "give me five options" instruction for variety, and an effort control for deliberation where available. When a vendor changes a model, check that your settings are still accepted.
Common mistakes
- Using a low temperature as an accuracy fix. It makes wrong answers repeatable too. Fix sources and checks.
- Writing "temperature 0" in the prompt. The model reads it as text; the setting is unchanged.
- Expecting identical output at temperature 0. Not promised. Compare after normalising.
- Hard-coding sampling settings for all models. A model that rejects them breaks the call. Wrap and log.
- Setting a small output cap on a deliberating model. Hidden reasoning can use the budget and cut off the answer.
Try it yourself
Run the page's blocks in order in one Python folder with promptlab.py beside them.
- Easy. Explain in two sentences why "Set temperature to 0" typed into a chat prompt does nothing.
- Medium. Using
run, compare temperature 0.1 and 1.5 for "capital of Australia" and for "capital of France". Which question gets better with lower temperature, and why is that not a general rule? - Hard. Write
agreement(question, runs, **settings)that returns the share of the most common answer, and use it to choose between three configurations for the France question. Add a rule: reject a configuration that scores lower on correct answers even if it agrees more.
Answers
Easy. The model reads the sentence as ordinary text; sampling settings are sent as separate request values or app controls, and the model cannot change them. Pass checklist: names the difference between text and setting; says where the setting really lives.
Medium.
for q in SCORES:
for t in (0.1, 1.5):
c = run(q, temperature=t)
print(f"{q:22} temp {t}: correct {c[TRUTH[q]] / 200:.0%}")capital of Australia temp 0.1: correct 0%
capital of Australia temp 1.5: correct 34%
capital of France temp 0.1: correct 100%
capital of France temp 1.5: correct 68%France improves at the low temperature because its top-scoring answer is right; Australia gets worse because its top-scoring answer is wrong. A setting amplifies what the model already prefers. Pass checklist: both questions compared; the reason is the position of the right answer in the toy's scores; no claim about real models.
Hard.
def agreement(question, runs=200, **settings):
c = run(question, runs, **settings)
return c.most_common(1)[0][1] / runs, c["Paris"] / runs
for cfg in [dict(temperature=0.0), dict(temperature=1.0), dict(temperature=1.0, top_p=0.5)]:
agree, correct = agreement("capital of France", **cfg)
print(cfg, f"agree {agree:.0%} correct {correct:.0%}", "REJECT" if correct < 1 else "ok"){'temperature': 0.0} agree 100% correct 100% ok
{'temperature': 1.0} agree 80% correct 80% REJECT
{'temperature': 1.0, 'top_p': 0.5} agree 100% correct 100% okPass checklist: agreement and correctness are measured separately; the rejection rule uses correctness; the answer says that agreement alone could pick a configuration that is repeatably wrong, and that a toy cannot choose settings for a real model.
Summary
- Prompts carry the task; settings are separate request values. A prompt cannot change a setting.
- Temperature and top-p change variability. They do not add truth, and temperature 0 does not guarantee identical output.
- Some models restrict or reject sampling settings; wrap calls and log what was applied.
- Measure repeatability by repeated runs and normalised comparison; raise it with narrow tasks and fixed formats.
- Reasoning effort and output caps interact through hidden reasoning tokens; check stop status.
- Read the current documentation for your exact model before changing any setting.
Next: Prompt Caching and Cost: Stable Prefixes, Usage Data and Estimates, where you run a controlled settings experiment and look at cache usage and cost.

