ai/courses

AI Fundamentals/Lesson 7 of 8

How LLMs Generate Text: Temperature, Context, Hallucinations

Next-token sampling, temperature, context windows, and where hallucinations come from.

Lesson
7 of 8
Time
25 min
Updated

TL;DR

The short answer

An LLM writes one token at a time. It reads all the text so far, gives every token in its vocabulary a probability of coming next, picks one, adds it to the text and repeats, until it picks a special "end" token. Settings such as temperature and top-p decide how adventurous each pick is.

The model can only see what fits in its context window, its working memory, and it has no built-in fact checker. It produces the most plausible continuation, which is usually true and sometimes confidently wrong. That's a hallucination.

One token at a time

Everything from the previous lessons comes together here. Your prompt is split into tokens (lesson 3), the tokens become embeddings (lesson 4), and the embeddings pass through all the transformer layers (lesson 5). At the top, the model produces one thing: a probability for every token in its vocabulary of being the next one. For a vocabulary of 200,000 tokens, that's 200,000 numbers that add up to 100%.

Then a very simple loop takes over:

  1. Pick one token from those probabilities.
  2. Add it to the end of the text.
  3. Run the whole model again on the longer text.
  4. Repeat until the model picks a special end-of-text token, or the app's length limit is reached.

That's why ChatGPT's answers appear word by word. It isn't a typing animation for dramatic effect. Each token really is computed after the previous one, with a full pass through billions of weights.

Fig. 1The generation loop: the model scores every possible next token, one is picked and appended, and the longer text goes back in. A 500-word answer is roughly 670 tokens, so roughly 670 passes through the model.

One token at a time doesn't mean the model has no plan. In 2025 Anthropic researchers traced what happens inside their Claude model while it writes rhyming poetry. Before starting a line, the model had already picked the word the line would end on, then wrote the line to reach it. The output comes out one token at a time, but the computation behind each token can look ahead.

Temperature and top-p: how adventurous each pick is

How exactly do you pick one token from the probabilities? The obvious answer, always take the most likely one, is called greedy decoding. It's predictable, which is good for facts and code, but for longer texts it tends to be bland and can get stuck repeating itself. So most chatbots sample: they roll weighted dice. If "pepperoni" has a 34% chance, it gets picked about a third of the time.

Two settings shape those dice:

  • Temperature reshapes the probabilities before the roll. Low temperature makes the favorite even more likely, so answers get predictable. High temperature flattens the odds, so unlikely tokens get picked more often: more variety, more surprises and, past a point, more nonsense. Temperature 1 uses the model's own probabilities unchanged.
  • Top-p, also called nucleus sampling, removes the long tail. With top-p 0.9, only the most likely tokens that together add up to 90% stay in the draw, and the weird leftovers are thrown out. Top-k is a cruder version: keep only the k most likely tokens.

Try both in the demo. Sample at temperature 1 a few times, then drag the temperature to the extremes.

DemoPick a prompt, then change temperature and top-p and sample. The bars show each candidate’s chance of being picked next. The scores are illustrative; a real model scores every token in its vocabulary.
sampling.py
import numpy as np

tokens = ["Paris", "a", "located", "the", "Lyon"]
logits = np.array([6.0, 3.5, 3.0, 2.5, 1.5])   # raw scores from the model

def probabilities(logits, temperature):
    z = logits / temperature
    e = np.exp(z - z.max())
    return e / e.sum()

for t in [0.2, 1.0, 2.0]:
    p = probabilities(logits, t)
    print(f"T={t}: " + ", ".join(f"{tok} {q:.1%}" for tok, q in zip(tokens, p)))

rng = np.random.default_rng()
print("sampled:", rng.choice(tokens, p=probabilities(logits, 1.0)))
CodeTemperature in a few lines of numpy, with made-up scores: divide the scores by the temperature, turn them into probabilities with softmax, then roll the dice. At 0.2, “Paris” gets 100%. At 2.0 it drops to 55.9%, and even “Lyon” gets 5.9%.
TemperatureBehaviorGood for
0 to 0.3Nearly always the most likely tokenFacts, data extraction, classification, code
0.7 to 1Natural varietyChat, writing, explanations
Above 1Surprising, then incoherentBrainstorming, with care
TableRough guidelines. Many apps don’t expose the setting at all, and some reasoning models don’t let you change it.

This also explains a common surprise: ask the same question twice and you get two different answers. That's the dice, not the model changing its mind. Even at temperature 0 the output can vary slightly between runs, because of how the calculations are split across GPUs, so don't build anything that depends on an LLM repeating itself word for word.

The context window: the model’s working memory

A model can only see a limited amount of text at once: its context window, measured in tokens. Everything has to fit inside it: the app's hidden instructions (the system prompt), the conversation so far, any documents you pasted, your question, and the answer the model is about to write.

Fig. 2The context window is everything the model can see in one go. When a conversation outgrows it, the oldest text falls out of view.

Here's the part that surprises people: the model doesn't remember your conversation. It has no memory between calls at all. Every time you send a message, the app sends the entire conversation again, from the top, and the model reads it fresh. It's like a support agent who has never seen you before, quickly reading the whole ticket history before each reply.

When the conversation gets too long, the app has to drop or summarize the oldest messages, and the model "forgets" what you said at the start. Long chats also get slower and, if you pay per token, more expensive, because each new message re-sends everything before it.

Context windows have grown enormously:

ModelYearContext window, tokensRoughly
GPT-320202,048A few pages
GPT-420238,192 (also a 32,768 version)A long article
Claude 2.12023200,000A long novel
Gemini 1.5 Pro20241,000,000 (later 2,000,000)Several books
Llama 4 Scout202510,000,000Dozens of novels
TableContext window sizes as announced by each company. A token is about three quarters of an English word.

Why LLMs hallucinate

A hallucination is an answer that's fluent, confident and false: a book that doesn't exist, a quote nobody said, a wrong date, a function in a code library that was never written. The text reads exactly like a correct answer, and that's the problem.

It follows from how the model works. Pretraining taught it to produce plausible text, not true text. When the model knows something well, such as the capital of France, the plausible continuation and the true one are the same. When it doesn't know, such as the birthday of someone mentioned once on the internet, it still produces a plausible continuation, and a made-up date looks just as plausible as the real one. There's no separate database of facts to check against, only patterns spread across billions of weights.

Training can make it worse. A 2025 OpenAI paper argued that the way models are trained and tested rewards guessing over admitting uncertainty. It's like a multiple-choice exam with no penalty for wrong answers: a student who guesses on every question scores better than one who leaves blanks, so the model learns to guess.

You can't switch hallucinations off, but you can make them much rarer:

  • Give the model the facts. Paste the document, or use retrieval (lesson 8), and tell it to answer only from what you gave it. Reading from a source is much more reliable than recalling from memory.
  • Let it say "I don't know." Tell it explicitly that not knowing is an acceptable answer.
  • Ask for sources, then check them. A link or quote you can verify is worth more than a confident paragraph.
  • Use search or tools for anything recent, numeric or niche.
  • Verify what matters. Names, numbers, citations, medical, legal and financial claims.

Turning the temperature down doesn't fix it. If the most likely token is wrong, greedy decoding picks the wrong token every single time, very consistently.

Thinking tokens: reasoning before answering

Reasoning models, from lesson 6, use the same generation loop with one addition: before the answer, they write a long scratchpad of reasoning. It's next-token prediction too, and every reasoning token gives the model one more step of computation to work with, the way you're better at long division on paper than in your head.

Some apps show the reasoning or a summary of it; others hide it. Either way you pay for it in time and, through an API, in money, because reasoning tokens are billed like output tokens. Many APIs let you choose how hard the model thinks. Use more for math, code, planning and tricky logic. Skip it for simple questions and casual writing, where it mostly adds waiting.

Exercise · about 5 minutes

Watch the dice roll

About 10 minutes with any chatbot. Start a new chat for each step so earlier messages don't influence the answer.

  1. Creative prompt, three times. Ask "Suggest a name for a coffee shop run by cats." in three new chats. The answers differ: that's sampling.
  2. Factual prompt, three times. Ask "What is the boiling point of water at sea level in Celsius?" The answers barely differ, because one continuation has almost all the probability.
  3. Play with temperature. Google AI Studio is free and has a temperature slider. Ask for a short poem at temperature 0, then at the maximum. Compare.
  4. Hunt a hallucination. Ask for "three academic papers about the history of the paperclip, with authors, years and links," with web search turned off. Then check whether the papers exist.
  5. Fix it. Paste a real article into the chat and ask a question about it, adding "Answer only from the text above. If the text doesn't say, reply 'not in the text.'" Ask one question the article answers and one it doesn't.

Quiz

  1. 1.How does an LLM produce a long answer?

  2. 2.What happens when you raise the temperature?

  3. 3.What is the context window?

  4. 4.Why do LLMs hallucinate?

  5. 5.Which step reduces hallucinations the most?

0 of 5 answered

Key takeaways

  • An LLM writes one token at a time: probabilities for every token, pick one, append it, run the model again.

  • Temperature reshapes the odds: low is predictable, high is adventurous. Top-p throws out the unlikely tail.

  • The context window is everything the model can see. Apps resend the whole conversation each time; what doesn’t fit is forgotten.

  • Hallucinations come from generating plausible text without a fact check. Give the model sources and verify what matters.

  • Reasoning models spend thinking tokens before answering: better on hard problems, slower and more expensive.

Go deeper

AI Fundamentals: How Modern AI Actually Works

  1. 01How machines learn25 min
  2. 02Neural networks30 min
  3. 03Tokens20 min
  4. 04Embeddings25 min
  5. 05Attention and transformers30 min
  6. 06How LLMs are trained30 min
  7. 07How LLMs generate text25 min
  8. 08RAG, tools and agents30 min