1. Home
  2. Blog
  3. Artificial Intelligence

Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

Temperature and top-p are the two settings that decide how predictable or varied an AI model’s answers are. We simulated the maths behind them with a toy example so you can see exactly what each setting does to the model’s choices.

10 min read
LLM temperature and top-p explained: how AI models choose their next word

Key takeaways

  • A model produces a probability for every possible next token, then samples one.
  • Temperature reshapes those probabilities: low values sharpen them, high values flatten them.
  • Top-p keeps only the most likely tokens that together reach a probability threshold.
  • Use low temperature for extraction and code, moderate for chat, and change one setting at a time.

Ask an AI model the same question twice and you may get two different answers. Ask it to extract a date from an invoice and you want the same answer every time. Ask it for ten slogan ideas and you want variety. The settings that control this trade-off are temperature and top-p, and they are among the most misunderstood options in any AI API.

We could not inspect a commercial model’s internal probabilities, so we built a small Python simulation of the standard sampling maths, using made-up scores for four candidate words. All the numbers below come from that simulation. Real models choose among tens of thousands of tokens, and providers may implement details differently, but the behaviour is the same in principle.

How a model picks the next word

At each step, a large language model outputs a score, called a logit, for every token in its vocabulary. A function called softmax turns those scores into probabilities that add up to 1. The model then samples one token according to those probabilities, appends it to the text, and repeats. Temperature and top-p change the probabilities before that sampling step.

Our toy example

Imagine the prompt “The capital of France is”. We gave four candidate next words these scores:

logits = {"Paris": 5.0, "Lyon": 3.0, "London": 2.5, "banana": 0.0}

Paris is clearly favoured, Lyon and London are plausible-sounding mistakes, and banana is nonsense. A real model would assign some probability to thousands of other tokens too.

Temperature: sharpening or flattening

Temperature divides every score before softmax is applied. Dividing by a small number exaggerates the gaps between scores; dividing by a large number shrinks them. Here are the probabilities our simulation produced:

Temperature Paris Lyon London banana
0.2 1.000 0.000 0.000 0.000
0.7 0.921 0.053 0.026 0.001
1.0 0.817 0.111 0.067 0.006
1.5 0.672 0.177 0.127 0.024
2.0 0.576 0.212 0.165 0.047

At 1.0, the model’s own distribution is used unchanged. At 0.2, Paris gets essentially all the probability. At 2.0, Paris drops to 58%, and even banana rises to almost 5%. Temperature does not add knowledge or creativity in any deep sense. It only changes how willing the model is to pick less likely options, which can mean fresher wording or simply more mistakes.

What sampling looks like

Probabilities are abstract, so we drew 1,000 samples at three temperatures, using a fixed random seed:

T=0.2  {'Paris': 1000, 'Lyon': 0,   'London': 0,   'banana': 0}
T=1.0  {'Paris': 810,  'Lyon': 117, 'London': 70,  'banana': 3}
T=2.0  {'Paris': 607,  'Lyon': 202, 'London': 146, 'banana': 45}

At temperature 2.0, about 4 answers in 10 named the wrong city, and 45 of 1,000 said “banana”. Now remember that a real answer is hundreds of tokens long. A small chance of an odd choice at every step adds up, and one bad token early in a sentence can send the rest of the answer in the wrong direction. This is one reason high temperatures make hallucinations more likely.

Temperature 0 and determinism

At temperature 0, the maths would divide by zero, so APIs treat it as “always pick the most likely token”, called greedy decoding. That makes output far more repeatable, but in practice not perfectly identical every time. Hosted models can vary slightly because of how calculations are batched and parallelised on the provider’s hardware, and models are updated over time. Some APIs offer a seed parameter for better repeatability. Treat temperature 0 as “highly consistent”, not as a guarantee.

Tip: Greedy decoding is not always best, even for factual tasks. It can get stuck repeating phrases in long outputs. For long-form text, a low but non-zero temperature, such as 0.2 to 0.4, often reads more naturally while staying focused.

Top-p (nucleus sampling)

Top-p takes a different approach. It sorts tokens from most to least likely, keeps the smallest group whose probabilities add up to at least p, discards the rest, and renormalises. Applied to our temperature-1.0 probabilities:

top_p=0.5   {'Paris': 1.0}
top_p=0.9   {'Paris': 0.881, 'Lyon': 0.119}
top_p=0.99  {'Paris': 0.821, 'Lyon': 0.111, 'London': 0.067}

At 0.5, Paris alone already covered more than half the probability, so it was the only option. At 0.9, Lyon joined. Even at 0.99, banana was cut off. That is top-p’s strength: it removes the long tail of unlikely tokens that cause nonsense, while adapting to the situation. When the model is confident, few tokens survive; when many continuations are reasonable, more survive.

Top-k and min-p

  • Top-k keeps a fixed number of the most likely tokens, such as 40, regardless of their probabilities. It is simple but does not adapt: 40 may be too many when the model is sure and too few when it is not.
  • Min-p keeps tokens whose probability is at least a fraction of the top token’s probability. It is popular in open-source model tools and is claimed to work well at higher temperatures, though the research is newer.

Not every API exposes every option. Check your provider’s documentation for which parameters are available and what their defaults are.

Using temperature and top-p together

Both settings shape the same distribution, so changing both at once makes behaviour hard to predict. Several providers recommend adjusting one and leaving the other at its default. A reasonable approach is to tune temperature first, since it is easier to reason about, and only reach for top-p if you need to cut off rare oddities at a higher temperature.

Suggested settings by task

Task Temperature Why
Data extraction, classification 0 to 0.2 One correct answer; consistency matters
Code generation 0 to 0.3 Small deviations break code
Question answering with sources 0.1 to 0.4 Stay close to the provided text
General chat, summaries 0.5 to 0.8 Natural tone with reasonable focus
Brainstorming, creative writing 0.8 to 1.2 Variety is the goal

These are starting points drawn from common practice, not rules. Model families differ, defaults differ by provider, and some newer reasoning models fix or ignore these settings entirely. Test with your own prompts. Clear instructions, covered in our prompt engineering guide, usually matter more than fine-tuning these numbers.

Common myths

  • “Higher temperature makes the model smarter or more creative.” It only makes less likely tokens more likely. Sometimes that is welcome variety; often it is just noise.
  • “Temperature 0 means the answer is correct.” It means the most likely answer. If the model is confidently wrong, temperature 0 makes it consistently wrong.
  • “Temperature controls length.” Length is controlled by the prompt and the maximum tokens setting, not by temperature.
  • “Lower is always safer.” Very low settings can cause repetitive or stilted text in long outputs.

Testing AI features

Sampling makes AI features non-deterministic, which changes how you test them:

  • Run each test case several times and measure the pass rate, rather than relying on one run.
  • Check properties, not exact strings: valid JSON, required fields present, numbers matching the source, no banned content. This is the same idea as property-based testing.
  • Fix the temperature in tests to match production, and record it with the results.
  • Re-run your evaluation set whenever you change the model, the prompt or the sampling settings.

Setting it in an API call

Most chat APIs accept these settings as fields in the request body. A typical request for an extraction task looks something like this (an illustration, not run for this article, and field names vary by provider):

{
  "model": "your-model-name",
  "temperature": 0.1,
  "max_tokens": 300,
  "messages": [
    {"role": "user", "content": "Extract the invoice date and total as JSON: ..."}
  ]
}

Keep these values in configuration, not scattered through code, and log them with each request alongside the model name. When an answer looks odd weeks later, knowing the exact settings that produced it saves a lot of guessing. If you serve several features from one model, give each feature its own settings: the summariser and the code assistant rarely want the same temperature.

Final thoughts

Temperature and top-p do not change what a model knows; they change how adventurous it is when choosing each next token. Our toy simulation showed temperature sliding Paris from certain to 58% and top-p cutting off the nonsense tail. Start low for tasks with one right answer, raise temperature only when you want variety, adjust one setting at a time, and test with repeated runs.

Frequently asked questions

What does temperature do in an LLM?

It rescales the model’s probabilities before sampling. Low temperature makes the most likely token dominate; high temperature spreads probability to less likely tokens, increasing variety and risk.

What is top-p sampling?

Top-p keeps the smallest set of most likely tokens whose combined probability reaches p, such as 0.9, and samples only from them. It removes the unlikely tail.

Does temperature 0 give the same answer every time?

Usually very similar answers, but not guaranteed. Hosted models can vary slightly because of how they run, and models are updated over time.

Should I change temperature and top-p together?

Generally no. Both reshape the same distribution, so many providers recommend adjusting one and leaving the other at its default.

What temperature should I use for code?

A low value, typically 0 to 0.3, because small random deviations can break code. Always test the generated code regardless of the setting.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →