RAG · Lesson 43 of 120
Citing Sources
Which file said it.
Customers trust an answer more when they can see where it came from. And so do we, when we check it. So we ask the model to cite its source after each fact.

- Show where it came from
- Builds trust
- Easy to check
Answers with sources
Each chunk now starts with its file name in square brackets. The instruction asks for the source after every fact. Our question needs two different pages. Run it. Each fact ends with the file it came from.
citations.pypython
from rag_kit import load_docs, make_chunks, Index
from llm import llm
index = Index(make_chunks(load_docs()))
q = "How long is the frame warranty, and how do I return a bike?"
hits = index.search(q, k=4)
context = "\n\n".join(f"[{c['source']}] {c['text']}" for s, c in hits)
prompt = f"""Answer in two short sentences, using only the context.
End each sentence with its source in brackets, like [shipping.md].
{context}
Question: {q}"""
print(llm.invoke(prompt).text.strip())Output
Northwind frames come with a lifetime warranty for the original owner [warranty.md]. You can return an unused bike within 30 days of delivery by paying a £25 collection fee [returns.md].
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Why cite
Citations let customers read the full page. They let you check the model didn't invent anything. And when an answer is wrong, the source tells you whether retrieval or the model was to blame.
| key | value |
|---|---|
| Customers | read more |
| You | check facts |
| Debugging | who was wrong |
| Format | [file.md] |
Summary
Put the source name on each chunk, and ask the model to cite it after every fact. Next, structured answers.
Key takeaways- Label chunks
- Cite each fact
- Check sources
Next up: Structured Answers — answer plus sources