This prompt is designed for a specific moment in an agentic RAG loop: the system has attempted a reasoning chain, hit a dead end, and identified what type of fact is missing but not where to find it. The ideal user is an AI engineer or CTO who has already built a mechanism to detect reasoning gaps—such as a validator that flags missing premises or a chain-of-thought monitor that detects an unanswerable step. The prompt's job is to translate that detected gap into a precise, targeted retrieval query that can plausibly unblock the chain. It is not a general-purpose query generator and should not be used for initial question decomposition or for generating queries directly from a user's original question without the intermediate reasoning trace.
Prompt
Evidence Gap Filling Prompt for Incomplete Reasoning Chains

When to Use This Prompt
Defines the precise conditions, required system state, and inappropriate use cases for deploying the evidence gap filling prompt in an agentic RAG pipeline.
Concretely, the system must provide three inputs: a partial reasoning chain (the steps completed so far), a natural-language description of the identified gap (what fact or relationship is missing), and the original user question for context. The prompt then produces a structured output containing a single, self-contained sub-question and a keyword-dense retrieval query. For example, if a chain analyzing a company's Q3 performance stalls because the Q2 baseline revenue is unknown, the gap description might be 'missing Q2 revenue figure for comparison,' and the prompt should output a query like "Acme Corp Q2 2024 revenue reported earnings" rather than a vague "Acme Corp financials." The output schema should also include an expected_evidence_type field (e.g., numerical_figure, date_range, entity_relationship) to help downstream retrieval rankers prioritize the right document chunks.
Do not use this prompt when the system cannot articulate a specific gap. If the failure mode is a vague 'I don't know' without a clear missing fact, this prompt will produce an unfocused query that wastes retrieval bandwidth. Similarly, avoid this prompt when the reasoning chain is empty or the user question is a simple lookup—those cases are better served by standard query rewriting prompts. After implementing, validate the output by checking that the generated query contains key entities from the gap description and that the sub-question is answerable from a single document. For high-stakes domains like legal or financial analysis, log the gap description, generated query, and retrieved results for human audit to ensure the self-correction loop isn't drifting off-course.
Use Case Fit
Where the Evidence Gap Filling Prompt works, where it fails, and the operational prerequisites for production use.
Good Fit: Agentic RAG Loops
Use when: your system already has a multi-step retrieval architecture and a known reasoning chain with a specific, identifiable gap. The prompt excels at generating targeted sub-queries for the next retrieval step. Guardrail: Only invoke this prompt after a dedicated gap-detection step has confirmed missing evidence; do not use it as a generic query rewriter.
Bad Fit: Single-Shot Q&A
Avoid when: you are building a single-turn RAG system without an agentic loop. This prompt assumes an incomplete reasoning chain exists, which is not the case in standard retrieve-then-answer architectures. Guardrail: For single-shot systems, use a query rewriting or expansion prompt from the Retrieval pillar instead. Adding this prompt will introduce latency without benefit.
Required Input: Explicit Gap Description
Risk: The prompt fails silently if the input reasoning chain is vague or the gap is described as 'missing information' without specifics. The generated query will be generic and unlikely to fill the real gap. Guardrail: The upstream gap-detection step must output a structured gap object with missing_fact_type and expected_evidence fields before this prompt is called.
Operational Risk: Query Drift
Risk: Over multiple hops, generated sub-queries can drift from the original user intent, retrieving evidence for a tangentially related question. Guardrail: Before executing the generated query, validate its semantic similarity to the original user question and the specific gap. Abort and re-prompt if cosine similarity drops below a defined threshold.
Operational Risk: Infinite Retrieval Loops
Risk: If the gap-filling query retrieves documents that do not contain the answer, the system may detect the same gap again, re-invoke this prompt, and loop indefinitely. Guardrail: Implement a hard limit on the number of gap-filling hops (e.g., max 3). After the limit, force the system to answer with a documented evidence gap or escalate to a human reviewer.
Bad Fit: Ambiguous or Unanswerable Questions
Avoid when: the original question is fundamentally unanswerable from the knowledge base, or the reasoning chain is entirely hallucinated. The prompt will confidently generate a plausible-sounding but useless query. Guardrail: Run an answerability check on the original question before decomposition. If the knowledge base lacks the domain entirely, route to an abstention or clarification workflow instead of the multi-hop pipeline.
Copy-Ready Prompt Template
A copy-ready prompt template for generating a targeted sub-query to fill a specific gap in an incomplete reasoning chain, ready to be wired into an agentic RAG loop.
This prompt template is the core instruction for an agentic step that detects a stalled reasoning process and requests the missing evidence. It is designed to be injected into a reasoning loop when a primary agent identifies a logical gap it cannot resolve with the currently retrieved context. The template forces the model to articulate exactly what is missing and produce a precise, self-contained retrieval query. Use this when your system needs to self-correct and seek new information rather than hallucinating a bridge or prematurely aborting the chain.
markdownYou are an evidence-gap analyst inside a multi-step reasoning system. Your task is to examine an incomplete reasoning chain, identify the specific missing evidence that prevents reaching a conclusion, and generate a precise retrieval query to find that evidence. **Reasoning Chain with Gap:** [REASONING_CHAIN] **Original User Question:** [USER_QUESTION] **Currently Retrieved Context (Insufficient):** [CURRENT_CONTEXT] **Instructions:** 1. **Identify the Gap:** State in one sentence the exact logical or factual link that is missing. What specific piece of information is required to connect the last valid step to the next one? 2. **Define Expected Evidence:** Describe the type of evidence that would fill this gap (e.g., a date, a definition, a causal relationship, a numerical value, a policy statement). 3. **Generate Retrieval Query:** Produce a single, self-contained search query designed to retrieve the missing evidence. The query must be specific, use keywords likely to appear in the target document, and avoid referencing the current conversation context. 4. **Output Format:** Return your response strictly as a JSON object with the following keys: `gap_statement`, `expected_evidence_type`, and `retrieval_query`. **Output Schema:** [OUTPUT_SCHEMA] **Constraints:** - Do not attempt to answer the original question. - Do not guess the missing evidence. Your job is only to formulate the query to find it. - The retrieval query must be a standalone string suitable for a vector or keyword search engine.
To adapt this template, replace the square-bracket placeholders with live data from your application's reasoning engine. [REASONING_CHAIN] should contain the step-by-step logic produced so far, with the last step clearly indicating a dead end. [CURRENT_CONTEXT] is the raw text of the documents already retrieved, which helps the model avoid generating a redundant query. The [OUTPUT_SCHEMA] placeholder should be replaced with your application's strict JSON schema definition for the expected response, including required fields and types. For high-stakes domains, ensure the [OUTPUT_SCHEMA] includes a confidence field and that a human review step is triggered if the gap cannot be clearly articulated. The primary failure mode is generating a query that is too vague or simply restates the original question; validate the output by checking if the retrieval_query contains novel, specific keywords not fully present in the [CURRENT_CONTEXT].
Prompt Variables
Placeholders required by the Evidence Gap Filling Prompt. Each variable must be populated before the prompt is sent to the model. Validation notes describe how to programmatically verify that the input is well-formed and safe.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[REASONING_CHAIN] | The partial reasoning chain with a known gap. Contains the steps completed so far and the point where evidence is missing. | Step 1: The patient was prescribed Lisinopril. Step 2: The patient reported a persistent cough. Step 3: [GAP] Need to establish the causal link. | Check that the string is non-empty and contains a clear gap marker such as '[GAP]' or 'MISSING'. Reject if the chain appears complete or if the gap is ambiguous. |
[GAP_DESCRIPTION] | A natural language description of what information is missing and why it is needed to continue the reasoning chain. | We need evidence that Lisinopril is known to cause a persistent dry cough as a side effect. | Verify that the description is a non-empty string. Check that it specifies both the missing fact and its role in the reasoning chain. Null is not allowed. |
[RETRIEVED_CONTEXT] | The full text of documents or passages already retrieved that are relevant to the reasoning chain. Used to avoid suggesting a query for evidence already in hand. | Document A: Lisinopril is an ACE inhibitor... Document B: Common side effects include dizziness and headache... | Ensure the input is a valid string. If no context has been retrieved yet, pass an empty string. Validate that the context does not already contain the answer to the gap to prevent redundant retrieval. |
[DOMAIN_CONSTRAINTS] | Optional domain-specific rules or a taxonomy that the generated query must respect, such as a medical ontology or legal citation format. | Use MeSH terms for drug side effects. Prefer sources from the last 5 years. | If provided, check that the string is non-empty. If not applicable, pass an empty string. Validate that constraints are parseable instructions, not free-form user input that could contain injection attacks. |
[OUTPUT_SCHEMA] | The required JSON structure for the output, defining the fields for the sub-question, retrieval query, and expected evidence type. | { "sub_question": "string", "retrieval_query": "string", "expected_evidence_type": "string" } | Validate that the schema is a valid JSON string. The schema must include 'sub_question', 'retrieval_query', and 'expected_evidence_type' as required fields. Reject schemas that allow arbitrary additional properties without review. |
[MAX_QUERY_LENGTH] | The maximum number of tokens or characters allowed for the generated retrieval query to ensure compatibility with the search backend. | 256 | Check that the value is a positive integer. If the search backend has a strict character limit, enforce it here. A value of 0 or null should be treated as 'no limit' but logged as a potential risk. |
[FEW_SHOT_EXAMPLES] | Optional examples of valid gap-filling query generation to guide the model's output format and style. | Example 1: Chain: ... Gap: ... Query: ... Expected Evidence: ... | If provided, validate that the examples are a list of objects, each with 'chain', 'gap', 'query', and 'expected_evidence' fields. Check that the examples do not contain the exact gap from the current request to prevent data leakage. An empty list is allowed. |
Implementation Harness Notes
How to wire the Evidence Gap Filling prompt into an agentic RAG application with validation, retries, and logging.
The Evidence Gap Filling prompt is not a standalone generator; it is a control-plane component inside an agentic RAG loop. Its job is to inspect a partial reasoning chain, identify a specific missing fact or logical leap, and produce a targeted sub-question and retrieval query. The application harness must treat this prompt as a decision point: if the gap is fillable, the output query is dispatched to the retrieval system; if the gap is fundamental or the prompt fails validation, the agent should escalate or abstain rather than fabricate an answer. Wire this prompt after a reasoning step produces an incomplete chain and before the next retrieval call.
The harness should enforce a strict output contract. Parse the model response into a typed object with fields: gap_description (string), sub_question (string), retrieval_query (string), expected_evidence_type (string), and is_fillable (boolean). If is_fillable is false or the output fails schema validation, the agent must not proceed with retrieval. Instead, log the gap report and either request human clarification or return a bounded answer with an explicit caveat about the unresolved gap. For high-stakes domains, implement a human review queue that surfaces gap reports where is_fillable is false or expected_evidence_type indicates a policy-sensitive fact. Use a model with strong instruction-following and JSON mode (such as GPT-4o or Claude 3.5 Sonnet with structured outputs enabled) to minimize parsing failures. Set temperature=0 to reduce variability in gap classification.
Build a retry-and-repair layer around this prompt. If the output fails JSON schema validation, retry once with the validation error message appended to the prompt as a repair instruction. If the second attempt also fails, log the raw output, increment a gap_fill_failure metric, and fall back to a safe response path—do not loop indefinitely. Instrument the harness to log every gap-fill attempt: the input reasoning chain, the identified gap, the generated query, the retrieval results that follow, and whether the gap was ultimately resolved. This trace data is essential for debugging multi-hop failures and for evaluating whether the gap-filling prompt is generating queries that actually retrieve useful evidence. Use these logs to build a golden dataset for regression testing the prompt across model updates.
The retrieval system that consumes the output query must be prepared for targeted, evidence-seeking queries rather than broad topic searches. The retrieval_query field should be passed directly to your vector store, keyword index, or hybrid retrieval endpoint. Do not rewrite or expand it unless you have a separate query expansion step with its own validation. After retrieval, the new evidence should be appended to the reasoning chain context, and the agent should re-attempt the reasoning step that produced the gap. This creates a tight feedback loop: reason, detect gap, fill gap, retrieve, reason again. Avoid the common failure mode of treating the gap-filling prompt as a one-shot fix; it works best as part of a bounded iterative loop with a maximum of three gap-fill attempts before the agent concedes and reports what it cannot resolve.
Expected Output Contract
Defines the structure and validation rules for the output generated by the Evidence Gap Filling Prompt. Use this contract to parse and validate the model's response before feeding the generated query into a retrieval system.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
gap_analysis | Object | Must contain 'missing_fact' (string) and 'required_evidence_type' (string). 'missing_fact' must not be empty or a restatement of the known context. | |
gap_analysis.missing_fact | String | Must be a specific, atomic fact that is absent from the provided reasoning chain. Parse check: string length > 10 characters. Must not be a question. | |
gap_analysis.required_evidence_type | String | Must be one of a predefined set of evidence types relevant to the domain (e.g., 'date', 'definition', 'statistic', 'causal_mechanism', 'event_description'). Validate against an allowed enum list. | |
sub_question | String | A self-contained, answerable question whose answer would provide the missing fact. Must end with a question mark. Parse check: string must not be identical to the original user question. | |
retrieval_query | String | A keyword or natural language query optimized for a vector or keyword search engine. Must contain key terms from the 'missing_fact'. Parse check: string length > 3 characters. | |
expected_answer_snippet | String | A brief, hypothetical example of the text that would constitute a valid answer. If null, the field must be explicitly null. Validation: if present, must be a declarative sentence, not a question. | |
confidence | Number | A float between 0.0 and 1.0 representing the model's confidence that filling this gap will advance the reasoning chain. Validation: must be a number, 0.0 <= value <= 1.0. A value below 0.5 should trigger a review or alternative gap search. |
Common Failure Modes
Evidence gap filling fails in predictable ways. Here are the most common failure modes when generating sub-queries to fill reasoning gaps, and how to guard against them in production.
Overly Broad Retrieval Queries
What to watch: The generated query is a restatement of the original complex question instead of a targeted sub-query for the specific missing fact. This floods the retriever with irrelevant chunks. Guardrail: Validate that the output query contains concrete entities, dates, or constraints from the gap description. Reject queries that are substring matches of the original user question.
Hallucinated Gap Filling
What to watch: The model invents a plausible-sounding fact to close the reasoning gap instead of generating a query to retrieve it. The output reads like an answer, not a retrieval request. Guardrail: Use a strict output schema that separates sub_question from expected_evidence_type. Add a validator that rejects outputs containing declarative answers in the query field.
Premature Gap Closure
What to watch: The model declares the gap filled based on weak or indirect evidence, skipping the retrieval step entirely. This is common when the model is overconfident or the gap description is vague. Guardrail: Require the output to include a retrieval_query field that is non-empty and distinct from the gap description. Add a check that the query would return new information, not just re-rank existing context.
Ignoring Temporal or Version Constraints
What to watch: The generated query omits time ranges, document versions, or effective dates that were specified in the gap description. The retriever returns outdated or irrelevant evidence. Guardrail: Extract temporal constraints from the gap description and verify they appear in the output query. If the gap says
Query-Answer Mismatch in Evaluation
What to watch: The generated query is plausible but the expected evidence type doesn't match what the reasoning chain actually needs. The gap asks for a causal mechanism, but the query asks for a definition. Guardrail: Include an expected_evidence_type field in the output schema with a controlled vocabulary (e.g., causal_mechanism, numerical_value, policy_rule, entity_relationship). Validate that the query aligns with the declared type.
Looping on Unfillable Gaps
What to watch: The system repeatedly generates queries for a gap that cannot be filled from the available knowledge base, wasting compute and latency budget. The model never concludes that evidence is missing. Guardrail: Implement a maximum retry count per gap. After N failed retrieval attempts, trigger an abstention path that marks the gap as unfillable and surfaces the limitation to the user or downstream system.
Evaluation Rubric
Criteria for testing whether the generated sub-question and retrieval query would plausibly fill the identified evidence gap. Use this rubric to automate quality gates before shipping the prompt into an agentic RAG loop.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Gap Relevance | Generated sub-question directly addresses the specific missing fact or logical link identified in the [GAP_DESCRIPTION] | Sub-question targets a tangential topic or repeats information already present in the [EXISTING_CHAIN] | LLM-as-judge pairwise comparison: present the gap and both the generated and a distractor sub-question; judge must select the relevant one with confidence >= 0.8 |
Query Specificity | Retrieval query contains concrete entities, dates, or technical terms from the gap context rather than generic phrases | Query is a verbatim restatement of the sub-question or uses only broad category words with no narrowing terms | Keyword overlap check: query must contain at least 2 terms not present in the sub-question string; manual spot-check 20 samples |
Expected Evidence Type Accuracy | The [EXPECTED_EVIDENCE_TYPE] field names a specific document class, data format, or fact category that would logically resolve the gap | Expected evidence type is 'information', 'data', 'document', or another overly generic label | Schema validation: field must match an allowed enum of at least 15 specific types defined in the system prompt; reject generic fallbacks |
Atomicity | Sub-question is answerable from a single retrieval result without requiring further decomposition | Sub-question contains conjunctions, multiple clauses, or implicit nested questions that would require additional hops | Parse check: sub-question must contain zero coordinating conjunctions joining independent clauses; flag if character count > 200 |
Non-Redundancy with Existing Chain | Sub-question asks for evidence not already cited or summarized in the [EXISTING_CHAIN] | Sub-question requests information already present in the chain steps, indicating the model failed to recognize existing coverage | Semantic similarity check: cosine similarity between sub-question embedding and each chain step embedding must be < 0.85 threshold |
Plausible Retrievability | Query is phrased in a way that a standard dense or sparse retriever could match against a real document collection | Query uses rhetorical questions, first-person pronouns, or conversational phrasing unlikely to match indexed text | Retrieval simulation: run query against a held-out test corpus; pass if top-5 results contain at least one document with relevant gap-filling content |
Gap-to-Query Traceability | A human reviewer can trace a clear logical line from the [GAP_DESCRIPTION] through the sub-question to the retrieval query | The connection between the gap and the query is opaque, requiring guesswork to understand why the query was chosen | Human eval on 50 random samples: 2 reviewers independently rate traceability on a 1-3 scale; pass if Cohen's kappa >= 0.7 and mean score >= 2.5 |
Output Format Compliance | Response strictly follows the [OUTPUT_SCHEMA] with all required fields present and no extra commentary | Response includes preamble text, markdown fences, or missing required fields like [RETRIEVAL_QUERY] | Schema validation: parse response as JSON; check required field presence; reject if root keys contain any field not in the schema definition |
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 simple string input for [REASONING_CHAIN] and [KNOWN_GAP_DESCRIPTION]. Skip strict output schema enforcement initially. Focus on whether the generated sub-question and retrieval query are directionally correct.
Watch for
- The model generating a retrieval query that is too broad or restates the original question instead of targeting the specific gap.
- Missing the expected evidence type declaration, which makes downstream retrieval harder to evaluate.
- Overly verbose reasoning before the query, wasting tokens without improving retrieval precision.

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