How LLMs generate text, and why they go wrong
One token at a time
Generation is a loop:
- The model reads the whole conversation so far (your message, its instructions, earlier turns).
- It outputs a probability for every possible next token.
- One token is chosen.
- That token is appended, and the loop repeats until the model emits a stop token.
Choosing the next token
- Greedy decoding always picks the most likely token. Predictable but often repetitive.
- Sampling picks randomly according to the probabilities.
- Temperature reshapes the probabilities. Low temperature (near 0) makes the model more focused and consistent; high temperature makes it more varied and creative, and more error-prone.
- Top-p (nucleus) sampling only samples from the smallest set of tokens whose probabilities add up to p, cutting off unlikely nonsense.
This is why the same question can get different answers each time.
The context window
The context window is how many tokens the model can consider at once: the instructions, conversation, documents and its own output. Modern models handle hundreds of thousands of tokens, some a million or more. Beyond it, earlier content must be dropped or summarized. Even within the window, models can pay less attention to material buried in the middle of very long inputs.
The model has no memory between conversations unless the application stores information and feeds it back in.
Hallucinations
A hallucination is a fluent, confident statement that is false: an invented citation, a made-up statistic, a nonexistent API function. Causes:
- The model is trained to produce plausible text, and plausible isn't the same as true.
- Its knowledge is compressed and imperfect, especially for rare facts, recent events, and precise numbers.
- Training has historically rewarded answering over admitting uncertainty.
Reducing them:
- Ground answers in provided sources (retrieval-augmented generation) and ask for citations.
- Give the model tools: search, calculators, code execution, databases.
- Tell it explicitly that "I don't know" is acceptable.
- Verify anything important, especially names, numbers, quotes, laws and citations.
Other limits to know
- Training cutoff: no knowledge of later events without tools.
- Sensitivity to wording: small prompt changes can change answers.
- Sycophancy: a tendency to agree with the user, even when the user is wrong.
- Prompt injection: instructions hidden in documents or web pages can hijack a model that reads them.
- Bias inherited from training data.
- Cost and speed: bigger models and longer outputs cost more and take longer. Providers price per million input and output tokens.
Check your understanding
You want consistent, factual answers for a data-extraction task. Which setting helps?
An LLM invents a court case that doesn't exist. The MOST effective mitigation is: