This playbook is designed for search engineers, RAG developers, and AI reliability engineers who are investigating a specific production failure. The core job-to-be-done is to move from a symptom—an eval failure—to a structured diagnosis of the retrieval pipeline. You should use this prompt when you have access to a complete production trace, including the original user query, the final list of retrieved documents with their ranking scores, the embedding model metadata, and the specific eval rubric that the response failed. The ideal user is someone who can query their observability platform, extract these trace segments, and format them as structured inputs for the prompt.
Prompt
Retrieval Gap Root-Cause for Eval Failure Prompt

When to Use This Prompt
Use this prompt to isolate the root cause of a retrieval gap when a RAG response fails an automated evaluation.
The prompt works by systematically comparing the evidence required for a passing eval against the evidence that was actually retrieved. It isolates the failure to one or more specific stages: query formulation (was the search query a poor representation of user intent?), embedding mismatch (did the query and documents live in different semantic spaces?), index staleness (was the correct information not yet indexed?), ranking cutoff (was the relevant document retrieved but ranked below the top-K threshold?), or filter misconfiguration (did a metadata filter incorrectly exclude the right documents?). For example, if an eval requires a specific regulatory clause to be cited and the trace shows the clause exists in the index but was ranked 15th with a top-K of 10, the prompt will flag a ranking cutoff issue rather than an index staleness issue.
Do not use this prompt when the eval failure is clearly caused by generation hallucination, tool-call errors, or prompt instruction violations without retrieval involvement. If the model had the correct documents in its context window but still produced an incorrect or unsupported answer, the root cause is in the generation layer, not the retrieval layer. In such cases, you should use the sibling playbooks for hallucination spot-checking or instruction leakage analysis. After running this diagnosis, the next step is to take the structured output—which includes a root-cause category, affected documents, and a confidence score—and feed it into your retrieval improvement workflow, whether that means tuning the embedding model, adjusting the ranker, or updating the query rewriter.
Use Case Fit
Where this retrieval gap diagnosis prompt delivers reliable root-cause analysis and where it falls short. Use these cards to decide if this prompt fits your investigation before you run it.
Good Fit: Trace Has Retrieval Step Visibility
Use when: your production traces capture the query sent to retrieval, the document IDs or chunks returned, their ranking scores, and the final context window contents. Guardrail: verify that your observability pipeline logs retrieval metadata before invoking this prompt. Without step-level retrieval traces, the diagnosis will be speculative.
Bad Fit: Eval Failure Is a Generation-Only Problem
Avoid when: the eval failure is caused by hallucination, tone, or formatting in the generation step despite correct retrieved evidence being present in the context window. Guardrail: run a context-window-to-output fidelity check first. If the model had the right evidence but misused it, the root cause is in generation or instruction-following, not retrieval.
Required Input: Eval Rubric with Evidence Expectations
Risk: without knowing what evidence the eval rubric required for a passing score, you cannot determine whether retrieval failed to find it or the model failed to use it. Guardrail: always pair this prompt with the specific eval dimension that failed and the evidence that dimension expected. Vague rubrics produce vague diagnoses.
Required Input: Index State at Request Time
Risk: diagnosing a retrieval gap without knowing what documents existed in the index at request time leads to false conclusions about missing documents. Guardrail: capture or reconstruct the index state snapshot (document IDs, metadata, ingestion timestamps) for the time window of the failing request. If you cannot, flag the diagnosis as time-bound and potentially incomplete.
Operational Risk: Embedding Drift Between Query and Index
Risk: the retrieval gap may be caused by embedding model version drift, where the query embedding and document embeddings were produced by different models or configurations. This prompt can detect the symptom but not the model version mismatch. Guardrail: include embedding model version metadata in your traces. If missing, add a manual verification step before acting on the diagnosis.
Operational Risk: Ranking Override Masks Retrieval Quality
Risk: a re-ranker or post-retrieval filter may have discarded relevant documents that the initial retrieval correctly returned. The prompt may blame retrieval when ranking is the true culprit. Guardrail: request separate trace segments for initial retrieval results and post-ranking context window contents. Compare both before concluding retrieval failed.
Copy-Ready Prompt Template
Paste this prompt into your investigation workflow. Replace square-bracket placeholders with trace data from the failed eval session.
This prompt template is designed to be copied directly into your investigation environment. It forces a structured comparison between the query intent, the retrieval pipeline's actual behavior, and the evidence required to pass the failed evaluation. Before using it, gather the failed eval's scorecard, the full trace from the production session (including embedding vectors, retrieval scores, and ranking metadata), and the source documents or index snapshot from the time of the request. The prompt assumes you have access to structured trace data—if your observability platform only captures final outputs, you will need to enrich your tracing before this prompt can produce a reliable diagnosis.
textYou are a retrieval quality investigator analyzing a production RAG session that failed an automated evaluation. Your task is to identify the root cause of the retrieval gap that led to the eval failure. ## INPUT DATA ### Failed Eval Session - **Eval Rubric:** [EVAL_RUBRIC_DESCRIPTION] - **Failed Dimension(s):** [FAILED_EVAL_DIMENSIONS] - **Eval Score:** [EVAL_SCORE] / [MAX_SCORE] - **Eval Judge's Explanation:** [EVAL_JUDGE_EXPLANATION] ### User Query
[USER_QUERY]
code### Retrieval Pipeline Trace - **Query Rewriting Applied:** [REWRITTEN_QUERIES] - **Embedding Model:** [EMBEDDING_MODEL_NAME] - **Index/Collection:** [INDEX_NAME] - **Retrieval Method:** [RETRIEVAL_METHOD] - **Top-K Requested:** [TOP_K] - **Retrieved Documents (with scores and ranks):** ```json [RETRIEVED_DOCUMENTS_ARRAY]
- Reranking Applied: [RERANKING_DETAILS]
- Final Context Window Contents (truncated to what the model saw):
code[CONTEXT_WINDOW_CONTENTS]
Generated Output
code[GENERATED_OUTPUT]
Expected Evidence for Passing Eval
- Required Facts or Citations: [REQUIRED_EVIDENCE_LIST]
- Source Documents That Should Have Been Retrieved: [EXPECTED_SOURCE_DOCUMENTS]
INVESTIGATION INSTRUCTIONS
-
Reconstruct the retrieval intent: What information did the user query actually need to produce a passing answer? Compare this against the rewritten queries actually sent to the retriever.
-
Audit the retrieval results: For each required piece of evidence, determine:
- Was it present in the index at request time?
- If present, what was its retrieval rank and score?
- If absent, is this an indexing gap (document missing from index) or a retrieval gap (document present but not surfaced)?
-
Diagnose the gap mechanism. Classify the root cause into one or more of:
- Query formulation failure: The rewritten queries did not capture the semantic or lexical intent needed to surface the evidence.
- Embedding mismatch: The query embedding and document embeddings are not aligned for this type of content (e.g., domain-specific terminology, code, or structured data).
- Ranking failure: The evidence was retrieved but ranked below the top-K cutoff or dropped during reranking.
- Context window truncation: The evidence was retrieved and ranked high enough, but was truncated from the final context window due to token limits.
- Index staleness: The required evidence was added to the source after the last index update.
- Metadata filter error: A metadata filter excluded the relevant documents unintentionally.
-
Quantify the gap: For each missing piece of evidence, state its retrieval rank (if retrieved), its relevance score, and the score threshold of the lowest-ranked document that made it into the context window.
-
Assess downstream impact: Explain how each retrieval gap directly caused the specific eval dimension to fail. Connect the missing evidence to the eval judge's explanation.
OUTPUT FORMAT
Return a JSON object with this schema:
json{ "retrieval_intent_summary": "string", "query_formulation_analysis": { "original_query": "string", "rewritten_queries": ["string"], "gap_assessment": "string", "suggested_query_fix": "string or null" }, "evidence_audit": [ { "required_evidence": "string", "present_in_index": true, "retrieval_rank": 12, "retrieval_score": 0.67, "made_it_to_context_window": false, "failure_category": "ranking_failure", "explanation": "string" } ], "root_cause_classification": { "primary_cause": "ranking_failure", "contributing_causes": ["context_window_truncation"], "confidence": "high", "evidence_summary": "string" }, "eval_failure_linkage": { "failed_dimension": "string", "causal_chain": "string", "severity": "critical" }, "remediation_recommendations": [ { "action": "string", "target_component": "string", "expected_impact": "string", "effort_estimate": "low" } ] }
CONSTRAINTS
- Do not speculate about index contents you cannot see. If the trace does not include full index state, flag this as a limitation.
- Distinguish clearly between "evidence was not in the index" and "evidence was in the index but not retrieved."
- If the eval failure is not actually caused by a retrieval gap, state this explicitly and suggest alternative root causes.
- Cite specific retrieval ranks, scores, and token positions from the trace data.
Adapt this template by replacing each square-bracket placeholder with actual trace data. The [RETRIEVED_DOCUMENTS_ARRAY] placeholder expects a JSON array of objects containing at minimum doc_id, content_snippet, retrieval_score, and rank. If your tracing system captures embedding vectors, include them in the [EMBEDDING_MODEL_NAME] context but do not paste raw vectors into the prompt—they consume tokens without adding reasoning value. The [EXPECTED_SOURCE_DOCUMENTS] field is critical: you must manually identify which documents or facts were needed to pass the eval. If you cannot determine this, run the eval rubric against a known-good answer first to extract the required evidence set. For high-stakes investigations where the remediation will change production retrieval behavior, route the output through a human review step before applying changes to query rewriting, embedding models, or index configuration.
Prompt Variables
Every placeholder required by the Retrieval Gap Root-Cause for Eval Failure Prompt. Wire these variables from your trace store, eval runner, and search index before invoking the prompt.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[FAILED_EVAL_OUTPUT] | The model response that failed the evaluation | The product's Q4 revenue was $12M. | Must be a non-empty string. Validate that the output matches the trace_id and timestamp of the eval failure event. |
[EVAL_RUBRIC_DIMENSION] | The specific eval criterion that failed | faithfulness_to_context | Must match a known dimension in the eval framework. Reject unknown dimensions. Use the exact string from the eval runner configuration. |
[EVAL_FAILURE_REASON] | The evaluator's explanation for the failure | Claim about Q4 revenue not found in retrieved documents. | Must be a non-empty string. If the eval runner provides structured failure codes, include both the code and the human-readable reason. |
[USER_QUERY] | The original user input that triggered the RAG pipeline | What was our Q4 2024 revenue? | Must be a non-empty string. Retrieve from the trace root span. Validate that the query timestamp matches the eval failure trace. |
[RETRIEVED_DOCUMENT_LIST] | The full list of documents or chunks retrieved for this query | ["doc_1: Q3 revenue was $11M...", "doc_2: Annual report summary..."] | Must be a JSON array of document objects with content and metadata. Validate that the list is not empty. If the retrieval step returned zero documents, this is a critical signal. |
[RETRIEVAL_QUERY_VECTOR] | The embedding or query representation used for retrieval | embedding_model: text-embedding-3-small, dimensions: 1536 | Must include the embedding model identifier and generation timestamp. Validate that the model version matches the production configuration at the time of the request. |
[RANKING_DECISIONS] | The ranking scores and ordering logic applied to retrieved documents | doc_1 score: 0.87, doc_2 score: 0.42, top_k: 5 | Must include per-document relevance scores and the top_k cutoff. Validate that the ranking configuration matches the deployed retriever settings. |
[CONTEXT_WINDOW_SNAPSHOT] | The final context assembled and sent to the generator model | System: You are a helpful assistant... Context: doc_1... doc_2... User: What was Q4 revenue? | Must be the exact string sent to the model. Validate that the snapshot timestamp matches the generation step in the trace. If context was truncated, include the truncation boundary marker. |
Implementation Harness Notes
How to wire the Retrieval Gap Root-Cause prompt into an incident response or continuous monitoring pipeline.
This prompt is designed to be triggered automatically when a RAG eval failure is traced to a retrieval gap—specifically, when the faithfulness or grounding score drops below a threshold and the trace shows that the required evidence was absent from the retrieved context. The harness should receive structured trace data as input, not raw logs. You'll need to extract the user query, the final model response, the eval rubric and failing score, the list of retrieved document IDs with their ranks and scores, and the embedding model version from your observability platform before calling this prompt.
Wire the prompt into your incident pipeline as a diagnostic step that runs after eval failure classification but before human triage. The input should be assembled from your trace store (e.g., LangSmith, Arize, or a custom trace database) and passed as a structured JSON object. Validate the input schema before calling the model: confirm that retrieved_documents is non-empty, that eval_rubric contains the failing dimension, and that query and generated_response are present. If any required field is missing, log a schema validation error and escalate to the on-call engineer rather than running the prompt with incomplete data. The output should be parsed as JSON and validated against an expected schema with fields for root_cause_category, evidence_gap_summary, pipeline_stage_identified, and recommended_action. If the model returns malformed JSON, apply a repair prompt or retry once before falling back to human review.
For continuous monitoring, run this prompt on a sampled subset of retrieval-gap eval failures—not every single event—to control cost and latency. Batch the results into a daily diagnostic digest that tracks the most frequent root-cause categories (e.g., query_rewrite_failure, embedding_drift, index_staleness, ranking_cutoff). Use these aggregates to trigger automated alerts when a category exceeds a threshold (e.g., more than 10% of sampled failures attributed to embedding drift within 24 hours). Do not use this prompt for real-time request correction; it is a diagnostic tool for post-hoc root-cause analysis. The recommended actions it produces should feed into your prompt improvement backlog, index refresh cadence, or embedding model migration plan—not into live request rewriting without human approval.
Common Failure Modes
When diagnosing retrieval gaps that caused an eval failure, the model often misattributes the root cause. These are the most common diagnostic errors and how to prevent them.
Blaming the Embedding When the Query Was Poor
What to watch: The model attributes the retrieval gap to a 'semantic mismatch' or 'embedding drift' when the real issue is a poorly formed, ambiguous, or incomplete query generated upstream. Guardrail: Require the prompt to first rule out query formulation errors by comparing the generated query against the user's original intent and the evidence required by the eval rubric before analyzing embeddings.
Ignoring Chunk Boundary and Segmentation Failures
What to watch: The model claims the evidence 'was not in the index' when it was actually present but split across chunk boundaries, making it unretrievable as a coherent unit. Guardrail: Add a step that checks whether the required evidence spans multiple documents or sections and flags segmentation as a potential cause before concluding the data was missing.
Misdiagnosing a Ranking Problem as a Retrieval Problem
What to watch: The model reports that relevant documents were 'not retrieved' when they were actually in the candidate set but ranked below the top-K cutoff. Guardrail: Require the prompt to inspect the full candidate list with relevance scores, not just the final retrieved set, and report the rank position of any missed evidence.
Overlooking Metadata Filter Over-Restriction
What to watch: The model focuses on query-document similarity while ignoring that an overly aggressive metadata filter silently excluded the relevant documents before semantic search ran. Guardrail: Include a step that audits all active filters, permissions, and date ranges applied during retrieval and flags any that would have excluded the ground-truth evidence.
Confusing Index Staleness with Retrieval Logic Failure
What to watch: The model attributes the gap to a retrieval pipeline bug when the index simply hadn't ingested the document at the time of the request. Guardrail: Require the prompt to check the document's ingestion timestamp against the request timestamp and rule out index staleness before diagnosing logic or configuration errors.
Producing a Root-Cause Without Trace Evidence
What to watch: The model confidently asserts a root cause based on plausible reasoning rather than concrete trace data, creating a diagnosis that sounds correct but cannot be verified. Guardrail: Require every root-cause claim to cite a specific trace event, log line, or retrieved-document ID. If no trace evidence supports the claim, the output must flag the diagnosis as speculative.
Evaluation Rubric
Use this rubric to test the diagnosis quality of the Retrieval Gap Root-Cause for Eval Failure Prompt before relying on it for incident response or pipeline fixes. Each criterion targets a specific failure mode in retrieval gap analysis.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Query-to-Gap Traceability | Diagnosis explicitly links the eval failure to a specific query formulation, embedding behavior, or ranking decision | Diagnosis blames retrieval gap without naming which retrieval stage failed | Inject a known bad query into a trace; verify the output names the query as the root cause |
Evidence Completeness | Diagnosis identifies all missing documents that were required for a passing eval, with relevance justification | Diagnosis lists only some missing documents or omits relevance scores for each | Compare the diagnosis list against a pre-annotated set of required documents for the eval |
Index State Attribution | Diagnosis distinguishes between index staleness, missing documents, and chunking failures as distinct causes | Diagnosis conflates index staleness with embedding mismatch or uses generic 'retrieval failure' language | Provide a trace where the index was intentionally stale; check if the diagnosis identifies staleness specifically |
Embedding Behavior Analysis | Diagnosis compares query embedding against document embeddings and flags semantic drift or domain mismatch | Diagnosis ignores embedding similarity scores or fails to mention embedding model behavior | Use a trace with known embedding mismatch; verify the diagnosis references embedding similarity or drift |
Ranking Decision Audit | Diagnosis explains why the retriever ranked irrelevant documents above the needed evidence | Diagnosis only states that relevant documents were not retrieved without analyzing ranking order | Provide a trace where ranking scores are available; check if the diagnosis references rank positions and score thresholds |
Downstream Eval Impact Mapping | Diagnosis maps each retrieval gap to the specific eval dimension it caused to fail | Diagnosis describes the retrieval gap without connecting it to the eval rubric or failure category | Cross-reference the diagnosis against the eval failure dimensions; verify each gap is linked to at least one eval criterion |
Actionable Remediation Signal | Diagnosis recommends at least one concrete retrieval pipeline change | Diagnosis ends with a vague suggestion or no remediation guidance | Check that the output contains a specific action tied to the root cause |
Confidence Calibration | Diagnosis expresses uncertainty when trace evidence is incomplete or ambiguous | Diagnosis asserts a single root cause with high confidence despite missing or conflicting trace data | Provide a trace with intentionally ambiguous retrieval behavior; verify the diagnosis includes uncertainty qualifiers or alternative hypotheses |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single retrieval trace and a lightweight eval rubric. Replace structured trace schemas with a free-text [TRACE_SUMMARY] that includes the query, retrieved doc IDs, and the eval failure reason. Accept a simple pass/fail diagnosis without requiring ranked hypotheses.
Prompt snippet
codeYou are diagnosing a retrieval gap that caused an eval failure. Query: [QUERY] Retrieved documents (IDs and snippets): [RETRIEVED_DOCS] Eval failure reason: [FAILURE_REASON] Identify the most likely retrieval gap and suggest one fix.
Watch for
- Missing ranking metadata makes it hard to distinguish embedding vs. scoring failures
- Without index state, you cannot detect staleness or missing documents
- Single-hypothesis output may miss compound retrieval failures

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us