Answers with Sources
Citations in RAG are references from an answer back to the passages it used. They let people check an answer and let you spot when a model claims something the documents don't say. Just as important is the "I don't know" answer: when nothing in the documents matches, the system should say so instead of guessing.
Cite, Check, or Decline
| Technique | Description |
|---|---|
| Numbered passages | It is used to give each retrieved passage a number the model can refer to |
| Structured citations | It is used to get the cited numbers back as data, not buried in text |
| Citation check | It is used to drop any cited number that doesn't match a retrieved passage |
| Score threshold | It is used to decline before calling the model when no passage matches well |
Example
This program uses the docs folder from "Building a RAG Pipeline":
from pathlib import Path
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
from model_api import ModelClient
MIN_SCORE = 0.35 # below this, nothing in the documents is close enough (chosen by testing)
class CitedAnswer(BaseModel):
answer: str
sources: list[int] # numbers of the passages used
chunks = [{"source": p.name, "text": t.strip()} for p in sorted(Path("docs").glob("*.md"))
for t in p.read_text().split("\n\n") if not t.startswith("#")]
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode([c["text"] for c in chunks], normalize_embeddings=True)
client = ModelClient()
def ask(question):
scores = vectors @ model.encode(question, normalize_embeddings=True)
best = [i for i in scores.argsort()[::-1][:3]]
if scores[best[0]] < MIN_SCORE:
return f"I couldn't find this in the school's documents (best match {scores[best[0]]:.2f}). Please contact the school office."
passages = "\n".join(f"[{n}] {chunks[i]['text']}" for n, i in enumerate(best, start=1))
result, reply = client.parse(
[{"role": "user", "content": f"Passages:\n{passages}\n\nQuestion: {question}"}],
CitedAnswer,
system=("Answer only from the numbered passages and list the numbers you used in sources. "
"If they don't answer the question, say so and leave sources empty."),
max_tokens=500,
)
if result is None:
return "No answer; please contact the school office."
valid = [n for n in result.sources if 1 <= n <= len(best)] # never trust a citation blindly
names = sorted({chunks[best[n - 1]]["source"] for n in valid})
return f"{result.answer} (Sources: {', '.join(names) or 'none'})"
for q in ["Does the fee waiver cover tuition?", "What is the school's policy on pets?"]:
print(q)
print(" ", ask(q))Example output. The best-match score, the decision to decline, and the source file names are real output of this code. The waiver answer was produced by an AI model on November 16, 2026, to show the shape; the program ran end to end against a local test server that returned it, not a live API.
Does the fee waiver cover tuition?
No. Fee waivers cover lab, library and field trip fees, but not tuition. (Sources: fee-policy.md)
What is the school's policy on pets?
I couldn't find this in the school's documents (best match 0.34). Please contact the school office.Explanation: For the waiver question, the best passage scores 0.71, so the three passages are numbered and sent with a rule to cite them. client.parse() returns a CitedAnswer whose sources lists the passage numbers used; the code keeps only numbers that exist and turns them into file names. For the pets question, the best score is 0.34, below MIN_SCORE, so the program declines without calling the model, which is both safer and cheaper.
Choosing the Threshold
The threshold separates questions the documents cover from those they don't.
Common Mistakes
Trusting citations without checking them. A model can cite a passage number that doesn't exist; validate in code.
Showing sources nobody can open. Link each source name to the actual document.
Never declining. Without a threshold, the system answers off-topic questions from the least-bad passage.
Interview Corner
How do you add citations to a RAG system?
Number the retrieved passages, ask the model to list the numbers it used (ideally as structured output), validate those numbers in code, and show the matching document names or links.
How should a RAG system handle questions its documents don't cover?
Decline clearly and point to a person or another source, for example when the best retrieval score is below a tested threshold, or when the model reports that the passages don't answer the question.
Practice
Exercise: test the threshold. Ask five on-topic and five off-topic questions and print the best score for each. Is 0.35 the right threshold for these questions? What would you change it to?
Check your understanding:
- Why number the passages?
- Why check the cited numbers in code?
- What happens below the threshold?
Key Takeaways
Quick reference
| Need | Approach |
|---|---|
| Cite | [1] passage numbering plus sources: list[int] |
| Check | Keep only numbers in range |
| Decline | Best score below the threshold |
Was this tutorial helpful?