Velamuvi AIAcademy

Lesson 14 of 16 · Generation and Quality

Common RAG Failures

Troubleshoot RAG: missing content, retrieval misses, lost context, outdated documents, ignored sources, made-up answers and access leaks, with a diagnosis tool.

  • 5 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Recognise the most common ways RAG systems fail
  • Diagnose which stage a wrong answer came from
  • Pick the right fix for each kind of failure
  • Avoid the failures that create security and trust problems

Find the broken stage first

When a RAG answer is wrong, the instinct is to tweak the prompt or change the model. Usually the problem is earlier. Check the stages in order:

  1. Content: is the answer in the knowledge base at all?
  2. Retrieval: did the chunk with the answer reach the prompt?
  3. Generation: given the right chunk, did the model use it correctly?

This program does that triage automatically for three wrong answers:

Try it yourselfPython
import math, re

# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
    "leave":     "leave holiday holidays vacation annual time-off carried",
    "sick":      "sick ill illness unwell doctor self-certify",
    "remote":    "remote home hybrid office hours",
    "expenses":  "expenses expense claim reimbursed receipt receipts meals",
    "equipment": "laptop laptops monitor headset equipment lost stolen",
    "security":  "password passwords 2fa two-factor login phishing security",
    "parental":  "parental maternity paternity baby birth adoption adoptive",
    "training":  "training course courses learning books conferences",
    "travel":    "travel trip trips flight flights train trains journeys",
    "pay":       "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}

def words(text):
    return re.findall(r"[a-z0-9'-]+", text.lower())

def embed(text):
    v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
    length = math.sqrt(sum(x * x for x in v))
    return [x / length for x in v] if length else v

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))       # vectors are unit length

# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
    "Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
    "Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
    "Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
    "Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
    "Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
    "Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
    "Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
    "Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
    "Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}

CHUNKS = [s.rstrip(".") + "." for text in HANDBOOK.values() for s in text.split(". ")]

def retrieve(question, k=3):
    q = embed(question)
    return sorted(CHUNKS, key=lambda c: cosine(q, embed(c)), reverse=True)[:k]

def diagnose(question, answer_phrase, k=3):
    """Where did a wrong answer go wrong? Check each stage in order."""
    holders = [c for c in CHUNKS if answer_phrase.lower() in c.lower()]
    if not holders:
        return "MISSING CONTENT: no chunk contains the answer. Add or fix the document."
    retrieved = retrieve(question, k)
    if not any(c in retrieved for c in holders):
        q = embed(question)
        all_ranked = sorted(CHUNKS, key=lambda c: cosine(q, embed(c)), reverse=True)
        rank = min(all_ranked.index(c) for c in holders) + 1
        return f"RETRIEVAL MISS: the answer is in the chunk ranked {rank}, outside the top {k}."
    return "RETRIEVED: the answer reached the prompt. If the reply is still wrong, fix the prompt or model."

cases = [
    ("Is there a gym at the office?", "gym"),
    ("Who pays for my dinner on a work trip?", "40 euros"),
    ("How long can I self-certify?", "7 days"),
]
for question, phrase in cases:
    print(question)
    print("   ", diagnose(question, phrase))

Three questions, three different fixes: write a missing document, improve retrieval, or look at the prompt and model. Without the triage, all three might have been “fixed” by changing the prompt, which would have helped none of them.

The failure catalogue

SymptomLikely causeFix
“I don't know” for things that are documentedRetrieval miss: different vocabulary, poor chunksHybrid search, query rewriting, better chunking
Answer misses a condition or exceptionChunk cut off its contextOverlap, heading-aware chunks, small-to-big retrieval
Answer quotes an old ruleOutdated documents still indexedDelete stale chunks, filter by version or date
Two answers contradict each otherConflicting documentsFix the sources; prefer the newest or official one via metadata
Wrong numbers from tablesTables flattened during loadingExtract tables separately, one row per sentence
Plausible details that aren't in any sourceModel filling gaps (hallucination)Stricter prompt, exact fallback, citation checks, minimum score
Right chunk retrieved, wrong answerToo many chunks, answer buried in the middleRerank and send fewer, better chunks
User sees another team's documentsMissing access filterFilter by user groups on the server for every query
Answer follows strange instructionsPrompt injection in a documentTreat sources as untrusted; no risky tools; trusted sources only

Common mistakes

Practice exercise

Write the triage rule for a wrong RAG answer: which stage of the pipeline should you fix?

Your solutionPython
def stage(in_knowledge_base, rank, k=5):
    # Return "missing content" if the answer isn't in the knowledge base,
    # "retrieval" if it is there but its rank is None or bigger than k,
    # otherwise "generation".
    return "?"

print(stage(False, None))
print(stage(True, 12))
print(stage(True, None))
print(stage(True, 2))
Knowledge check

The chunk with the right answer is ranked 12th, but only the top 5 chunks go into the prompt. What kind of failure is this?

Summary

  • Diagnose in order: content, then retrieval, then generation.
  • Each failure has a typical fix: write missing content, improve retrieval, or tighten the prompt and context.
  • Outdated or conflicting documents, flattened tables and missing access filters cause many real-world problems.
  • Treat retrieved text as untrusted, and add every failure to your test set.

Next: a project that puts it all together: question answering over a PDF.

Finished reading? Tick it off to track your progress.