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:
- Pick one token from those probabilities.
- Add it to the end of the text.
- Run the whole model again on the longer text.
- 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.
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.
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)))| Temperature | Behavior | Good for |
|---|---|---|
| 0 to 0.3 | Nearly always the most likely token | Facts, data extraction, classification, code |
| 0.7 to 1 | Natural variety | Chat, writing, explanations |
| Above 1 | Surprising, then incoherent | Brainstorming, with care |
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.
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:
| Model | Year | Context window, tokens | Roughly |
|---|---|---|---|
| GPT-3 | 2020 | 2,048 | A few pages |
| GPT-4 | 2023 | 8,192 (also a 32,768 version) | A long article |
| Claude 2.1 | 2023 | 200,000 | A long novel |
| Gemini 1.5 Pro | 2024 | 1,000,000 (later 2,000,000) | Several books |
| Llama 4 Scout | 2025 | 10,000,000 | Dozens of novels |
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.
- 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.
- 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.
- 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.
- 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.
- 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.How does an LLM produce a long answer?
2.What happens when you raise the temperature?
3.What is the context window?
4.Why do LLMs hallucinate?
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
- Anthropic: Tracing the thoughts of a large language modelWhat researchers found inside Claude, including how it plans rhymes and does mental math.
- OpenAI: Why language models hallucinateA readable explanation of why training and benchmarks reward confident guessing.
- ChatGPT Prompt Engineering for Developers (DeepLearning.AI)A free short course on writing prompts that get reliable results, with code you run in the browser.
- Holtzman et al. (2019), The Curious Case of Neural Text DegenerationThe paper that introduced top-p (nucleus) sampling and showed why greedy decoding gets repetitive.
- Liu et al. (2023), Lost in the MiddleHow language models use, and miss, information in long contexts.