This prompt is for search engineers and RAG developers who need to identify systematic blind spots in their retrieval pipeline. The core job-to-be-done is analyzing a production trace where both keyword-based retrieval (e.g., BM25) and semantic (dense vector) search failed to surface a relevant document that a human reviewer or downstream evaluation later confirmed should have been retrieved. The ideal user is someone with access to production traces, including the original user query, the final ranked list of retrieved documents, and a ground-truth 'missed' document. You should use this prompt when you suspect your keyword index has vocabulary gaps, synonym blind spots, or morphological mismatches that semantic search alone cannot compensate for.
Prompt
Keyword Retrieval Coverage Gap Detection Prompt

When to Use This Prompt
Define the job-to-be-done, the ideal user, required inputs, and the operational boundaries for the Keyword Retrieval Coverage Gap Detection Prompt.
This prompt requires a specific set of inputs to be effective. You must provide the original [USER_QUERY], the combined [RETRIEVED_DOCUMENT_LIST] from both keyword and semantic paths, and the [MISSED_DOCUMENT] that should have been returned. The prompt is designed to isolate the failure to the keyword retrieval component, so it is critical that the missed document was also absent from the semantic search results. If the document was found by semantic search but not by keyword search, you should use the 'Hybrid Search Weight Tuning Analysis Prompt' instead. Do not use this prompt for real-time query rewriting; it is a diagnostic tool for offline trace analysis and index improvement.
The output is a structured coverage gap report, not a simple score. It will identify the specific tokens or phrases in the query that failed to match the missed document, classify the gap type (e.g., synonym gap, stemming failure, entity name mismatch), and recommend concrete index or query expansion rules. Before acting on the recommendations, validate them against a broader set of historical queries to ensure the proposed expansion doesn't introduce noise. For high-stakes search applications where a missed document has regulatory or safety implications, always have a human reviewer confirm the gap classification before modifying production indexes.
Use Case Fit
Where this prompt works and where it does not. Understand the operational boundaries before deploying it into a production observability pipeline.
Good Fit: Post-Mortem Retrieval Analysis
Use when: you have a production trace where a user query received a low-quality or irrelevant answer, and you need to determine if the root cause was a dual failure in both keyword and semantic retrieval. Guardrail: Run this prompt on traces already flagged by user feedback or low answer-faithfulness scores to avoid analyzing every successful request.
Bad Fit: Real-Time Query Rewriting
Avoid when: you need to rewrite a user's query in real-time before retrieval. This prompt is a forensic analysis tool, not a query expansion module. Guardrail: Route real-time query rewriting to a dedicated expansion prompt. Use this prompt only for offline trace review and index improvement planning.
Required Inputs: Full Trace Payload
What to watch: The prompt requires the original user query, the list of retrieved documents from keyword search, the list from semantic search, and the final generated answer. Missing any component produces an incomplete gap report. Guardrail: Validate the trace payload schema before calling the prompt. If any retrieval source is empty, the prompt should report it as a data gap rather than a coverage gap.
Operational Risk: False Positive Gaps
What to watch: The model may flag a 'coverage gap' when the user query is genuinely unanswerable from the available corpus, not because retrieval failed. Guardrail: Add a pre-check step that classifies whether the query is answerable from the knowledge base. If not, suppress the coverage gap label and classify the trace as 'out-of-domain'.
Operational Risk: Index Churn Without Validation
What to watch: Teams may act on the prompt's index expansion recommendations without validating them against a golden query set, causing regressions in precision. Guardrail: Treat the prompt's output as a hypothesis. Require that any recommended synonyms or document additions be tested against a held-out eval set before merging into production indexes.
Variant: Multi-Language Coverage Gaps
What to watch: Keyword retrieval gaps are often more severe for non-English queries where exact token matching fails due to morphology or transliteration. Guardrail: If your system serves multilingual traffic, run this prompt on traces segmented by language. Compare gap rates across languages to identify where language-specific analyzers or multilingual embeddings are needed.
Copy-Ready Prompt Template
A reusable prompt for analyzing production traces to detect keyword retrieval coverage gaps that semantic search also missed.
The following prompt template is designed to be copied directly into your observability or trace analysis workflow. It accepts a production trace containing the user query, the set of documents retrieved by keyword search, the set retrieved by semantic search, and any relevance judgments or user feedback signals. The prompt instructs the model to identify queries where keyword retrieval failed to surface relevant documents that semantic search also missed, producing a structured coverage gap report with actionable recommendations for index or query expansion.
textYou are a search quality engineer analyzing a production retrieval trace. Your task is to detect keyword retrieval coverage gaps: queries where keyword-based retrieval failed to surface relevant documents, and semantic retrieval also did not recover those documents. ## INPUT - User Query: [USER_QUERY] - Keyword Retrieval Results: [KEYWORD_RESULTS] - Semantic Retrieval Results: [SEMANTIC_RESULTS] - Relevance Judgments (if available): [RELEVANCE_JUDGMENTS] - User Feedback Signal (if available): [USER_FEEDBACK] ## OUTPUT SCHEMA Return a JSON object with the following structure: { "coverage_gap_detected": boolean, "gap_severity": "none" | "low" | "medium" | "high" | "critical", "missing_document_patterns": [ { "pattern_description": string, "example_terms_or_phrases": [string], "why_keyword_missed": string, "why_semantic_missed": string, "estimated_relevance": "low" | "medium" | "high" } ], "affected_query_categories": [string], "recommendations": { "index_expansion": [string], "query_expansion_rules": [string], "synonym_additions": [string], "hybrid_weight_adjustments": string | null, "new_fields_to_index": [string] }, "confidence": number, "evidence_summary": string } ## CONSTRAINTS - Only flag a coverage gap when BOTH keyword and semantic retrieval failed to return a relevant document that should have been retrieved. - If relevance judgments are unavailable, base your assessment on query-document topical alignment and standard information retrieval expectations. - Do not flag gaps where the query is ambiguous and multiple interpretations are reasonable without additional context. - Confidence must reflect the certainty of the gap assessment given available evidence. - Recommendations must be specific and implementable, not generic advice. ## EXAMPLES [EXAMPLES] ## RISK LEVEL [RISK_LEVEL]
To adapt this template, replace each square-bracket placeholder with data from your trace store. [KEYWORD_RESULTS] and [SEMANTIC_RESULTS] should include document IDs, snippets, and relevance scores. [RELEVANCE_JUDGMENTS] can be human labels, click-through data, or explicit feedback. [EXAMPLES] should contain one or two annotated few-shot examples showing a clear coverage gap and a non-gap case to calibrate the model's threshold. [RISK_LEVEL] should be set to "high" if the output drives automatic index changes without human review, or "low" if the report is advisory only. Always validate the output JSON against the schema before ingesting it into your search pipeline or dashboard. For high-risk workflows, route the generated recommendations to a human reviewer before applying index or query expansion changes.
Prompt Variables
Required and optional inputs for the Keyword Retrieval Coverage Gap Detection Prompt. Each variable must be populated from production trace data before the prompt is assembled and sent.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The original user search query that triggered the retrieval pipeline | What are the latency requirements for the new inference API? | Must be a non-empty string. Validate that the query is exactly as logged in the trace, not a sanitized or rewritten version. |
[RETRIEVED_DOCUMENTS] | The full set of documents returned by the hybrid retrieval pipeline, including both keyword and semantic results | [ {"id": "doc_1", "source": "keyword", "content": "...", "score": 0.87}, {"id": "doc_2", "source": "semantic", "content": "...", "score": 0.92} ] | Must be a valid JSON array with at least one document. Each document must have id, source, and content fields. Validate that source is either keyword or semantic. Null or empty array triggers a no-retrieval abort. |
[KEYWORD_QUERY_VARIANT] | The keyword-specific query variant generated by the retrieval system, if any | inference API latency requirements SLA | Can be null if no keyword expansion was performed. If present, must be a non-empty string. Validate that this matches the keyword query logged in the trace. |
[SEMANTIC_QUERY_VARIANT] | The semantic-specific query variant generated by the retrieval system, if any | What are the latency requirements for the new inference API? | Can be null if no semantic expansion was performed. If present, must be a non-empty string. Validate that this matches the semantic query logged in the trace. |
[RETRIEVAL_CONFIG] | The retrieval pipeline configuration active during this trace, including index settings and search parameters | {"keyword_index": "prod_v2", "semantic_index": "prod_v2", "top_k": 20, "hybrid_weight": 0.5} | Must be a valid JSON object. Validate that index names match known production indexes. Missing config triggers a warning but does not block analysis. |
[TRACE_ID] | Unique identifier for the production trace being analyzed | trace_2025-03-15_14-32-07_a1b2c3 | Must be a non-empty string matching the trace ID format used in the observability system. Validate against the trace ID regex pattern. Used for audit trail and report linking. |
[RELEVANCE_THRESHOLD] | Minimum relevance score for a document to be considered potentially useful | 0.65 | Must be a float between 0.0 and 1.0. Default is 0.65 if not specified. Validate that the threshold is appropriate for the retrieval system's score distribution. |
[COVERAGE_GAP_DEFINITION] | Criteria for what constitutes a coverage gap in this analysis context | A query term present in the user query but absent from all retrieved document content, where the term is semantically significant | Must be a non-empty string describing the gap criteria. Validate that the definition is specific enough to produce consistent gap detection across traces. Avoid vague definitions like 'missing stuff'. |
Implementation Harness Notes
How to wire the Keyword Retrieval Coverage Gap Detection prompt into an application or observability pipeline.
This prompt is designed to be integrated into a batch trace analysis pipeline, not a real-time user-facing feature. The primary integration point is a scheduled job or an on-demand diagnostic tool that queries your observability platform's API for production traces where both keyword and semantic retrieval were attempted but the overall RAG pipeline produced a low-confidence or factually incomplete answer. The prompt expects a structured trace payload containing the user query, the keyword retrieval results, the semantic retrieval results, and the final generated answer. Before calling the model, your harness must assemble this payload from your trace store, ensuring that sensitive or personally identifiable information is redacted from the query and document snippets before they are sent to the model.
The implementation should follow a validate → prompt → parse → log → act loop. First, validate the assembled trace payload against a strict schema: the keyword_results and semantic_results arrays must contain at least one document each, and the user_query must be a non-empty string. If validation fails, log the malformed trace and skip it. After a successful model call, parse the JSON output and validate that the coverage_gaps array contains properly structured objects with gap_type, missed_document_snippet, and recommendation fields. Any parsing failure should trigger a retry with a stricter output format instruction. Log every analysis result—including the trace ID, the number of gaps found, and the specific recommendations—to your observability platform for trend analysis. For high-risk domains like healthcare or legal search, route traces with a high number of critical gaps to a human review queue before automatically applying index changes.
For model choice, a model with strong JSON mode support and a large context window is required because the prompt must ingest multiple sets of search results. GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro are suitable. Avoid small or fast models that may struggle to maintain the structured output format when comparing long document lists. If you are processing a high volume of traces, implement cost controls by first filtering traces to only those where the RAG answer's faithfulness score fell below a defined threshold, or where the user provided negative explicit feedback. Do not run this prompt on every successful trace. The output of this prompt—a list of specific terms and document patterns that keyword search missed—should be programmatically fed into your search index configuration: add the recommended synonyms, adjust the keyword boosting weights, or create new index fields as suggested. Close the loop by monitoring whether subsequent coverage gap analyses show a reduction in the same gap categories.
Expected Output Contract
Defines the structure, types, and validation rules for the coverage gap report. Use this contract to parse and validate the model's output before ingestion into downstream dashboards or alerting systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
coverage_gap_report | JSON Object | Top-level object must parse as valid JSON. Schema validation must pass against the expected structure. | |
gap_id | String (UUID v4) | Must match UUID v4 regex pattern. Uniqueness must be verified against the trace batch to prevent duplicate gap entries. | |
query_text | String | Must be a non-empty string. Must exactly match the original user query from the production trace log. Length must be between 1 and 2000 characters. | |
retrieval_method | String (Enum) | Must be one of: 'keyword_only', 'semantic_only', 'hybrid'. Value must be derived from the trace's retrieval pipeline configuration. | |
missed_document_ids | Array of Strings | Must contain at least one document ID. Each ID must match the document ID format from the source index. Array must not contain duplicates. | |
gap_category | String (Enum) | Must be one of: 'vocabulary_mismatch', 'entity_miss', 'acronym_expansion', 'synonym_gap', 'structural_miss', 'other'. If 'other', the gap_description field becomes required. | |
gap_description | String | Required if gap_category is 'other'. Must be a non-empty string between 10 and 500 characters. Must not contain PII or raw user data from the trace. | |
severity | String (Enum) | Must be one of: 'critical', 'high', 'medium', 'low'. Severity must be consistent with the number of missed documents and their relevance scores from the trace. | |
recommended_action | String (Enum) | Must be one of: 'add_synonym', 'expand_query', 'update_index_mapping', 'add_alias', 'manual_review', 'adjust_analyzer'. Action must be actionable by the search engineering team. | |
confidence_score | Number (Float 0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Scores below 0.6 must trigger a human review flag. Precision must be to two decimal places. | |
trace_evidence | JSON Object | Must contain a 'trace_id' string and a 'timestamp' in ISO 8601 format. The trace_id must resolve to a valid production trace in the observability platform. | |
evaluation_flag | Boolean | Must be true if confidence_score is below 0.6 or if gap_category is 'other'. Otherwise must be false. Used to route the report for human review. |
Common Failure Modes
Keyword retrieval coverage gaps often surface as 'silent failures'—the system returns results, but not the right ones. These cards identify what breaks first in coverage gap detection and how to build safeguards into your analysis pipeline.
False Negative Gap Claims
What to watch: The prompt flags a coverage gap where keyword retrieval actually did return relevant documents, but the analyzer missed them due to synonym mismatch or normalization differences. This inflates gap counts and directs engineering effort at non-existent problems. Guardrail: Cross-validate gap claims by re-running the original keyword query against the document store and comparing result sets before accepting a gap classification. Require the prompt to cite specific missing document IDs.
Semantic-Only Bias in Gap Detection
What to watch: The analyzer over-weights semantic similarity signals and declares a gap whenever keyword retrieval didn't match the semantic top results, even when keyword results were actually more precise for the query type. This produces false coverage gap reports for exact-match queries where keyword is the correct retrieval mode. Guardrail: Include query type classification in the analysis—distinguish exact-match, attribute-filter, and entity-lookup queries from broad topical queries. Only flag gaps where keyword retrieval should have matched but didn't.
Trace Sampling Bias
What to watch: Coverage gap analysis runs on a non-representative sample of production traces—only failed sessions, only high-latency requests, or only specific user segments. The resulting gap report overfits to the sample and misses systemic gaps in other traffic. Guardrail: Stratify trace sampling by query category, user segment, session outcome, and time window before running gap detection. Document the sampling methodology in the prompt's input context so the analyzer can flag sample bias.
Index Staleness Confusion
What to watch: The prompt identifies a coverage gap that isn't a retrieval failure but an index freshness problem—documents exist in the source system but haven't been indexed yet. The gap report recommends query expansion when the real fix is reindexing. Guardrail: Require the prompt to check document timestamps and index update logs before classifying a gap as retrieval-related. Add an explicit 'index staleness' category to the gap taxonomy so these cases are routed to the right remediation path.
Overgeneralized Expansion Recommendations
What to watch: The prompt recommends query expansion terms that are too broad, introducing noise that degrades precision for other queries. A gap detected for one query pattern leads to index or query changes that harm overall retrieval quality. Guardrail: Require the prompt to estimate the blast radius of each expansion recommendation—how many other queries would be affected and whether precision would degrade. Include a rollback test: if the expansion were applied, would the original precise queries still return correct top results?
Missing Multi-Language Coverage
What to watch: The gap detection prompt operates only on English queries and documents, missing coverage gaps in other languages where keyword tokenization, stemming, or synonym expansion behaves differently. Multilingual gaps go undetected until user-reported failures accumulate. Guardrail: Extend the prompt to flag the language of each query-document pair and report coverage gaps per language. If multilingual traces aren't available, explicitly state the language coverage limitation in the gap report output schema.
Evaluation Rubric
Use this rubric to test the Keyword Retrieval Coverage Gap Detection Prompt before shipping. Each criterion targets a specific failure mode observed in production trace analysis. Run these checks against a golden set of annotated traces where known coverage gaps exist.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Gap Identification Recall | Prompt identifies all known coverage gaps in the golden trace set where both keyword and semantic retrieval failed to surface relevant documents. | Missed gaps where human annotators confirmed relevant documents existed in the index but were not retrieved by any method. | Run against 20 golden traces with pre-labeled coverage gaps. Require recall >= 0.90. Flag any false negative gap for manual review. |
Gap Identification Precision | Prompt does not flag false coverage gaps where relevant documents were actually retrieved or where no relevant documents exist in the index. | False positive gap reports that claim retrieval failure when documents were present in the retrieved set or when the index genuinely lacks relevant content. | Run against 20 golden traces with known non-gaps. Require precision >= 0.85. Investigate any false positive as a potential prompt hallucination or reasoning error. |
Root-Cause Classification Accuracy | Prompt correctly classifies each gap as keyword-specific failure, semantic-specific failure, or dual failure with the correct contributing factor. | Misclassification of a semantic-only gap as keyword-only, or vice versa. Attribution to wrong root cause such as tokenization when the issue was stop-word filtering. | Compare root-cause labels against expert annotations for 15 traces with known failure modes. Require exact match accuracy >= 0.80. Log mismatches for prompt refinement. |
Query Expansion Recommendation Relevance | Recommended query expansions are syntactically valid, semantically related to the original query, and would plausibly retrieve the missing documents. | Expansion terms that are unrelated, introduce topic drift, or would retrieve irrelevant documents. Recommendations that repeat the original query verbatim without modification. | Have a search engineer review expansion recommendations for 10 gap reports. Require >= 70% of recommendations rated as useful or partially useful. Reject any recommendation that would degrade precision by more than 20%. |
Index Improvement Recommendation Actionability | Index configuration recommendations are specific, technically feasible, and reference concrete index settings or pipeline stages. | Vague recommendations such as improve tokenization without specifying the analyzer change. Recommendations that conflict with known index architecture constraints. | Review by search infrastructure engineer for 10 gap reports. Require >= 80% of recommendations rated as actionable without additional research. Flag any recommendation that would break existing query patterns. |
Evidence Traceability | Every identified gap includes a reference to the specific trace event, query timestamp, or document ID that demonstrates the retrieval failure. | Gap claims without trace references. References that point to trace events that do not exist or do not support the claimed failure. | For each gap in 15 reports, verify that the cited trace reference exists and supports the gap claim. Require 100% traceability. Any untraceable gap is a blocking failure. |
Confidence Calibration | Prompt assigns higher confidence scores to gaps with clear retrieval failure evidence and lower scores to ambiguous cases where index completeness is uncertain. | High confidence scores on gaps where the index may not contain relevant documents. Low confidence on clear retrieval failures with strong trace evidence. | Compare confidence scores against human certainty ratings for 20 gaps. Require Spearman rank correlation >= 0.70. Flag inversions where prompt confidence contradicts evidence strength. |
Output Schema Compliance | Report matches the expected [OUTPUT_SCHEMA] exactly, with all required fields present, correct types, and no extra fields. | Missing required fields such as gap_id or retrieval_method_evaluated. Type errors such as string instead of array for expansion_terms. Hallucinated fields not in schema. | Validate output against JSON Schema for 25 reports. Require 100% structural validity. Any schema violation is a blocking failure that requires retry or repair. |
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 trace and lighter validation. Replace strict JSON schema enforcement with a structured markdown table output to speed up iteration. Focus on one query category at a time.
codeAnalyze this production trace for keyword retrieval coverage gaps. [TRACE_JSON] Output a markdown table with columns: Query, Keyword Results, Semantic Results, Gap Description, Recommended Expansion Terms.
Watch for
- Missing schema checks letting malformed traces through
- Overly broad gap descriptions without specific missing terms
- No baseline comparison against semantic retrieval performance

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