The short answer
#You cannot switch hallucination off, but you can make it rare and make it visible. Give the model the facts it needs in the prompt instead of relying on what it remembers, tell it plainly that "I do not know" is an acceptable answer, ask it to quote the source, and then check the quote in code. Where the answer feeds a decision, add a human review step. The model is a very good reader and a poor encyclopaedia; design around that.
_10const system = `Answer using only the document below._10If the document does not contain the answer, say "Not covered in the source."_10Quote the exact sentence you relied on._10_10<document>_10${doc}_10</document>`;
Why it happens
#A language model is trained to predict the next token: given everything so far, what text is most likely to come next? That objective rewards fluent, plausible output. It does not reward truth, and it does not include any notion of "I have no information about this". When you ask for the opening hours of a shop the model has never seen, the most likely continuation is still a time, because answers to that kind of question usually contain a time.
There is no flag inside the model that says "this is a fact I stored" versus "this is a pattern I completed". Both come out in the same confident voice. That is why hallucinations are hard to spot by reading: they look exactly like correct answers. Things it has seen a lot (the syntax of a for loop) are reliable; things it has seen rarely or never (your pricing page, a library released last month, a paper by someone with an uncommon name) are where it fills gaps with plausible invention. URLs, citations, version numbers, function names and statistics are the classic failure points because they look structured and precise, and the model has learnt the shape without the content.
The fix is not to make the model smarter. It is to change the task from "recall" to "read and report", and to build checks on the outside.
How to fix it
#Give it the facts
If the answer exists in a document, put the document in the prompt. For a handful of pages, paste the text into the system prompt. For a large corpus, retrieve the relevant chunks first (search your database, or use embeddings and a vector index) and include only those. This is retrieval-augmented generation (RAG), and it is the single biggest lever: a model reading a passage in front of it is far more reliable than one recalling from training.
Tell it that not knowing is fine
Models follow instructions about tone and scope, so give one. "If the answer is not in the document, say so" works much better than you might expect, because it offers the model a high-probability continuation that is not a made-up fact. Pair it with "do not use outside knowledge" when you want answers grounded strictly in the source.
Ask for quotes and verify them in code
Have the model return the exact sentence it relied on, then check that the sentence really appears in the source. A fabricated answer usually comes with a fabricated quote, and String.includes catches it.
_18const Answer = z.object({_18 answer: z.string(),_18 quote: z.string().describe('An exact sentence copied from the source that supports the answer'),_18 confidence: z.enum(['high', 'low', 'not_in_source']),_18});_18_18const response = await client.messages.parse({_18 model: 'claude-sonnet-5-5',_18 max_tokens: 1024,_18 system,_18 messages: [{ role: 'user', content: question }],_18 output_config: { format: zodOutputFormat(Answer) },_18});_18_18const { answer, quote, confidence } = response.parsed_output;_18if (confidence === 'not_in_source' || !doc.includes(quote)) {_18 return { answer: null, reason: 'No supported answer found' };_18}
Normalise whitespace before comparing, since the model may tidy a line break.
Use structured outputs so it cannot invent categories
When the output is a classification, give the model a fixed list. With a JSON schema and an enum, the API constrains the response so the model literally cannot return a category you did not define. The same trick works for status codes, country codes and product IDs you pass in.
_10const Ticket = z.object({_10 category: z.enum(['billing', 'bug', 'feature_request', 'other']),_10 summary: z.string().max(200),_10});
Always include an escape hatch such as other; without one, the model is forced to pick a wrong category when none fits.
Lower the stakes with human review
Decide what happens when the model is wrong before you ship. Drafting a reply that a person sends is low risk; sending it automatically is not. Showing a suggested tag that an agent confirms is fine; silently closing a ticket is not. Where a mistake is costly, keep a person in the loop and show them the quote so they can check in seconds.
Evaluate on real questions
Collect twenty to fifty real questions with known answers and run them through your prompt whenever you change it. Count how often the model answers correctly, declines correctly, and makes something up. You will learn which kinds of question cause trouble, and you will notice when a prompt change makes things worse.
Common pitfalls
#- Trusting generated URLs. Models produce links that look right and lead nowhere. Fetch every URL in code before showing it, or only allow links that came from your own data.
- Trusting library APIs it suggests. A model may invent a method name or an option that does not exist, especially for new or niche packages. Check the docs, or let the type checker and tests catch it.
- Confusing confidence with correctness. Fluent, assertive text is the model's default register, not a signal that it knows. Build your checks on evidence (quotes, lookups), not tone.
- Asking the model to check its own answer in the same breath. "Are you sure?" often produces a confident "Yes". A separate verification step with the source in front of it works far better.
- Burying the facts. A relevant paragraph lost in two hundred pages of unrelated text gets missed. Retrieve the relevant chunks and keep the context focused.
- Reaching for sampling settings. Hallucination is not randomness; a wrong answer can be the most likely one. Grounding, instructions and structure fix it; fiddling with sampling does not.
Related reading
#quick question
Was this resource helpful?
by Danny