AI Agents & LLMsMedium
How do you make an LLM cite its sources reliably?
Learning path, stage 3 of 5: RAG and fine-tuning · question 8 of 10Give each source a clear ID, require citations next to each claim, and check them. Either use the provider's built-in citations feature, which returns exact cited spans, or check in code that each quoted passage or source ID really exists in what you retrieved. Prompt-only citations can be invented, just like any other text.
Approaches
- Native citations: send the documents as document blocks with citations enabled. The response comes back as text blocks linked to exact character or page ranges.
- Quote-then-answer: the model first pulls exact quotes and then answers from them. Check each quote with a substring match.
- ID citations: sources labelled
[1]…[n]. Check that the cited IDs exist and, optionally, use a judge to check that each one supports its claim.
UX tips
- Link each citation to the source passage so users can check it.
- Show "no source found" instead of a made-up answer.
- Log citation accuracy as a metric.
Sources
Code example
tsx
1// Native citations: the response links text to exact spans in the document.2import Anthropic from "@anthropic-ai/sdk";34const client = new Anthropic();56export async function citedAnswer(policyText: string, question: string) {7 const res = await client.messages.create({8 model: "claude-opus-5-5",9 max_tokens: 1024,10 messages: [{11 role: "user",12 content: [13 {14 type: "document",15 source: { type: "text", media_type: "text/plain", data: policyText },16 title: "Refund policy",17 citations: { enabled: true },18 },19 { type: "text", text: question },20 ],21 }],22 });2324 for (const block of res.content) {25 if (block.type !== "text") continue;26 const refs = (block.citations ?? []).map((c) => `"${c.cited_text}"`).join("; ");27 console.log(block.text + (refs ? ` ← ${refs}` : ""));28 }29}
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, 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.