Advanced RAG Patterns

Updated · 10 min read
hardPython 3.13airagaccess-controlcitationsretrievalfailure-analysis

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

PatternDescription
Access control at retrievalIt is used to filter documents by the user's permissions before ranking, so private text never reaches the model
Freshness and versionsKeep the latest version of each document; remove deleted ones from the index
Multi-document answersIt is used to retrieve the top few passages, so answers can combine sources
CitationsName the source and date of every fact
AbstainingIt is used to decline when no passage scores above a threshold
Query rewritingRephrase or expand the question, or ask several versions, before searching
Parent-child retrievalIt is used to search small chunks but give the model the larger section around them
Failure analysisLabel 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.

Filter first, keep it fresh, cite everything, decline when unsure
Python
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
Output
[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.

Python
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}")
Output
 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:

StageCasesTypical fix
Correct44
Wrong passage ranked first (right one in top 3)2A reranker; see "Hybrid Search and Reranking"
Declined, but the answer was in the top 32Tune the threshold, or rerank before thresholding
Retrieval miss1Better chunks, query rewriting, or a new FAQ entry
Answered an off-topic question1A 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

PatternWhen it helpsWatch out for
Graph RAGQuestions about relationships across many documents ("which policies affect grade 11 transfers?")Building and updating the graph is costly; plain retrieval is often enough
Multimodal RAGAnswers in tables, scanned forms, images or audio transcriptsParsing errors (OCR, transcription) become retrieval errors; see "Multimodal Models"
Agentic RAGMulti-step questions where the next search depends on the last resultMore steps, more cost, more chances to go wrong; set limits
Query rewritingShort or vague questionsRewrites 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:

  1. Why must the permission filter run before ranking?
  2. How did the pipeline avoid the old $40 lab fee?
  3. What did the failure analysis suggest fixing first, and why?

Quick check: advanced RAG

4 questions
1What did a parent get when asking when teachers are paid?
2Which lab fee did the parent see?
3How many of Campus Helper's 6 failures had the right passage in the top 3?
4When can Graph RAG help?

Key Takeaways

Quick reference

NeedPractice
Access controlFilter by the user's permissions before ranking
FreshnessKeep the latest version; remove deleted documents
CitationsTitle and date for every fact
AbstainDecline below a score threshold
DebugLabel failures by stage on an evaluation set

Was this tutorial helpful?

Lesson 101 of 186