What is Sampling and temperature?
Sampling and temperature is an AI engineering fundamental for people who work with LLMs. Where answer variation comes from and when you want more or less of it.
Same month, same company, two complaints. The marketing team asked the model for ten campaign headlines, and got ten headlines that were almost identical.
Meanwhile, the data team was extracting the company tax ID from invoices. And on every run, the field came back in a different format.
Both teams asked the engineer for the same thing: tweak the temperature. One wanted more variation. The other wanted less.
To know whether temperature is even the right knob, you need to understand where variation comes from. That's this lesson. And you'll see why, for one of these two teams, the answer is a different tool altogether.
At every step, the model computes a probability for every possible next token. Sampling is the rule that picks one token from those probabilities.
Picture a weighted die. The most likely word has the biggest face. But the other faces are still there, and sometimes they come up.
Let's follow one step. The model looks at everything already in the sequence.
It produces a distribution. Say, Electronics at eighty percent, Audio at fifteen, and dozens of other words sharing the rest.
Then the sampling settings reshape that distribution, before the draw.
One token is drawn from the adjusted distribution.
And the chosen token joins the sequence. Every later choice depends on it.
That last step matters more than it looks. Since each token depends on the ones before it, a different early choice changes everything after it. Two answers can drift far apart, even when each step varies only a little.
That's what the data team saw. The tax ID came back with dots and a slash, then digits only, then with a period at the end. Three paths, a few tokens apart, and all three plausible.
There are three classic knobs. Temperature sharpens or flattens the distribution. Low temperature raises the peak, so the leading token leads even more. High temperature flattens the chart, and second and third place get a real chance.
Top p doesn't stretch the chart. It cuts the tail, and draws only among the most likely tokens that add up to a given probability.
And top k keeps only a fixed number of the most likely tokens.
One piece of advice. Tuning more than one at once makes the effect impossible to read. If you use these knobs at all, pick one. Temperature alone is enough for an experiment.
Back to the category example. Near zero temperature, Electronics comes out almost every time. At high temperature, Audio shows up, and even Computing. But notice what none of those draws does. None of them turns a punctuated tax ID into fourteen clean digits. Format doesn't live on that knob.
Low temperature reduces variation. It doesn't turn the model into a deterministic function.
Details of how the provider runs the model can still change the output.
A tiny change in the prompt changes everything after it.
And some providers offer a seed setting, to try to repeat a draw. Even when it exists, the docs usually call it best effort. So don't build a test that depends on two identical calls.
Here's one for you. The tax ID extractor returns dots and a slash on one run, and digits only on the next. The data team wants temperature zero. What actually fixes the format?
A schema that asks for a string of fourteen digits, and validation in code before you store the value. At temperature zero, all three spellings are still plausible, so nothing in the draw forces fourteen digits.
And writing always use the same format, please, in capitals, helps a little and guarantees nothing. The model can still be wrong. Your code is what refuses to let the wrong value in. That's the job of structured output, not temperature.
Here's something telling. The newest models from several providers are removing these knobs. On current Anthropic models, like Claude Opus and Sonnet five point five, the API rejects any temperature other than the default. Older models, like Haiku four point five, still accept it.
Control moved elsewhere: the output format, the reasoning effort, and the prompt itself. And that tells you something useful. Tuning sampling was never the right way to guarantee format or correctness. Providers are just making that explicit.
So if you migrate the extractor to one of those models, and the data team panics, the answer is calm. Nothing changes in the contract. The schema, the validation and the eval were always the control.
Now the marketing side. On the page there's an experiment, with a model that still accepts temperature. You generate five headlines at low temperature, and five at high temperature.
Compare the variety between the two blocks. Then try a different route.
Ask, in a single call, for ten headlines that differ from each other, in different tones, for different audiences. Variety you ask for in the prompt usually beats variety you draw at random.
And here's the trap on that side. High temperature spreads the headlines, and it also spreads the quality. One is sharp, the next is an empty slogan. Push it to the extreme, and you trade similar for useless. Ten options in one call let you pick with your own criterion, instead of hoping the draw hits the right tone.
So what changes? For extraction, classification, and any output your code reads, use structured output plus validation. Don't lean on temperature.
For creativity, ask for variety explicitly, and generate several options in one call.
For important decisions, think about where variation hurts. A credit opinion at high temperature means two similar customers can get different answers, with no business reason. There, you want less variation, not more. And running the same task several times and comparing is a pattern of its own, called voting.
And variation is always there. If you run the same test case three times and get three passes, then two, then three, that's normal. The number that matters is the rate over many runs. That's why every system with a model needs evals, and not a test that runs once.
So, back to the two teams. Marketing didn't need a hotter die. It needed to ask for variety. And the data team didn't need a colder one. It needed a schema and a check in code. Temperature changes how wide the draw is. It never guarantees what comes out.
In the next lesson, we'll look at the prompt itself, and treat it like what it really is: an interface, with a contract, versions and tests. See you there.
Amostragem e temperatura
Sampling and temperature is an AI engineering fundamental for people who work with LLMs. Where answer variation comes from and when you want more or less of it.
A marketing team asked the model for ten campaign headline ideas and got ten nearly identical headlines. The same month, the data team complained that tax ID extraction from invoices returned the field in a different format on every run. Both teams asked the engineer for the same thing: “tweak the temperature”.
One wanted more variation. The other wanted less. To know whether temperature is the right knob, you need to understand where variation comes from.
At every step, the model computes a probability for every possible token. Sampling is the rule that picks one token from those probabilities.
flowchart LR
IN(["1. Context so far"]):::io --> P(["2. Next-token probabilities"]):::llm
P --> A["3. Adjust: temperature, top_p"]:::tool
A --> S["4. Draw"]:::tool
S --> OUT(["5. Chosen token"]):::io
Look at step 5: since each token depends on the previous ones, a different early choice changes everything after it. Two answers can diverge a lot even when each step varies only a little. That is what the data team saw: 12.345.678/0001-90, 12345678000190, and 12.345.678/0001-90. are three paths a few tokens apart. (The Brazilian company tax ID, the CNPJ, has a punctuated form and a digits-only form, both plausible.)
| Parameter | What it does | Low value | High value |
|---|---|---|---|
temperature |
Flattens or sharpens the distribution | Almost always the most likely token | Less likely tokens get a chance |
top_p |
Cuts the tail: draws only among tokens that add up to p probability | Few options | Many options |
top_k |
Draws only among the k most likely tokens | Few options | Many options |
Low temperature raises the peak: the leading token becomes even more leading. High temperature flattens the chart: second and third place get a chance. top_p and top_k do not stretch the chart; they throw away the tail and draw only from what remains.
Tuning both at once makes the effect unreadable. If you still use these knobs, pick one. In practice, temperature alone is enough for the experiment; the output format handles the rest.
A concrete example, still illustrative. At the category step, the model assigns 0.80 to Electronics, 0.15 to Audio, and the rest to dozens of other words. Near zero temperature, Electronics comes out almost every time. At high temperature, Audio and even Computing show up. None of those draws produces 12.345.678/0001-90 instead of 14 digits: format does not live on that knob.
Low temperature reduces variation, but it does not turn the model into a deterministic function. Server-side execution details can still change the output, and a tiny prompt change changes everything. If your code needs a fixed format, the answer is Structured Output, not temperature.
The tax ID case is the classic example. Zero temperature can still return dots, slashes, or digits only, because all three forms are plausible. The schema asks for a 14-digit string. Validation in code rejects the rest. Temperature does not do that job.
Some providers offer a seed parameter to try to repeat sampling. Even when it exists, the docs usually treat it as best effort, not a guarantee. Do not build a test that depends on two identical calls.
The newest models from several providers are removing these knobs. On current Anthropic models such as Claude Opus 5.5 and Claude Sonnet 5.5, the API rejects non-default temperature, top_p, and top_k. Earlier models such as Claude Haiku 4.5 still accept them. Control moved elsewhere: the output format, the reasoning effort, and the prompt itself.
That tells you something useful: tuning sampling was never the right way to guarantee format or correctness. Providers are just making that explicit.
This experiment uses a model that still accepts temperature. Generate five headlines at low temperature and five at high temperature.
import anthropic
client = anthropic.Anthropic()
for temperature in (0.0, 1.0):
print(f"--- temperature={temperature}")
for _ in range(5):
reply = client.messages.create(
model="claude-haiku-4-5",
max_tokens=60,
temperature=temperature,
messages=[{"role": "user", "content": "A short headline for a headphones sale."}],
)
print(next(b.text for b in reply.content if b.type == "text"))
Compare the variety between the two blocks. Then try another route for the marketing team: ask for “ten headlines that differ from each other, in different tones” in a single call. Diversity you ask for in the prompt usually beats diversity you draw at random.
The trap here is the inverse of extraction. High temperature spreads the headlines, and it also spreads quality: one is sharp, the next is an empty slogan. Asking for ten options in one call lets you pick with a criterion of your own (eval, rule, human), instead of hoping the draw hits the right tone.
Answer the 6 questions to complete this lesson. Watching alone does not complete it: the check is what counts toward the trail and the certificate.
Sampling and temperature is an AI engineering fundamental for people who work with LLMs. Where answer variation comes from and when you want more or less of it.