Sub topic 3
What models get wrong and why
This chapter covers the failure modes you will meet in almost every LLM feature: hallucination, nondeterminism, context limits, and a few quieter problems. It assumes you have read the chapter on how a model turns a prompt into text. You should also be comfortable with Python and JSON. The goal is a working model of why each failure happens, so you can pick a defense instead of hoping prompts fix everything.
Why failures follow from how the model works
A language model generates text one token at a time. At each step it produces a probability distribution over possible next tokens, and a sampling rule picks one. Nothing in that loop checks a fact, runs a calculation, or consults a source. The model is trained to produce text that is plausible given the text before it. Most of the time plausible and correct coincide. When they do not, you get a failure that looks as confident as a success.
Three properties explain most problems:
- The model's knowledge is compressed into its weights during training and is frozen after a cutoff date.
- Output is sampled, so the same input can yield different outputs.
- The model can only attend to the tokens inside its context window.
Hallucination
Hallucination is output that is fluent and confident but not supported by facts or by the source you gave the model. Typical cases are invented citations, nonexistent function names in code, wrong dates, and made-up policy details.
It happens because the model fills gaps with likely-sounding text. If you ask for the refund policy of a company it has never seen, the most probable continuation is a generic refund policy, and it will read as authoritative.
Hallucination is more likely when:
- the answer depends on rare or recent facts the model saw little of or never saw,
- the prompt presumes something false ("Why did the 2019 version drop feature X?"),
- the task asks for precise details such as numbers, quotes, identifiers, or URLs,
- the model is not given source material and no permission to say "I don't know".
Hallucination also appears when the source is provided. A summary can add a claim that is not in the document. This is sometimes called an unfaithful or ungrounded answer.
Defenses
- Supply the facts in the prompt, as in retrieval-augmented generation, and tell the model to answer only from them.
- Allow an explicit "not found" answer so refusing is cheaper than guessing.
- Ask for quotes or passage identifiers alongside claims, then verify that the quotes appear in the source with ordinary string matching.
- Use code for anything that has one right answer: arithmetic, dates, lookups.
- Restrict outputs to a fixed set where possible, and validate.
The classifier from the topic's code examples shows the last defense. It does not trust the reply, and it falls back to a safe label.
LABELS = ["billing", "bug", "feature_request", "other"]
def classify(ticket: str, complete) -> str:
prompt = (
"Classify the support ticket into exactly one label from: "
+ ", ".join(LABELS)
+ ".\nReply with the label only.\n\nTicket: " + ticket
)
answer = complete(prompt).strip().lower()
return answer if answer in LABELS else "other"If the model replies "Billing issue, probably", the function returns "other" instead of passing a free-form string downstream. Note the trade-off: a fallback hides the failure. In production, also log how often the fallback fires, because a rising rate signals a prompt or model problem.
Nondeterminism
Sampling means the same prompt can produce different answers. A parameter called temperature controls how much randomness is used. At temperature 0 the model usually picks the most probable token each step, which makes output far more repeatable.
Low temperature does not guarantee identical output. Providers may batch requests, use different hardware, or update the model behind a version alias, and any of these can change results. Treat determinism as "mostly stable", not as a contract.
Consequences for your design:
- Do not write tests that compare full output strings. Check properties instead: valid JSON, an allowed label, a required phrase.
- Pin a specific model version where the provider allows it, and re-run your tests when you change it.
- Use low temperature for extraction and classification, and higher values only when variety is the point, such as brainstorming.
- Expect small prompt edits to change behavior. Keep a set of test inputs and rerun it after every edit.
Context limits
The context window is the maximum number of tokens the model can read and write in one request. Your instructions, the conversation history, retrieved documents, and the reply all share it. Exceed it and the request fails or, in some systems, older content is silently dropped.
Larger windows do not remove the problem:
- Cost and latency grow with the number of input tokens.
- Models often use information at the start and end of a long prompt better than information buried in the middle.
- Irrelevant text can distract the model and lower answer quality.
Practical responses are to send only relevant passages, summarize old conversation turns, and count tokens before sending. The table below links each limit to a symptom.
| Cause | Typical symptom | Common mitigation |
|---|---|---|
| Input exceeds window | Request error or truncated history | Count tokens, trim, summarize |
| Key fact buried mid-prompt | Answer ignores a fact that was provided | Retrieve fewer, better passages; put key facts near the end |
| Reply budget too small | Output cut off mid-sentence or mid-JSON | Reserve output tokens; check the stop reason |
| Stale knowledge | Outdated facts stated confidently | Retrieve current documents or call a tool |
Other failures worth knowing
- Format drift. You ask for JSON and get JSON wrapped in prose, or with a missing field. Parse and validate every time.
- Reasoning and arithmetic slips. The model may skip a step or miscompute, especially with long numbers or multi-step logic. Delegate calculations to code.
- Sycophancy. The model tends to agree with the user's stated opinion or accept a false premise. Phrase questions neutrally and test with wrong premises.
- Prompt sensitivity. Reordering examples or rewording an instruction can change the result.
- Bias. Outputs reflect patterns in training data, which can disadvantage groups or reproduce stereotypes. Measure on realistic inputs from your own users.
- Prompt injection. Text inside a document or web page can contain instructions the model follows. A later chapter covers this in detail.
Validate output before you use it
Since you cannot prevent every error, treat model output as untrusted input. This example parses extraction output and fails loudly if a field is missing or has the wrong type.
import json
def parse_invoice(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data.get("vendor"), str):
raise ValueError("vendor must be a string")
if not isinstance(data.get("total"), (int, float)):
raise ValueError("total must be a number")
return data
print(parse_invoice('{"vendor": "Acme", "total": 129.5}'))Validation catches malformed output but not a wrong value. A well-formed {"vendor": "Acme", "total": 1295} passes these checks. For high-stakes values, add cross-checks, such as comparing the total with the sum of the line items, or route low-confidence cases to a person.
A layered response
The usual pattern combines several defenses instead of relying on one.
Each layer targets one cause: retrieval reduces knowledge gaps, grounding rules reduce guessing, low temperature reduces variance, and validation catches what remains. Later chapters on evaluation and safety show how to measure whether the layers work.
Exercise
A summarizer returns, at temperature 0, a summary that includes a figure not present in the source document. A colleague proposes lowering the temperature further. Why will that not fix the problem, and what would you do instead?
Show answer
The figure is a hallucination (an ungrounded claim), not randomness. Temperature only changes how the model samples among likely tokens, and the error can appear on every run. Instead, instruct the model to use only the document, ask it to quote the supporting passage for each figure, verify programmatically that each quoted passage and number appears in the source, and reject or flag summaries that fail the check.
Exercise
Your chat assistant answers well in short conversations but starts ignoring earlier instructions after about fifty turns. Name two likely causes and one fix for each.
Show answer
One cause is that the history approaches the context limit and older turns are truncated or dropped, so the instructions are gone. Fix: count tokens, keep the system instructions pinned at the start, and summarize older turns. Another cause is that long prompts dilute attention on content in the middle. Fix: restate the key rules near the end of the prompt and send only the relevant history.