How LLMs work: tokens, context windows & sampling
Explain tokens, context limits, temperature and why models hallucinate.
By Invicly Tech, , in AI Engineering with Python. About 13 minutes to read.
In short
A large language model predicts the next token from the tokens before it, one step at a time. Text is split into tokens, the whole conversation must fit in a context window, and sampling settings control how random the choices are.
Think of it like this: It is like a very well-read autocomplete that writes one word-piece at a time.
Explained simply
A large language model (LLM) is a program trained on a huge amount of text. Its one skill is guessing what comes next. Give it the start of a sentence and it scores every possible next piece of text, picks one, adds it to the end, and guesses again. A long answer is just this small step repeated hundreds of times.
The model does not read letters or whole words. It reads tokens: small pieces of text, such as "un", "believ" and "able". Common words are often one token, rare words are split into several. Everything is counted in tokens: how much you can send, how fast the answer comes, and how much you pay.
A model can only look at a limited number of tokens at once. This limit is the context window. Your instructions, the chat so far, any documents you paste and the answer it writes must all fit inside it. The model also has no memory between requests, so your app sends the conversation again every time.
Because the model writes what sounds likely, not what it has checked, it can produce confident answers that are wrong. This is called hallucination. It is not a rare bug; it is how the system works. Good AI apps give the model real sources to read and check its answers.
Press Play on a diagram to walk through it one step at a time.
- 1Text in
Prompt plus conversation so far
- 2Tokenise
Split text into token IDs, often word pieces
- 3Model forward pass
Scores every possible next token
- 4Sample
Temperature and top-p pick one token
- 5Append and repeat
Until a stop token or length limit
- Picks likely tokens
- More consistent output
- Good for extraction and code
- Can be repetitive
- Samples less likely tokens
- More varied output
- Good for brainstorming
- More prone to errors
- Instructions
- System prompt
- Output format rules
- Conversation
- Earlier user messages
- Earlier assistant replies
- Knowledge
- Retrieved documents
- Pasted files
- Tools
- Tool definitions
- Tool call results
- The reply
- Output tokens being generated
- Limited by max output tokens
- Learns weights from huge text sets
- Takes weeks and huge GPU clusters
- Fixes a knowledge cutoff date
- Happens before you ever call it
- Weights are frozen and never change
- Only sees what is in the context
- No memory of earlier requests
- Paid per token, in seconds
In depth
Tokenisation: how text becomes numbers
Before the model sees anything, a tokenizer cuts the text into pieces from a fixed vocabulary, usually tens of thousands to a few hundred thousand entries. Most modern tokenizers use byte pair encoding (BPE): start from single bytes, then repeatedly merge the most common neighbouring pairs seen in training data. Frequent words become one token; rare words, names and typos become several.
Each token maps to an integer ID, and the model only works with those IDs. A space is usually part of the token, so " cat" and "cat" can be different tokens. This explains some odd behaviour: models are weak at counting letters in a word because they never see the letters, only the pieces.
For English, a rough rule is 1 token for about 4 characters, or about 0.75 words. Code, numbers and many non-English languages use more tokens for the same meaning, so they cost more and fill the context faster. Each model family has its own tokenizer, so counts differ between providers.
- About 4 characters or 0.75 English words per token
- Same text, different model: different token count
- Numbers are often split into several tokens
- Non-Latin scripts usually need more tokens
- 1Raw text
Hello world!
- 2Pre-split
Split near spaces and punctuation
- 3Merge pieces
BPE joins common byte pairs
- 4Look up IDs
Each piece becomes an integer
- 5Into the model
IDs become vectors the model reads
What happens inside one prediction
Each token ID is turned into a vector (a list of numbers). These vectors pass through many transformer layers. In each layer, an attention step lets every position look back at the earlier tokens and decide which ones matter for it, then a feed-forward step transforms the result. The last layer produces one score, called a logit, for every token in the vocabulary.
Generation has two phases. In prefill, the model reads your whole prompt at once, in parallel, which is fast per token. In decode, it produces the answer one token at a time, because each new token depends on the one before. The model keeps the work it already did for earlier tokens in a KV cache so it does not redo it. This is why long outputs, not long inputs, usually dominate the waiting time.
- 1Token IDs
Integers from the tokenizer
- 2Embeddings
Each ID becomes a vector
- 3Transformer layers
Attention plus feed-forward, repeated many times
- 4Logits
One score per vocabulary token
- 5Sampling
Turn scores into one chosen token
Context windows in practice
The context window counts input and output together. If a model has a 128,000 token window and your prompt uses 120,000, at most 8,000 are left for the answer. Most APIs also have a separate max output tokens setting, and they return an error if the request is too long rather than quietly cutting it.
Everything counts toward the limit: the system prompt, every earlier message, pasted documents, tool definitions and tool results. Long chats therefore grow until something must be dropped. Apps handle this by keeping only recent turns, summarising old ones, or retrieving just the relevant parts.
Bigger is not free. Standard attention work grows faster than the length (roughly with its square), so long prompts are slower and cost more. Models can also miss facts placed in the middle of a very long prompt. Send what is relevant, not everything you have.
- Input plus output must fit in the window
- Tool definitions and results use tokens too
- Long prompts cost more and respond slower
- Put key instructions where they are easy to find
How temperature and top-p really work
The logits are turned into probabilities with a function called softmax. Temperature divides the logits before softmax. A temperature below 1 makes the top choice even more likely; above 1 it flattens the odds so unlikely tokens get picked more often. Temperature 0 effectively means always take the top token (greedy decoding).
Top-p, also called nucleus sampling, then keeps only the smallest group of tokens whose probabilities add up to p, and draws from that group. With p = 0.9, a long tail of strange tokens is cut off. Top-k is a simpler cousin that keeps the k most likely tokens.
Providers usually advise changing temperature or top-p, not both. Even at temperature 0, output can differ between runs, because GPU maths and request batching are not perfectly repeatable. If you need the same answer every time, store it rather than regenerate it.
- 1Logits
Raw score for every token
- 2Divide by temperature
Low sharpens, high flattens
- 3Softmax
Scores become probabilities
- 4Top-p cut
Keep the smallest set reaching p
- 5Random draw
Pick one token from what is left
Why hallucinations happen and how to reduce them
A model is trained to continue text in a likely way, not to look facts up. It stores patterns from training data inside its weights, and rare facts are stored weakly or not at all. It also has a knowledge cutoff: it knows nothing that happened after its training data was collected. When asked something it does not know, the most likely continuation still looks like a confident answer.
Lowering temperature makes output more consistent, but a consistent wrong answer is still wrong. What actually helps is changing what the model has to work with and what it is allowed to say.
- Give it sources: paste or retrieve the relevant documents
- Allow it to say I don't know, and mean it
- Ask for quotes or citations you can check
- Verify with code, tools or a database where possible
- Test with questions whose answers you already know
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Explain tokens and tokenisation~1h
- 2Understand context window limits~1h
- 3Experiment with temperature and top-p~1h
- 4Explain why models hallucinate~1h
Key points
- Models see tokens, not characters or words; one English word is often one to two tokens.
- The context window limits input plus output tokens in a single request.
- Models have no memory between requests; you resend the conversation each time.
- Hallucinations happen because the model generates plausible text, not verified facts.
Key terms
Tap a card to flip it. 0/5 known
Examples
Seeing tokens for yourself
You want to know why a 20-page contract fills more of the context than you expected. Step 1: install a tokenizer library. tiktoken is OpenAI's open-source tokenizer; other model families use different tokenizers, so treat its counts as an estimate for them. Step 2: encode a few strings and compare the token count with the character count. Step 3: notice that common English words are cheap, while long rare words, digits and non-Latin scripts take more tokens. Step 4: for an exact count for your model, read the usage numbers the API returns.
# pip install tiktoken
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
samples = ["hello world", "Hello World!", "antidisestablishmentarianism",
"Order 4815162342 shipped", "こんにちは世界"]
for text in samples:
ids = enc.encode(text)
pieces = [enc.decode([i]) for i in ids]
print(f"{len(text):>3} chars -> {len(ids):>2} tokens {pieces}")Temperature on a toy example
Imagine the prompt is "The capital of France is" and the model gives four candidate tokens raw scores (logits). Step 1: divide the scores by the temperature. Step 2: apply softmax to get probabilities. At temperature 0.5, Paris gets about 98%. At 1.0 it drops to about 84%, and at 2.0 to about 60%, while pizza rises from almost 0 to about 5%. That is why high temperatures produce more surprising, and more often wrong, text.
import math
logits = {"Paris": 5.0, "Lyon": 3.0, "London": 2.0, "pizza": 0.0}
def probs(temperature: float) -> dict[str, float]:
exps = {w: math.exp(v / temperature) for w, v in logits.items()}
total = sum(exps.values())
return {w: round(e / total, 3) for w, e in exps.items()}
for t in (0.5, 1.0, 2.0):
print(t, probs(t))
# 0.5 {'Paris': 0.98, 'Lyon': 0.018, 'London': 0.002, 'pizza': 0.0}
# 1.0 {'Paris': 0.839, 'Lyon': 0.114, 'London': 0.042, 'pizza': 0.006}
# 2.0 {'Paris': 0.598, 'Lyon': 0.22, 'London': 0.133, 'pizza': 0.049}Quick reference
- English rule of thumb: 1 token is about 4 characters or 0.75 words
- Context window = input tokens + output tokens for one request
- Temperature below 1 sharpens choices, above 1 flattens them, 0 is near-greedy
- Adjust temperature or top-p, usually not both at once
- The model keeps no memory: your app resends the history every turn
- Output tokens are generated one by one, so long answers mean long waits
- Knowledge cutoff: the model knows nothing after its training data ends
- Fewer hallucinations: give sources, allow I don't know, verify the answer
Common mistakes
- Assuming temperature 0 guarantees identical output every time.
- Treating model answers as facts without grounding or checking.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Take a paragraph of English and the same paragraph in another language. Estimate tokens with the 4-characters rule, then count them with a real tokenizer.
- Exercise 2medium
Write a function that applies temperature and then top-p to a dict of logits and returns the tokens that remain, with their renormalised probabilities.
- Exercise 3hard
Measure hallucination on a small scale: write 10 questions about your own company or project that a public model cannot know. Ask a model each one twice, once with no context and once with the right document pasted in. Score the answers.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do LLMs understand what they write?
- They build rich internal patterns that capture a lot of meaning, but they are trained to predict likely text, not to check truth. Treat their output as a strong draft that still needs grounding and verification.
- Why does the same prompt give different answers?
- The next token is drawn at random from a probability list, so different runs take different paths. Lower temperature reduces this, but small differences can remain even at 0.
- Does a bigger context window mean I can skip retrieval?
- Not usually. Very long prompts cost more, respond slower and can bury the key facts, so sending only the relevant parts often gives better answers.
- How many tokens is a page of text?
- A typical page of English prose is around 500 words, which is roughly 650 to 700 tokens. Dense tables, code or other languages can be more.