This prompt is for RAG pipeline operators and reliability engineers who need to move from 'retrieval looks bad' to a specific, actionable failure mode. Instead of manually inspecting vector scores or reading through irrelevant passages, this prompt classifies the failure into a specific mode such as query-document mismatch, missing index coverage, stale data, or ambiguous query intent. Use it when a user query produces low-quality retrieval results and you need a structured diagnosis to decide whether to rewrite the query, re-index documents, update the knowledge base, or route to a fallback. The prompt belongs in automated retrieval debugging pipelines, observability dashboards, and pre-generation quality gates.
Prompt
Retrieval Failure Mode Detection Prompt

When to Use This Prompt
Diagnose why retrieval failed by classifying the failure mode, not by manually inspecting vector scores.
The prompt expects a user query and the top-k retrieved passages as input. It outputs a structured classification with a primary failure mode, a confidence score, and a diagnostic evidence snippet that explains why the mode was selected. This is not a replacement for retrieval evaluation benchmarks or human relevance judgment; it is a diagnostic classifier that speeds up root-cause analysis. Wire it into your pipeline after retrieval and before answer generation, or use it offline to triage clusters of bad retrieval traces. For high-stakes applications where a misdiagnosis could route users to the wrong fallback, always pair the classifier output with a human review step or an LLM-as-judge confirmation pass.
Do not use this prompt when you need a fine-grained relevance score for every passage—that is a ranking task, not a failure-mode classification. Do not use it when the retrieval set is empty; the prompt requires at least one retrieved passage to compare against the query. If your system already has structured error codes from the retriever itself, use those signals as additional context fields in the prompt to improve classification accuracy. The next section provides the copy-ready template you can adapt with your own failure taxonomy and output schema.
Use Case Fit
Where the Retrieval Failure Mode Detection Prompt works, where it fails, and what you need before deploying it.
Good Fit: Automated Retrieval Debugging
Use when: You have a RAG pipeline producing poor answers and need to classify why retrieval failed before touching generation. Guardrail: Run this prompt on a sample of low-confidence traces, not every query, to control cost and latency.
Bad Fit: Real-Time User-Facing Guardrails
Avoid when: You need a sub-100ms decision before showing an answer to a user. This prompt performs diagnostic reasoning that adds latency. Guardrail: Use a lightweight binary classifier for pre-generation gating; reserve this prompt for offline or async debugging loops.
Required Inputs
What you need: The original user query, the full set of retrieved passages with their metadata, and any pre-retrieval query rewrites. Guardrail: If passage metadata lacks source timestamps or authority signals, the prompt cannot detect staleness or authority-mismatch failure modes.
Operational Risk: Mode Drift Across Models
What to watch: A failure mode classification that works on GPT-4 may produce different mode labels or miss categories on smaller models. Guardrail: Pin your evaluation to a fixed model version and re-validate the classification taxonomy when you change models.
Operational Risk: Diagnostic Over-Confidence
What to watch: The prompt may assign a specific failure mode with high confidence even when multiple failure modes overlap. Guardrail: Require the output to include a confidence score and an alternative mode when confidence is below a threshold; log ambiguous cases for human review.
Operational Risk: Missing Index Coverage Blind Spot
What to watch: The prompt can only reason about what was retrieved. If the knowledge base is missing entire document sets, the prompt cannot detect that gap. Guardrail: Pair this prompt with periodic knowledge-base coverage audits and missing-entity detection prompts to catch systemic gaps.
Copy-Ready Prompt Template
A copy-paste ready prompt for classifying retrieval failures into specific, diagnosable modes with supporting evidence.
This prompt template is designed to be dropped directly into your retrieval debugging workflow. It forces the model to act as a diagnostic classifier, moving beyond vague 'bad retrieval' assessments to identify the specific failure mode—such as query-document mismatch, stale data, or ambiguous intent. Replace each square-bracket placeholder with data from your production trace before sending it to the model. The output is a structured classification that can be logged, aggregated, and used to trigger automated remediation in your RAG pipeline.
textYou are a retrieval pipeline diagnostician. Your task is to analyze a failed retrieval attempt and classify the failure into a specific mode. Do not provide a generic assessment. You must identify the most likely root cause from the categories below and support your classification with direct evidence from the provided data. ## FAILURE MODE CATEGORIES - **query_document_mismatch**: The query terms do not semantically or lexically match the content in the retrieved documents. - **missing_index_coverage**: The information required to answer the query is not present in the search index at all. - **stale_data**: The retrieved documents contain information that is factually outdated or has been superseded. - **ambiguous_query_intent**: The user's query is too vague, has multiple interpretations, or lacks the specificity needed for precise retrieval. - **retrieval_configuration_error**: The failure is likely due to search parameters (e.g., top_k too low, similarity threshold too strict, incorrect embedding model). - **document_chunking_artifact**: The relevant information is split across chunks, and no single chunk contains the complete context needed. ## INPUT DATA **User Query:** [USER_QUERY] **Retrieved Documents (top_k):** [RETRIEVED_DOCUMENTS] **Search Configuration:** [SEARCH_CONFIG] **Expected Answer (if known):** [EXPECTED_ANSWER] ## OUTPUT SCHEMA You must respond with a valid JSON object conforming to this schema: { "failure_mode": "string (one of the categories above)", "confidence_score": 0.0-1.0, "diagnostic_evidence": { "query_analysis": "string (brief analysis of the query's clarity and specificity)", "document_analysis": "string (summary of what the retrieved documents actually contain)", "gap_explanation": "string (explanation of why the retrieved content fails to meet the query's need)" }, "recommended_action": "string (a specific, actionable step to remediate this failure, e.g., 'rewrite query to include date filter', 're-ingest source X', 'increase top_k to 20')" } ## CONSTRAINTS - If you cannot determine the failure mode with certainty, set the confidence score low and explain what additional information you would need. - Base your analysis strictly on the provided input data. Do not invent facts about the user or the index. - The recommended_action must be specific enough for an engineer to implement without further clarification.
To adapt this prompt for your environment, start by populating the RETRIEVED_DOCUMENTS placeholder with the actual text of the top-k results, not just metadata or IDs. The model needs the content to diagnose mismatches. If your pipeline uses a hybrid search, include the SEARCH_CONFIG as a structured object detailing the vector, keyword, and fusion parameters. For high-stakes applications, wire the output confidence_score into a routing rule: scores below 0.7 should trigger a human review of the diagnostic before any automated remediation is applied. You can also extend the FAILURE MODE CATEGORIES list with modes specific to your domain, such as access_control_filter_error or multilingual_mismatch.
Prompt Variables
Required inputs for the Retrieval Failure Mode Detection Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The original user question or search query that triggered retrieval | What is the Q3 revenue for the enterprise segment? | Must be a non-empty string. Check for leading/trailing whitespace. Reject if length exceeds model context window minus prompt overhead. |
[RETRIEVED_DOCUMENTS] | The set of documents or passages returned by the retrieval pipeline for the query | [{"doc_id": "doc_42", "content": "Enterprise revenue reached $12M in Q3...", "score": 0.87}] | Must be a valid JSON array. Each object requires doc_id and content fields. Empty array is allowed and should trigger a NO_DOCUMENTS_RETRIEVED failure mode. |
[RETRIEVAL_METADATA] | Operational metadata about the retrieval call including index name, timestamp, and retrieval method | {"index": "finance_v3", "timestamp": "2025-01-15T10:30:00Z", "method": "hybrid", "top_k": 10} | Must be a valid JSON object. timestamp must parse as ISO 8601. method should be one of the known retrieval strategies in your pipeline. |
[EXPECTED_DOCUMENT_TYPES] | The document types or sources expected to contain the answer, used to detect index coverage gaps | ["quarterly_financial_report", "earnings_transcript", "investor_presentation"] | Must be a JSON array of strings. Use a controlled vocabulary matching your knowledge base taxonomy. Empty array means no type expectations are specified. |
[QUERY_INTENT_CLASSIFICATION] | Pre-classified intent of the user query from an upstream router or classifier | {"intent": "financial_metric_lookup", "confidence": 0.94} | Must be a valid JSON object with intent and confidence fields. confidence must be a float between 0.0 and 1.0. If no upstream classifier exists, set to null. |
[INDEX_SCHEMA] | Description of the search index schema including available fields, filters, and date ranges | {"fields": ["content", "doc_type", "date", "entities"], "date_range": {"earliest": "2020-01-01", "latest": "2025-01-14"}} | Must be a valid JSON object. date_range.earliest and date_range.latest must parse as dates. Use to detect stale data and missing index coverage failure modes. |
[FAILURE_MODE_CATALOG] | The list of known retrieval failure modes the prompt should classify against | ["QUERY_DOCUMENT_MISMATCH", "MISSING_INDEX_COVERAGE", "STALE_DATA", "AMBIGUOUS_QUERY", "LOW_QUALITY_CHUNKS", "NO_DOCUMENTS_RETRIEVED"] | Must be a JSON array of strings. Each value must match a defined failure mode in your observability taxonomy. Customize per deployment but keep the catalog stable for consistent classification. |
Implementation Harness Notes
How to wire the Retrieval Failure Mode Detection Prompt into a production RAG pipeline for automated debugging and monitoring.
This prompt is designed to be called as a post-retrieval diagnostic step, not as a user-facing response generator. Wire it into your RAG pipeline immediately after the retrieval step and before answer generation. The harness should take the original user query, the list of retrieved document chunks with their metadata, and any available retrieval scores as inputs. The prompt's structured failure mode classification should be logged, metered, and used to trigger automated remediation workflows such as re-writing the query, expanding the index, or flagging stale documents for re-indexing.
Implement a strict JSON schema validator on the model's output before the classification enters your observability pipeline. The expected output shape includes a failure_mode enum, a confidence float, and a diagnostic_evidence array of strings. If the model returns malformed JSON, a missing required field, or an unrecognized failure mode, retry once with a repair prompt that includes the raw output and the schema. If the retry also fails, log the raw output and emit an unknown_failure event to your monitoring system. For high-throughput systems, consider using a cheaper, faster model for this classification step (such as a fine-tuned classifier or a smaller LLM) and reserve a more capable model for the answer generation stage.
Integrate the failure mode classification into your existing metrics dashboards. Track the distribution of failure modes over time to detect regressions in retrieval quality after index updates or query pattern shifts. Set alerts on spikes in query_document_mismatch or stale_data modes. For missing_index_coverage failures, automatically append the query to a knowledge gap log that feeds your content acquisition or indexing backlog. For ambiguous_query_intent failures, route the query to a clarification module that asks the user a disambiguating question before re-running retrieval. Always log the full diagnostic payload alongside the trace ID so that on-call engineers can replay and debug specific failures without reproducing the entire session.
Common Failure Modes
Retrieval failure mode detection is only as reliable as the diagnostic signals it uses. These are the most common ways the prompt breaks in production and how to guard against them.
Vague Failure Classification
What to watch: The prompt returns generic labels like 'retrieval issue' or 'bad results' instead of specific, actionable failure modes. This happens when the output schema lacks a constrained taxonomy. Guardrail: Provide a strict, closed-set enum of failure modes (e.g., query_document_mismatch, missing_index_coverage, stale_data, ambiguous_query_intent) and require the model to select exactly one.
Missing Diagnostic Evidence
What to watch: The model asserts a failure mode without citing which retrieved passages, query terms, or metadata led to that conclusion. This makes the classification unverifiable and unactionable. Guardrail: Require the output to include a diagnostic_evidence field that quotes specific passages, query segments, or metadata fields that support the classification.
Confidence Without Calibration
What to watch: The prompt produces a failure mode classification with high confidence even when the signals are ambiguous, leading operators to trust a wrong diagnosis. Guardrail: Add a confidence_score field (0.0–1.0) and a confidence_rationale that explains what evidence is strong or weak. Calibrate against human-labeled failure cases.
Query-Only Diagnosis
What to watch: The prompt classifies the failure based only on the query without examining the retrieved documents, missing cases where the query is well-formed but the index is stale or incomplete. Guardrail: Require both [QUERY] and [RETRIEVED_PASSAGES] as inputs. Include a check that the model references specific passages in its diagnostic evidence.
Overlooking Temporal Staleness
What to watch: The prompt correctly identifies a mismatch but fails to detect that the root cause is stale data rather than a query formulation problem. This leads to the wrong remediation. Guardrail: Include stale_data as a distinct failure mode in the taxonomy and require the model to check document timestamps or content freshness signals when available.
Single-Mode Blindness
What to watch: The prompt returns only one failure mode when multiple issues are present (e.g., both ambiguous query and missing index coverage), hiding the full diagnostic picture. Guardrail: Allow an optional secondary_failure_modes array and instruct the model to list contributing factors even when a primary mode is identified.
Evaluation Rubric
Criteria for evaluating the Retrieval Failure Mode Detection Prompt's output quality before deployment. Use these rubrics to build automated eval harnesses, calibrate LLM-as-judge checks, and set pass/fail gates.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Failure Mode Classification Accuracy | Predicted failure mode matches the ground-truth label injected into the test case at least 90% of the time across a golden dataset of 50+ retrieval failures. | Output misclassifies a known query-document mismatch as 'missing index coverage' or produces a generic 'other' category for a clear, diagnosable failure. | Run against a curated test set with known injected failure modes. Measure exact-match accuracy and macro-F1 across all defined failure classes. |
Diagnostic Evidence Grounding | Every failure mode classification is accompanied by at least one specific, quoted span from the query, retrieved passages, or metadata that supports the diagnosis. | Output provides only a high-level label with no cited evidence, or the cited evidence contradicts the stated failure mode. | Parse the output for evidence fields. Validate that each evidence string is a substring match in the input query or retrieved passages. Flag empty or hallucinated evidence. |
Failure Mode Granularity | Output selects from the predefined failure mode taxonomy without inventing new categories. If the failure does not fit, it uses the 'unclassified' label with a structured note. | Output invents a novel failure mode not present in the taxonomy, or collapses two distinct failures into a vague single label. | Check the predicted label against an allowed enum list. If the label is not in the set, flag it. For 'unclassified' usage, verify the note field is populated and non-generic. |
Confidence Calibration | The confidence score correlates with actual classification correctness. High-confidence predictions are correct at least 95% of the time; low-confidence predictions are correct no more than 60% of the time. | The model assigns high confidence (above 0.9) to incorrect classifications, or low confidence (below 0.5) to correct ones, indicating miscalibration. | Bucket predictions by confidence decile. Plot observed accuracy per bucket. Expected calibration error (ECE) should be below 0.1 on the test set. |
Structured Output Schema Compliance | Output is valid JSON matching the defined schema with all required fields present and correctly typed. | Output is missing required fields, contains extra untyped fields, or uses string types where numbers or arrays are expected. | Validate output against the JSON Schema using a standard validator. Reject any response that fails schema parsing. Measure schema compliance rate across 100+ test runs. |
Ambiguous Query Handling | When the query intent is ambiguous, the output includes an 'ambiguous_query' failure mode with at least two plausible interpretations listed. | Output confidently assigns a specific failure mode to an ambiguous query without acknowledging the ambiguity, or fails to list alternative interpretations. | Use a test set of deliberately ambiguous queries. Check that the output contains the 'ambiguous_query' label and that the interpretations array has at least two entries. |
Stale Data Detection | When retrieved passages contain temporal markers indicating outdated information relative to the query's time context, the output correctly flags 'stale_data'. | Output misses a clear temporal mismatch, such as a query asking for 2024 data when all retrieved passages are dated 2022. | Construct test cases with known temporal mismatches. Verify that 'stale_data' is predicted and that the evidence field cites the conflicting timestamps. |
Latency Budget Compliance | End-to-end prompt execution completes within the defined latency budget for the retrieval debugging pipeline. | Prompt execution exceeds the latency budget by more than 20%, causing downstream pipeline delays or timeouts. | Measure wall-clock time from prompt submission to parsed output across 100 runs. Calculate p50, p95, and p99 latency. Flag if p95 exceeds the budget. |
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
Start with the base prompt and a small set of known failure cases. Use a single model call without schema enforcement. Focus on getting the failure mode taxonomy right for your retrieval stack.
Simplify the output to a single failure_mode field and a free-text diagnostic_evidence string. Skip structured severity scoring and confidence calibration until the taxonomy stabilizes.
Watch for
- Overly broad failure mode categories that collapse distinct problems into one bucket
- The model inventing failure modes not present in the retrieval trace
- Inconsistent mode labels across runs that break downstream dashboards

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