How an LLM Works: Tokens, Temperature and Top-p in Practice
How an LLM turns your prompt into text: tokenization, next-token prediction, temperature, top-p and the context window, and why it hallucinates.
A teammate opened a ticket titled "non-deterministic LLM in production": same prompt, same model, two different answers five minutes apart. He had already set temperature: 0 and expected identical output. It isn't a bug — it's how an LLM generates text, and understanding that mechanism settles half the questions that come up once you put a language model inside an application.
The short answer: an LLM predicts the next token, one at a time, from a probability distribution over its entire vocabulary. It samples (or picks) one token from that distribution, appends it to the text, and repeats until it stops. Temperature, top-k and top-p are just ways of tweaking that draw; the context window is the cap on how much text goes into each step.
This is the technical deep dive. If you want the big picture — what generative AI is, where it fits and where it doesn't — start with What is generative AI and come back here to see the engine.
Tokenization: the model doesn't read words, it reads chunks
Before any prediction, text becomes a list of numbers. The tokenizer splits the input into tokens — whole words, word fragments or bytes — and each token has an ID in the vocabulary. The most common family is BPE (Byte Pair Encoding), which builds the vocabulary by merging the most frequent byte pairs in the training corpus. Every company trains its own: OpenAI publishes theirs in the tiktoken library; Anthropic doesn't publish Claude's tokenizer, but exposes a token counting endpoint.
I ran tiktoken with two public OpenAI tokenizers to see the effect in practice:
| Tokenizer | Vocabulary | tokenização (Portuguese) |
Brasília |
|---|---|---|---|
cl100k_base (GPT-4) |
100,277 tokens | token + ização |
Bras + ília |
o200k_base (GPT-4o) |
200,019 tokens | token + ização |
Brasília |
With the bigger vocabulary, " Brasília" became a single token. That has direct consequences:
- The same text costs a different number of tokens on each model — and you pay per token.
- A "1M token" window is not 1M words. Anthropic estimates about 555k words in 1M tokens on Claude's current tokenizer, introduced with Claude Opus 4.7 (models overview, checked in November 2026).
- Non-English text usually costs more. In the four sentences I measured (Portuguese and the English translation),
cl100k_baseused 1.46× more tokens for Portuguese;o200k_base, 1.19×. It's a small sample — the exact number depends on the tokenizer and the text — but the direction is consistent.
Next-token prediction: the core loop
With the input tokenized, the model runs one forward pass and returns a number (a logit) for every token in the vocabulary. Softmax turns those numbers into probabilities that sum to 1. One token is chosen, appended to the sequence, and the whole sequence goes back in for the next pass. That's autoregressive generation: every output token costs one forward pass, so a 300-token answer is 300 passes.
Input (o200k_base): ["A", " capital", " do", " Brasil", " é"]
Pass 1 → distribution: { " Brasília": 0.74, " Rio": 0.17, " São": 0.06, ... }
Chosen token: " Brasília"
New input: ["A", " capital", " do", " Brasil", " é", " Brasília"]
Pass 2 → distribution: { ".": 0.81, ",": 0.12, ... }
(The prompt is Portuguese for "The capital of Brazil is".) The first pass uses the numbers from the temperature example further down; the second pass is illustrative. With an older tokenizer like cl100k_base, the same answer would take two passes: first " Bras", then "ília".
The model has no stored "answer". It has billions of weights tuned so that its next-token distribution looks like the text it saw in training.
How the model learns: pre-training, fine-tuning and RLHF
Training a modern LLM has, roughly, three stages:
- Pre-training. The model reads a huge corpus and learns to predict the next token by minimizing cross-entropy between the distribution it predicts and the token that actually came next. Grammar, facts and code patterns all land here — as sequence statistics.
- Instruction tuning (SFT). A pre-trained model completes text but doesn't follow requests. It's fine-tuned on well-written question-and-answer examples so it behaves like an assistant.
- Preference tuning (RLHF/RLAIF). People compare pairs of answers and mark the better one; a reward model learns those preferences and the LLM is optimized against it. That's the InstructGPT recipe. In the RLAIF variant, part of the judging comes from another model guided by written principles, as in Anthropic's Constitutional AI.
The point many people get wrong: RLHF aligns the model with human preferences — helpful, polite, well-formatted answers — not with a database of verified facts. It reduces some errors, but it doesn't turn the model into a database.
Attention: why long context is expensive
Self-attention is what lets the model use the whole context on every pass. For each token it computes query, key and value vectors and decides how much each earlier token weighs on the current prediction — that's how "she" in a sentence gets tied to the right subject two sentences back, something an n-gram model that only looks at the last N tokens can't do.
In the standard attention of the original Transformer, cost grows with the square of the sequence length: doubling the context quadruples the attention work. Providers use many optimizations to make 1M-token windows viable, but the rule of thumb holds: big context is slower and pricier, and Anthropic itself warns that accuracy and recall drop as context grows ("context rot", in the context windows docs).
Temperature, top-k and top-p: an example where the numbers add up
The distribution coming out of softmax is rarely used raw. Three controls reshape it before the draw:
- Temperature (T) divides the logits before softmax. T below 1 concentrates probability on the favorite; T above 1 flattens the distribution. T = 0 is treated as greedy decoding: always the most likely token.
- Top-k keeps only the k most likely tokens and renormalizes.
- Top-p (nucleus sampling, from Holtzman et al.) keeps the smallest set of tokens whose cumulative probability reaches p, and renormalizes.
I computed, with a Python script, five candidates to continue "A capital do Brasil é", with logits [4.0, 2.5, 1.5, 0.5, 0.0]:
| Token | T = 0.5 | T = 1.0 | T = 1.5 |
|---|---|---|---|
| " Brasília" | 0.945 | 0.739 | 0.580 |
| " Rio" | 0.047 | 0.165 | 0.213 |
| " São" | 0.006 | 0.061 | 0.110 |
| " uma" | 0.001 | 0.022 | 0.056 |
| " a" | 0.000 | 0.014 | 0.040 |
(Rounded to three decimals; each column sums to 1.)
Now apply top_p = 0.9:
- At T = 1.0: " Brasília" (0.739) + " Rio" (0.165) = 0.904 ≥ 0.9. Two tokens survive, renormalized to 0.818 and 0.182.
- At T = 1.5: " Brasília" + " Rio" = 0.793, still short; adding " São" gives 0.903. Three tokens survive: 0.642, 0.236 and 0.121.
That's why top-p is called adaptive: when the model is confident the nucleus is small; when it's unsure, the nucleus grows. A top_k = 2 would cut at the same two tokens at any temperature.
OpenAI's Responses API reference documents temperature from 0 to 2 with a default of 1, top_p with a default of 1, and recommends altering one or the other, not both (API reference, checked in November 2026). Two more controls complete the picture: the output token cap (max_tokens at Anthropic, max_output_tokens in OpenAI's Responses API), which cuts generation when reached, and stop sequences, strings that end generation when they appear.
In 2026, you often can't touch these at all
With reasoning models, providers started locking sampling down. At Anthropic, models from Claude 4.7 on accept only the default values, and on API version 2026-10-21 any request that sends temperature, top_p or top_k gets a 400 error, even at the default value (2026-10-21 migration guide). The control you're left with is reasoning effort (effort), not randomness. If your code still sends temperature: 0.2 "for consistency", check the docs for the model you use before upgrading the SDK.
And about the ticket from the opening: temperature 0 doesn't guarantee identical output on inference servers. The most solid explanation today comes from Thinking Machines (September 2025): kernels aren't invariant to batch size, and batch size depends on server load at that moment. The same request lands in different batches and the floating-point math comes out different.
The context window: working memory with a hard limit
Everything the model "remembers" in a request is in the context: system prompt, history, documents, tool definitions and the answer being generated (reasoning tokens included). The model keeps nothing between passes beyond that context: with Anthropic's Messages API, for example, you resend the whole history on every call, and even when a provider stores the conversation for you, it goes back into the window on every request.
Current sizes, checked on the official pages in November 2026:
| Model | Context window | Max output |
|---|---|---|
| Claude Opus 5.5, Sonnet 5.5, Haiku 5.5 (Anthropic) | 1M tokens | 128K tokens |
| GPT-6 Astra (OpenAI) | 1,050,000 tokens (922k max input) | 128K tokens |
| Gemini 4 Argon (Google) | 1,048,576 tokens, input and output combined | 65,536 tokens in default synchronous mode |
Sources: Anthropic, OpenAI, Google. These numbers change with every release — treat the table as a snapshot of the month.
What happens when it overflows? The API doesn't drop old tokens on its own. At Anthropic, if the input alone exceeds the window, the API returns a 400 ("prompt is too long"); if the input fits but input + max_tokens doesn't, models from 4.5 on accept the request and stop with stop_reason: "model_context_window_exceeded" when generation hits the limit. At OpenAI, the default (truncation: "disabled") is to fail with a 400; the "auto" option, which dropped items from the start of the conversation, is marked deprecated. Whoever trims, summarizes or compacts the history is the application — the chat app you use, your agent, or a server-side compaction feature you explicitly turn on. And the limit isn't "not enough hardware": it comes from the architecture, from how far the model was trained to use context, and from cost.
Why the model hallucinates with such confidence
Hallucination is the model producing false information in the same tone it uses when it's right. It follows directly from the loop: the goal is the plausible continuation, not the true one. And since each token depends on the previous ones, one bad token contaminates the rest. If sampling picks "To" after "The capital of Canada is", the most likely continuation becomes "ronto" — and the model will defend Toronto fluently, because that's now the context.
Plausibility and truth are different objectives, and RLHF, as we saw, optimizes preference. To reduce the problem in production, put the facts in the context and ask the model to lean on them: that's what RAG does. Explicit instructions help too — there's a practical guide in how to write clear prompts and a less recipe-driven take in prompt engineering without formulas. Once the model starts calling tools and taking actions, a hallucination costs more; I covered that in where AI agents actually help.
Frequently asked questions
Does the model "think" before answering?
Reasoning models generate intermediate tokens before the final answer: Claude with adaptive thinking, OpenAI models with reasoning.effort, among others. Mechanically it's still next-token prediction — the gain comes from the model writing intermediate steps that enter the context and guide the rest. Those tokens take up context window space and are billed as output tokens.
Why does Portuguese text use more tokens than English?
Because tokenizers are trained on English-dominated corpora, so common English words become a single token while Portuguese words with inflections and accents get split more. In the sentences I measured, the gap was 1.46× on cl100k_base (GPT-4) and 1.19× on o200k_base (GPT-4o). Bigger vocabularies shrink the gap but don't close it.
What's the difference between top-k and top-p?
Top-k always cuts at the same number of candidates; top-p cuts by cumulative probability mass. In this post's example, top_p = 0.9 kept two tokens at T = 1.0 and three at T = 1.5, while top_k = 2 would keep two in both cases. Providers recommend tuning temperature or top-p, not both.
Why doesn't temperature 0 always give the same answer?
Because the math itself varies on the server. Inference kernels aren't batch-invariant, and the batch changes with load, so logits come out slightly different and, in a close race, the chosen token changes. On several current models you can't even send temperature anymore: determinism has to come from your system (response caching, output validation), not from the parameter.
An LLM is a well-calibrated draw, repeated token by token
Tokenization, autoregressive prediction and sampling explain almost everything that looks odd about an LLM: why cost depends on language, why long context is slow, why the same question yields different answers, and why one bad token mid-sentence turns into a confident hallucination. The model doesn't look up facts or check what it writes; it estimates the most plausible continuation and draws from it.
In practice: measure tokens instead of words, don't count on temperature for determinism, treat the context window as a limit your application has to manage, and put the facts in the prompt when the answer has to be right. To get a ballpark of a prompt's size before sending it, I paste the text into the word and character counter — it isn't a token count, which only the model's tokenizer gives you, but it warns you when that "small context" already has 40,000 words.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.