How to Debug a RAG Pipeline That Returns Wrong Answers
A RAG application can retrieve documents, send them to an LLM, and generate a response successfully, yet still give users incorrect answers.
Imagine an internal support assistant telling an employee that the refund period is 30 days when the actual company policy specifies 14 days.
The required information exists in the knowledge base. The vector database is responding normally, and the LLM API returns a successful response. Nothing appears broken from an infrastructure perspective.
Yet the answer is wrong.
This is one of the challenges of building production RAG applications. A failure can originate in document ingestion, chunking, embeddings, retrieval, context assembly, or LLM generation.
The right way to debug RAG is to trace an incorrect answer through every stage and identify exactly where the information became inaccurate or incomplete.
1. Start by Inspecting the Retrieved Context
The first question should be simple:
Did the LLM actually receive the information needed to answer the question?
Run the same query again and inspect the retrieved chunks before they are sent to the model.
Check which documents were retrieved, their ranking positions, similarity scores, and whether they contain the information required to answer the question.
Also inspect whether metadata filters removed relevant documents or whether the final prompt excluded some retrieved chunks because of token limits.
This immediately separates two major failure types.
- Retrieval failure: The correct information never reaches the LLM.
- Generation failure: The correct information reaches the LLM, but the model produces an incorrect answer.
Changing the prompt will not fix a retriever that consistently selects the wrong documents.
2. Use Symptoms to Find the Likely Failure
Rather than changing multiple components simultaneously, map the observed behaviour to the stage most likely responsible.
| Symptom | Possible cause | What to inspect |
|---|---|---|
| Relevant document never appears | Retrieval or embedding problem | Query vectors, top-K results, filters |
| Correct document appears but misses important details | Poor chunking | Chunk boundaries and source document |
| Results changed after a deployment | Embedding or index mismatch | Model version, index version, ingestion configuration |
| Old information appears | Stale or duplicate documents | Document versions, deletion and update handling |
| Relevant chunks are buried in results | Poor ranking | Similarity scores, hybrid search, reranking |
| Correct chunks are retrieved but ignored | Context assembly or prompt problem | Final prompt, token count, context ordering |
| Answer includes unsupported facts | Generation or grounding failure | Model response, grounding instructions, source evidence |
This is a starting diagnostic guide, not a definitive mapping. Some symptoms can have multiple causes.
3. Check Document Ingestion and Chunking
Sometimes the required information exists in the original document but is missing from the chunks stored in the vector database.
Consider a refund policy:
"Employees can request a refund within 14 days of purchase. Refund requests submitted after this period require manager approval."
If the document is split incorrectly, the refund period might appear in one chunk while the approval condition appears in another.
The retriever may return only part of the policy, leaving the LLM with incomplete information.
Inspect the original document alongside the generated chunks.
Look for headings separated from their content, tables that lost their structure, sentences split across unrelated chunks, and text missing during PDF extraction.
Also check for duplicate or outdated documents. An updated policy may have been indexed alongside an older version, creating contradictory retrieval results.
Try adjusting chunk size and overlap, or use recursive and document-aware splitting when the original document structure matters.
The objective is not to produce larger chunks automatically. It is to preserve enough context for each retrieved passage to answer the intended question.
4. Verify the Embedding Model and Index
Embeddings convert queries and documents into numerical representations used for semantic retrieval.
A mismatch between indexing and query-time configuration can significantly reduce retrieval quality.
For example, suppose your ingestion pipeline uses one embedding model to generate document vectors, but a deployment changes the query embedding model without rebuilding the existing index.
The query and document vectors may now belong to incompatible embedding spaces.
Check:
- Is the same embedding model and version used during indexing and querying?
- Do the vector dimensions match?
- Are normalization and distance metric configurations consistent?
- Did preprocessing or chunking change between deployments?
- Is the application querying the correct index version?
If you change embedding models, regenerate document embeddings and rebuild or migrate the index appropriately.
Also investigate whether the embedding model handles your domain's terminology effectively. A general-purpose model may struggle with specialised technical language, product identifiers, and error codes.
LlamaIndex's RAG failure checklist identifies embedding mismatches, stale indexes, and retrieval configuration changes as common causes of inconsistent results. https://github.com/run-llama/llama_index/blob/main/docs/src/content/docs/framework/optimizing/rag_failure_mode_checklist.md
5. Debug Retrieval and Ranking
Even when documents are indexed correctly and embeddings are consistent, retrieval can still return irrelevant results.
Suppose the knowledge base contains the correct refund policy, but the retriever returns five unrelated support articles.
Investigate the top-K results before changing the LLM.
Adjust top-K: Retrieve more candidates when relevant passages are appearing below the current cutoff. However, more retrieved content can introduce noise.
Add hybrid search: Combine BM25 keyword retrieval with dense vector search when queries contain exact product names, error codes, or technical terminology.
Introduce reranking: Retrieve an initial candidate set and use a reranking model to evaluate and reorder passages against the original query.
Review similarity thresholds: An overly restrictive threshold can discard useful information, while a loose threshold can allow irrelevant passages into the context.
Change one setting at a time and measure whether relevant documents become more consistently retrievable.
6. Inspect Context Assembly and the Final Prompt
Consider a situation where the retriever finds the correct refund policy, but the final answer is still incorrect.
The next step is to inspect the exact prompt sent to the LLM.
The retrieval results might be correct, but the context assembly stage can introduce problems:
- Relevant chunks are removed because of token limits.
- Too many unrelated passages bury important information.
- Conflicting document versions appear together.
- Context is assembled in an unclear order.
- The prompt does not explain how to handle missing or conflicting evidence.
A RAG prompt should explicitly instruct the model to answer using the supplied context, avoid unsupported claims, and acknowledge when the retrieved information is insufficient.
The important detail is to inspect the final assembled context, not just the retriever's original output.
7. Follow One Incorrect Answer Through the Entire Pipeline
Consider the refund example from earlier.
An employee asks:
"When will I receive my refund?"
The correct policy specifies 14 days, but the RAG assistant responds with 30 days.
Instead of immediately modifying the prompt, reproduce the request and trace it through each stage.
Step 1: Inspect the source document.
The original policy clearly states 14 days. The source itself is correct.
Step 2: Inspect the indexed chunks.
The correct passage exists, but an older policy version also remains in the index and mentions 30 days.
This introduces conflicting evidence.
Step 3: Inspect retrieval results.
The older document ranks above the updated policy, so the retriever selects the wrong information.
Step 4: Inspect the final prompt.
The old policy is supplied to the LLM without a clear indication that it has been superseded.
Step 5: Identify the actual fix.
Update the ingestion pipeline to remove or supersede outdated documents, attach document-version metadata, and apply appropriate filters during retrieval.
Finally, replay the original question and verify that the updated policy is retrieved and the answer correctly states 14 days.
In this scenario, changing the embedding model or increasing the prompt instructions would not address the actual problem.
The failure originated in document version management.
This is why tracing a single incorrect answer can be more useful than making several architectural changes based on guesswork.
8. Evaluate the Pipeline Before and After Fixing It
Fixing one incorrect response does not guarantee that the same problem will not affect other queries.
Create a small evaluation dataset containing real user questions, expected answers, and relevant source documents.
Run it whenever you change chunking, embeddings, retrieval settings, prompts, or models.
Evaluate the following dimensions separately:
Retrieval quality
- Recall@K: Measures whether relevant documents appear within the top K retrieved results.
- Precision@K: Measures how many retrieved results in the top K are relevant.
- MRR: Measures how highly the first relevant result appears.
These metrics require relevance labels or known relevant documents for reliable calculation.
Context quality
- Context precision: Measures whether the retrieved passages are relevant rather than unnecessary noise.
- Context recall: Measures whether the retrieved context contains the information needed to answer the question.
Generation quality
- Faithfulness or groundedness: Checks whether the answer is supported by the retrieved context.
- Answer relevance: Checks whether the response actually addresses the user's question.
- Completeness: Checks whether important parts of the expected answer are missing.
Microsoft's RAG evaluation guidance separates retrieval evaluation from final response evaluation, which makes it easier to determine which stage needs improvement. https://learn.microsoft.com/en-us/azure/foundry/concepts/evaluation-evaluators/rag-evaluators
Do not rely on a single overall score. A system can retrieve excellent documents and still generate poor answers.
Also inspect actual traces containing the query, retrieved chunk IDs, ranking scores, index version, final prompt, model configuration, and generated response.
Tools such as LangSmith and MLflow can help capture and inspect these execution traces.
Use automated evaluations for repeatable comparisons, and manually review important failures. LLM-based judges can help assess relevance and groundedness, but their scores should not be treated as unquestionable ground truth.
Conclusion
A RAG pipeline can produce incorrect answers even when its individual components appear to be working.
The problem might begin with document ingestion, continue through chunking and retrieval, or occur when the LLM interprets the supplied context.
The most effective debugging approach is to reproduce the failure, inspect the retrieved evidence, trace the final prompt, and identify the exact stage responsible.
Fix that stage, then run the same evaluation set again to confirm that retrieval and answer quality have improved without introducing new problems.
Don't start by changing the LLM prompt. Start by finding where the pipeline went wrong.



