Retrieval-Augmented Generation
An LLM knows only what was in its training data — nothing about your company's handbook, yesterday's meeting notes or this week's prices. Retrieval-augmented generation (RAG) fixes that without retraining: for each question, retrieve the most relevant passages from your own documents and put them into the prompt, then let the model generate an answer grounded in them.
The pipeline
┌──────────── offline (indexing) ────────────┐
documents ──► split into chunks ──► embed / index ──► store
└────────────────────────────────────────────┘
question ──► embed / search ──► top-k chunks ──► prompt = instructions + chunks + question ──► LLM ──► answer + sourcesRAG's strengths:
- Fresh and private knowledge — update the documents, not the model.
- Fewer hallucinations — the model can quote the source instead of relying on memory.
- Citations — you know which chunks were used and can show them to the user.
Step 1: retrieval with TF-IDF
Retrieval can use embeddings (see Vector Search) or classic keyword scoring. TF-IDF gives a word a high weight when it appears often in a document but rarely across all documents. scikit-learn makes it a few lines:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
docs = [
"Returns: items can be returned within 30 days with the receipt. Sale items cannot be returned.",
"Shipping: standard delivery takes 3-5 working days. Express delivery arrives the next working day.",
"Opening hours: the shop is open Monday to Saturday, 9:00 to 18:00, and closed on Sundays.",
"Gift cards are valid for two years and can be used online and in the shop.",
"Loyalty programme: members collect one point per euro and get a voucher at 100 points.",
]
vectorizer = TfidfVectorizer(stop_words="english")
doc_vectors = vectorizer.fit_transform(docs)
def retrieve(question, k=2):
scores = cosine_similarity(vectorizer.transform([question]), doc_vectors)[0]
ranked = scores.argsort()[::-1][:k]
return [(int(i), round(float(scores[i]), 3)) for i in ranked]
for q in ["Can I return a sale item?", "Is the shop open on Sunday?", "How long does express delivery take?"]:
print(q, "->", retrieve(q))Can I return a sale item? -> [(0, 0.281), (4, 0.0)]
Is the shop open on Sunday? -> [(2, 0.361), (3, 0.196)]
How long does express delivery take? -> [(1, 0.554), (4, 0.0)]
Each result is (document index, similarity). The right document comes first for all three questions.
Step 2: build the grounded prompt
The retrieved chunks are inserted with clear labels, and the instructions tell the model to answer only from them and to cite them:
docs = {
"returns": "Items can be returned within 30 days with the receipt. Sale items cannot be returned.",
"shipping": "Standard delivery takes 3-5 working days. Express delivery arrives the next working day.",
}
def rag_prompt(question, retrieved_ids):
sources = "\n".join(f'<source id="{i}">{docs[i]}</source>' for i in retrieved_ids)
return (
"Answer the customer's question using only the sources below.\n"
"Cite the source id in square brackets after each claim, e.g. [returns].\n"
"If the sources don't contain the answer, say you don't know.\n\n"
f"{sources}\n\nQuestion: {question}"
)
print(rag_prompt("Can I return a sale item?", ["returns", "shipping"]))Answer the customer's question using only the sources below.
Cite the source id in square brackets after each claim, e.g. [returns].
If the sources don't contain the answer, say you don't know.
<source id="returns">Items can be returned within 30 days with the receipt. Sale items cannot be returned.</source>
<source id="shipping">Standard delivery takes 3-5 working days. Express delivery arrives the next working day.</source>
Question: Can I return a sale item?
Given this prompt, a model typically answers along the lines of "No — sale items cannot be returned [returns]." The citation lets your app link to the source and lets reviewers verify the claim.
Step 3: check the answer against the sources
You can cheaply check that cited ids exist and that the cited source really shares content with the claim. This toy check (word overlap) catches citations to sources that were never retrieved:
import re
retrieved = {
"returns": "Items can be returned within 30 days with the receipt. Sale items cannot be returned.",
}
def check_citations(answer):
report = []
for claim, cite in re.findall(r"([^.\[]+)\[(\w+)\]", answer):
if cite not in retrieved:
report.append(f"'{cite}': NOT a retrieved source")
continue
claim_words = {w.lower().strip(",.") for w in claim.split() if len(w) > 3}
overlap = claim_words & {w.lower().strip(",.") for w in retrieved[cite].split()}
report.append(f"'{cite}': supported by words {sorted(overlap)}")
return report
for answer in ["No, sale items cannot be returned [returns].",
"Yes, you get a full refund within 90 days [refunds]."]:
print(answer)
for line in check_citations(answer):
print(" ", line)No, sale items cannot be returned [returns].
'returns': supported by words ['cannot', 'items', 'returned', 'sale']
Yes, you get a full refund within 90 days [refunds].
'refunds': NOT a retrieved source
What makes RAG work well
| Stage | Common problem | Remedy |
|---|---|---|
| Chunking | chunks too big (noise) or too small (missing context) | split along sections; small overlap (see Chunking) |
| Retrieval | right document not in top-k | hybrid search (keywords + embeddings), better queries, re-ranking |
| Prompt | model ignores sources or adds outside knowledge | explicit "only from sources" instruction; citations |
| No answer | model guesses when nothing relevant was found | similarity threshold → "I don't know" |
| Evaluation | unclear whether retrieval or generation failed | measure them separately (see Evaluating LLM Apps) |
Note: RAG reduces hallucinations but does not eliminate them: the model may still misread a source or combine sources incorrectly. Keep citations visible so users can check.
Go further: Building a RAG Pipeline adds BM25 retrieval written from scratch and treats retrieved text as untrusted input, and Evaluating Retrieval and RAG measures each stage.
Test yourself
What problem does RAG mainly solve?
- Slow tokenization
- The model lacks knowledge of your private or recent documents
- High temperature
- Small vocabulary
When does TF-IDF give a word a high weight in a document?
- When it appears in every document
- When it is frequent in that document but rare across the collection
- When it is the longest word
- When it is a stop word
Why ask the model to cite source ids?
- It makes answers longer
- Users and code can verify each claim against the retrieved text
- Citations are required by the API
- It improves tokenization