Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 8 steps

Prompt and Context Engineering
  1. 1
    Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  2. 2
    Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  3. 3
    Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  4. 4
    Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  5. 5
    Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  6. 6
    Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  7. 7
    Context Engineering: What Belongs in the Context Window, Turn by Turn
  8. 8
    Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. LLM Fundamentals

Learning path: Prompt and Context Engineering · Step 1 of 8

Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer

A model scores every next word, softmax turns the scores into probabilities and one word is drawn. See what temperature and top-p do to that draw with six words, plain numpy and 1000 draws.

Chaand Sheikh

·27 November 2026LLM Fundamentals

What you will learn

  • Turn next-word scores (logits) into probabilities with softmax
  • Explain how temperature sharpens or flattens the probabilities before the draw
  • Apply top-p to cut off the unlikely tail and rescale the words that survive
  • Pick sampling settings for extraction, replies, creative work and evals

Before you start

  • Basic Python and numpy
  • What an LLM Can and Cannot Do

Send the same prompt to a model twice and you can get two different answers. Sometimes that's exactly what you want, and sometimes it breaks your app. To control it, you need to know where the difference comes from.

Picture a jar of coloured marbles, where each colour is a word. For the next word, the model fills the jar: lots of green marbles for coffee, fewer blue ones for beans, and just one or two for the rare words. Then one marble is drawn at random. This time it's blue, beans. Draw again and you might get coffee.

Temperature is like shaking up how many marbles of the rare colours there are. Top-p throws the rarest colours out of the jar before you draw. Same jar, different draw, different answer.

Everything below runs with plain numpy. No model, no API key.

From scores to one drawn word scores (logits) divide by temperature softmax probabilities top-p keeps likely words draw one word This repeats for every single word of the reply.
Every next word goes through the same steps. Temperature and top-p change the probabilities, the draw picks one word.

The model scores every next word

Our prompt is "Our coffee shop tagline: Fresh ..." and we want the next word. For every possible next word, the model gives a score. These scores are called logits. Here we use six candidates with scores from 3.0 down to -0.5.

To be clear: these are hand-made scores for teaching, not from a real model. A real model scores every token it knows, tens of thousands of them. (If tokens are new to you, see LLM Tokens, Context Windows and Cost.)

"""Prompt: "Our coffee shop tagline: Fresh ..." - the next word.
Hand-made scores (logits) for six candidates, not from a model."""
import numpy as np

WORDS = ["coffee", "beans", "mornings", "brew", "starts", "ideas"]
LOGITS = np.array([3.0, 2.2, 1.6, 1.0, 0.2, -0.5])


def softmax(scores, temperature=1.0):
    z = scores / temperature
    e = np.exp(z - z.max())          # minus max: no overflow
    return e / e.sum()

That's words.py. Read softmax line by line:

  • scores / temperature divides the scores by the temperature. Keep an eye on this line, because it is the whole trick of temperature.
  • np.exp makes every score positive. Subtracting the max first just keeps the numbers from overflowing.
  • Dividing by the sum makes the results add up to 1. Now they are probabilities.

Scores in, probabilities out

"""Scores in, probabilities out."""
from words import WORDS, LOGITS, softmax

probs = softmax(LOGITS)
for word, score, p in zip(WORDS, LOGITS, probs):
    print(f"{word:9} score {score:5.1f}   prob {p:.3f}")
print("sum of probs:", round(probs.sum(), 3))
coffee    score   3.0   prob 0.520
beans     score   2.2   prob 0.234
mornings  score   1.6   prob 0.128
brew      score   1.0   prob 0.070
starts    score   0.2   prob 0.032
ideas     score  -0.5   prob 0.016
sum of probs: 1.0

coffee gets 0.520, beans 0.234, and the rare words just a few hundredths. All six words still have a chance, and the probabilities add up to 1. This is the jar.

Temperature sharpens or flattens

Now we draw from the jar. The script below makes a random generator with a fixed seed, 42, so you get the same counts when you run it. It loops over three temperatures with the same scores, and for each one rng.choice draws 1000 words with exactly those probabilities.

"""Temperature reshapes the probabilities before we draw."""
import numpy as np

from words import WORDS, LOGITS, softmax

rng = np.random.default_rng(42)
for t in (0.2, 1.0, 1.5):
    probs = softmax(LOGITS, temperature=t)
    print(f"T={t}:", " ".join(f"{w} {p:.2f}" for w, p in
                              zip(WORDS, probs)))
    draws = rng.choice(WORDS, size=1000, p=probs)
    print("   1000 draws, 'coffee':", (draws == "coffee").sum(),
          " different words:", len(set(draws)))
T=0.2: coffee 0.98 beans 0.02 mornings 0.00 brew 0.00 starts 0.00 ideas 0.00
   1000 draws, 'coffee': 979  different words: 3
T=1.0: coffee 0.52 beans 0.23 mornings 0.13 brew 0.07 starts 0.03 ideas 0.02
   1000 draws, 'coffee': 521  different words: 6
T=1.5: coffee 0.40 beans 0.24 mornings 0.16 brew 0.11 starts 0.06 ideas 0.04
   1000 draws, 'coffee': 406  different words: 6
Temperature 0.2, 1.0 and 1.5 on the same six scores T = 0.2 coffee0.98 beans0.02 mornings0.00 brew0.00 starts0.00 ideas0.00 coffee 979 / 1000, 3 words T = 1.0 coffee0.52 beans0.23 mornings0.13 brew0.07 starts0.03 ideas0.02 coffee 521 / 1000, 6 words T = 1.5 coffee0.40 beans0.24 mornings0.16 brew0.11 starts0.06 ideas0.04 coffee 406 / 1000, 6 words
Same six scores, three temperatures. Low temperature piles almost everything on coffee; high temperature gives the rare words a real share.

Read the three runs:

  • T = 0.2. Dividing by a small number stretches the scores apart. coffee jumps to 0.98 and came up 979 times in 1000 draws. Only three different words showed up at all.
  • T = 1.0. Dividing by 1 changes nothing: the original 0.52. coffee came up 521 times.
  • T = 1.5. The scores are squeezed together. coffee drops to 0.40, the rare words get a real share, and all six words appeared. coffee came up 406 times.

The prompt never changed. Only the shape of the jar did. Low temperature almost always gives the top word; high temperature gives the rare words a real chance.

Top-p keeps the likely words only

Top-p works differently. Put the probabilities end to end, most likely first, and keep a running total. Pick a value for p, here 0.9. Keep words until the running total reaches p, and drop everything after that.

"""Top-p: keep the smallest set of words that covers p."""
import numpy as np

from words import WORDS, LOGITS, softmax

probs = softmax(LOGITS)
order = np.argsort(-probs)                 # most likely first
running = np.cumsum(probs[order])
keep = order[: np.searchsorted(running, 0.9) + 1]
print("running total:", np.round(running, 3))
print("kept:", [WORDS[i] for i in keep])

kept = probs[keep] / probs[keep].sum()     # renormalize
for i, p in zip(keep, kept):
    print(f"  {WORDS[i]:9} {p:.3f}")
running total: [0.52  0.754 0.882 0.953 0.984 1.   ]
kept: ['coffee', 'beans', 'mornings', 'brew']
  coffee    0.546
  beans     0.245
  mornings  0.135
  brew      0.074
  • np.argsort(-probs) orders the words, most likely first.
  • np.cumsum gives the running total: 0.52, 0.754, 0.882, 0.953 and so on.
  • np.searchsorted finds where the total crosses 0.9, and we keep everything up to there. 0.882 is not enough yet, so brew joins and the kept words cover 0.953.
  • Last, we rescale the survivors so they add up to 1 again. coffee goes from 0.520 to 0.546, and the draw happens from these four words only.
Top-p = 0.9 on the six probabilities coffee 0.520 beans 0.234 mornings brew p = 0.9 0 1 0.52 0.754 0.882 0.953 kept: coffee, beans, mornings, brew (cover 0.953) dropped: starts, ideas rescaled: coffee 0.546, beans 0.245, mornings 0.135, brew 0.074
Top-p with p = 0.9. The words up to the cut survive and are rescaled; starts and ideas can never be drawn.

So top-p cuts off the long tail of unlikely words, but it keeps the variety among the good ones. Temperature changes the shape of the whole jar; top-p removes the rare marbles from it.

When do you want variety?

TaskSettingWhy
Extract fields, classify a tickettemperature 0 or closeone right answer: take the top word
Help-desk reply, summarylow to mediumnatural wording, same facts
Taglines, ideas, nameshigher, maybe top-pyou want different options
Tests and evalsfixed settings, many runsmeasure the spread, not one lucky answer

The last row matters more than it looks. If the output can change from run to run, one passing run proves very little. Keep the settings fixed and run each case several times, as in LLM Regression Testing in CI.

Change one knob at a time. If you move temperature and top-p together, you can't tell which one changed the output. Defaults and allowed ranges differ by provider, so check its documentation before you pick numbers.

Common mistakes

  • Expecting the same answer twice with a medium or high temperature. Different draws are the model working as designed.
  • Using a high temperature for extraction or classification. There is one right answer; extra variety only adds wrong ones.
  • Judging a prompt on one run. At any temperature above zero you see one draw from the jar, not the jar.
  • Turning both knobs at once, then guessing which one helped.
  • Copying numbers from another provider. Ranges and defaults are not the same everywhere.

Quick recap

IdeaWhat it doesIn our example
Logitsone score per possible next word3.0 down to -0.5 for six words
Softmaxscores to probabilities that add up to 1coffee 0.520, beans 0.234
Low temperaturesharpens: the top word almost always winsT=0.2: coffee 979 of 1000, 3 words
High temperatureflattens: rare words get a real shareT=1.5: coffee 406 of 1000, 6 words
Top-pkeeps the words covering p, drops the tailp=0.9 keeps 4 words, coffee rescaled to 0.546

Try it yourself

  1. In 02_temperature.py, add 0.01 and 5 to the temperatures. (Our small softmax divides by the temperature, so 0.01 stands in for "close to zero".)
  2. In 03_top_p.py, change 0.9 to 0.5. How many words survive?
  3. In words.py, give ideas a score of 3.5 and rerun all three scripts.

The three scripts, a README and sample prompts are in the StudyEasy AI Community, free to join.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Prompt and Context Engineering · step 1 of 8

Next post
Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

The AI Stack in One Picture: Six Layers Every AI Product Is Built From

Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.

Tokenization: What an LLM Actually Sees When You Type

A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.

LLM Tokens, Context Windows and Cost: What One Question Really Costs

Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.

What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps

A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.

On this page

  • The model scores every next word
  • Scores in, probabilities out
  • Temperature sharpens or flattens
  • Top-p keeps the likely words only
  • When do you want variety?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.