Advanced RAG Patterns
Advanced RAG is everything a retrieval-augmented system needs beyond "find similar text and pass it to the model" once real users, real documents and real risks are involved. It must only retrieve what each user is allowed to see, prefer the current version of a document, combine several sources for one answer, cite each one, abstain when nothing relevant exists, and be diagnosed stage by stage when it fails.
"Building a RAG Pipeline" built the basic version. This lesson adds the production patterns.
The Patterns
| Pattern | Description |
|---|---|
| Access control at retrieval | It is used to filter documents by the user's permissions before ranking, so private text never reaches the model |
| Freshness and versions | Keep the latest version of each document; remove deleted ones from the index |
| Multi-document answers | It is used to retrieve the top few passages, so answers can combine sources |
| Citations | Name the source and date of every fact |
| Abstaining | It is used to decline when no passage scores above a threshold |
| Query rewriting | Rephrase or expand the question, or ask several versions, before searching |
| Parent-child retrieval | It is used to search small chunks but give the model the larger section around them |
| Failure analysis | Label each failure by stage: parsing, retrieval, ranking, threshold or generation |
Example: Permissions, Freshness, Citations and Abstaining
The programs need pip install sentence-transformers numpy. Download and loading messages are left out of the output shown.
This program has five documents with metadata: two versions of the fee schedule, a payment policy, a staff handbook and a confidential list of fee waivers. Three kinds of user ask questions.
from sentence_transformers import SentenceTransformer
# A small document store with metadata: who may see each section, and when it was published
DOCS = [
{"id": "fees-2025", "date": "2025-07-01", "audience": "public", "title": "Fee Schedule 2025-26",
"text": "The science lab fee is $40 a year."},
{"id": "fees-2026", "date": "2026-07-01", "audience": "public", "title": "Fee Schedule 2026-27",
"text": "The science lab fee is $45 a year and is due by September 30."},
{"id": "late-2026", "date": "2026-07-01", "audience": "public", "title": "Payment Policy 2026-27",
"text": "A late fee of $10 is added when a payment is more than 14 days overdue."},
{"id": "staff-pay", "date": "2026-07-01", "audience": "staff", "title": "Staff Handbook",
"text": "Teachers are paid on the last working day of each month."},
{"id": "waivers", "date": "2026-07-01", "audience": "office", "title": "Fee Waiver Decisions",
"text": "Fee waivers approved this term: 12 families, list attached."},
]
CAN_SEE = {"parent": {"public"}, "staff": {"public", "staff"}, "office": {"public", "staff", "office"}}
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode([d["text"] for d in DOCS], normalize_embeddings=True)
def retrieve(question, role, k=2, threshold=0.35):
# 1. Access control BEFORE ranking: a user can never retrieve what they may not see
allowed = [i for i, d in enumerate(DOCS) if d["audience"] in CAN_SEE[role]]
# 2. Freshness: when a document has newer versions, keep only the latest
latest = {}
for i in allowed:
series = DOCS[i]["id"].split("-")[0]
if series not in latest or DOCS[i]["date"] > DOCS[latest[series]]["date"]:
latest[series] = i
pool = sorted(latest.values())
scores = vectors[pool] @ model.encode(question, normalize_embeddings=True)
ranked = sorted(zip(scores, pool), reverse=True)[:k]
return [(float(s), DOCS[i]) for s, i in ranked if s >= threshold]
def answer(question, role):
hits = retrieve(question, role)
print(f"[{role}] {question}")
if not hits: # 3. Abstain when nothing relevant is found
print(" I couldn't find that in the documents you can access. Please contact the school office.\n")
return
for score, d in hits: # 4. Cite each source with its title and date
print(f" {d['text']} [{d['title']}, {d['date']}] (score {score:.2f})")
print()
answer("How much is the lab fee, and what happens if I pay late?", "parent") # needs two documents
answer("When are teachers paid?", "parent") # exists, but not for parents
answer("When are teachers paid?", "staff")
answer("Which families got fee waivers?", "parent")
answer("Is there a swimming pool?", "parent") # not in any document[parent] How much is the lab fee, and what happens if I pay late?
The science lab fee is $45 a year and is due by September 30. [Fee Schedule 2026-27, 2026-07-01] (score 0.71)
A late fee of $10 is added when a payment is more than 14 days overdue. [Payment Policy 2026-27, 2026-07-01] (score 0.51)
[parent] When are teachers paid?
I couldn't find that in the documents you can access. Please contact the school office.
[staff] When are teachers paid?
Teachers are paid on the last working day of each month. [Staff Handbook, 2026-07-01] (score 0.85)
[parent] Which families got fee waivers?
I couldn't find that in the documents you can access. Please contact the school office.
[parent] Is there a swimming pool?
I couldn't find that in the documents you can access. Please contact the school office.Explanation:
- Two documents answer the first question: the lab fee and the late fee, each cited with its title and date.
- Freshness: the 2025-26 schedule said $40. The pipeline keeps only the latest version, so parents see $45. An outdated document is one of the most common causes of confidently wrong RAG answers.
- Access control: the staff handbook is retrieved for staff but not for a parent, and the confidential waiver list never reaches a parent's search at all. The filter runs before ranking, so nothing private can leak into the prompt.
- Abstaining: the swimming pool question matches nothing above 0.35, so the system says it couldn't find it instead of inventing an answer.
Example: Diagnosing Failures by Stage
When a RAG system gets something wrong, the fix depends on where it went wrong. This program labels each of Campus Helper's 50 evaluation cases by stage.
import json
from collections import Counter
import numpy as np
from sentence_transformers import SentenceTransformer
texts = [item["text"] for item in json.load(open("faq.json"))]
cases = json.load(open("eval_set.json"))
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode(texts, normalize_embeddings=True)
def diagnose(case, threshold=0.35):
"""Label each case by the stage of the pipeline where it went wrong, or 'correct'."""
scores = vectors @ model.encode(case["question"], normalize_embeddings=True)
order = list(np.argsort(scores)[::-1])
top = order[0]
if case["must_contain"] is None:
return "correct" if scores[top] < threshold else "answered off-topic question"
relevant = {i for i, t in enumerate(texts) if case["must_contain"] in t}
if scores[top] < threshold:
return "declined, but the answer was in top 3" if relevant & set(order[:3]) else "declined: retrieval miss"
if top in relevant:
return "correct"
return "wrong passage ranked first (right one in top 3)" if relevant & set(order[:3]) else "retrieval miss"
stages = Counter()
examples = {}
for case in cases:
label = diagnose(case)
stages[label] += 1
if label != "correct":
examples.setdefault(label, case["question"])
for label, n in stages.most_common():
print(f"{n:3} {label}")
print("\nOne example of each failure:")
for label, q in examples.items():
print(f" {label}: {q!r}") 44 correct
2 wrong passage ranked first (right one in top 3)
2 declined, but the answer was in top 3
1 retrieval miss
1 answered off-topic question
One example of each failure:
wrong passage ranked first (right one in top 3): "We can't afford the fees. Is there help?"
declined, but the answer was in top 3: 'When will we hear if my son got in?'
retrieval miss: 'Can my daughter start in the middle of the year?'
answered off-topic question: "What is the school's policy on pets?"Explanation:
| Stage | Cases | Typical fix |
|---|---|---|
| Correct | 44 | |
| Wrong passage ranked first (right one in top 3) | 2 | A reranker; see "Hybrid Search and Reranking" |
| Declined, but the answer was in the top 3 | 2 | Tune the threshold, or rerank before thresholding |
| Retrieval miss | 1 | Better chunks, query rewriting, or a new FAQ entry |
| Answered an off-topic question | 1 | A higher threshold for that topic, or an off-topic check |
Four of the six failures had the right passage in the top 3, so ranking, not retrieval, is the biggest problem here. Without this breakdown, a team might rebuild the whole index when a reranker would do.
More Advanced Patterns
| Pattern | When it helps | Watch out for |
|---|---|---|
| Graph RAG | Questions about relationships across many documents ("which policies affect grade 11 transfers?") | Building and updating the graph is costly; plain retrieval is often enough |
| Multimodal RAG | Answers in tables, scanned forms, images or audio transcripts | Parsing errors (OCR, transcription) become retrieval errors; see "Multimodal Models" |
| Agentic RAG | Multi-step questions where the next search depends on the last result | More steps, more cost, more chances to go wrong; set limits |
| Query rewriting | Short or vague questions | Rewrites can drift from what the user meant |
Common Mistakes
Filtering permissions after retrieval. Private text may already be in the prompt; filter first.
Indexing every version of a document. Old versions compete with new ones; keep the latest.
Fixing the wrong stage. Diagnose first: retrieval, ranking, threshold or generation.
No abstain path. Without one, the model fills gaps with guesses.
Interview Corner
How do you enforce access control in a RAG system?
Attach permissions to every document or chunk, and filter by the user's permissions at retrieval time, before ranking, so unauthorized text never reaches the prompt. Test it with cross-user queries.
How do you debug a RAG system that gives wrong answers?
Label failures by stage on an evaluation set: was the right passage parsed, retrieved, ranked first, above the threshold, and used correctly in the answer? Then fix the stage with the most failures.
Practice
Exercise: a deleted document. Add a field "deleted": True to the 2025-26 fee schedule and make retrieve skip deleted documents. Then remove the 2026-27 schedule as well: what does a parent get for the lab fee question now?
Check your understanding:
- Why must the permission filter run before ranking?
- How did the pipeline avoid the old $40 lab fee?
- What did the failure analysis suggest fixing first, and why?
Key Takeaways
Quick reference
| Need | Practice |
|---|---|
| Access control | Filter by the user's permissions before ranking |
| Freshness | Keep the latest version; remove deleted documents |
| Citations | Title and date for every fact |
| Abstain | Decline below a score threshold |
| Debug | Label failures by stage on an evaluation set |
Was this tutorial helpful?