What are hallucinations, and how do you reduce them?

Learning path, stage 1 of 5: How LLMs work · question 7 of 10

A hallucination is fluent, confident output that is false or unsupported: invented facts, citations, APIs or numbers. It happens because the model is trained to produce plausible text, not verified text, and it has no built-in way to tell "I know this" from "this sounds right".

Common causes

  • The question is outside its training data or after its knowledge cutoff.
  • Prompts that pressure it to answer, with no "I don't know" path.
  • Long or noisy contexts where the relevant fact is buried.
  • Asking for exact details (quotes, IDs, URLs) from memory.

Mitigations that work

  • Ground it: provide the source documents (RAG) and tell it to answer only from them.
  • Allow abstention: "If the documents don't contain the answer, say so."
  • Require citations or quotes, then check them in code.
  • Use tools for facts and arithmetic (search, database, calculator) instead of recall.
  • Verify: a second pass or a judge model checks claims against the sources.
  • Keep the context tight and put the important material where it's easy to find.

Sources

Code example

tsx
1// Grounded answering with an explicit way out, plus a cheap quote check.
2import Anthropic from "@anthropic-ai/sdk";
3
4const client = new Anthropic();
5
6export async function groundedAnswer(question: string, docs: string) {
7 const res = await client.messages.create({
8 model: "claude-opus-5-5",
9 max_tokens: 1024,
10 system:
11 "Answer ONLY from the <docs>. Quote the sentence you relied on inside <quote> tags. " +
12 "If the docs do not contain the answer, reply exactly: NOT_IN_DOCS.",
13 messages: [{ role: "user", content: `<docs>\n${docs}\n</docs>\n\nQuestion: ${question}` }],
14 });
15 const text = res.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
16
17 // verify: every quoted sentence must really appear in the source
18 const quotes = [...text.matchAll(/<quote>([\s\S]*?)<\/quote>/g)].map((m) => m[1].trim());
19 const grounded = quotes.every((q) => docs.includes(q));
20 return { text, grounded };
21}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app