This prompt is designed for production Retrieval-Augmented Generation (RAG) systems that execute multi-hop query plans and require automatic, in-process recovery when a retrieval step fails. A 'hop' is considered failed when it returns zero results, results that fall below a configurable relevance threshold, or results that lack the specific entities or facts needed to construct the subsequent query in the chain. The core job-to-be-done is to prevent a full pipeline failure by programmatically repairing the broken segment of the query plan, allowing the system to self-correct without immediately escalating to a human operator or returning a generic 'I don't know' response. The ideal user is an AI engineer or RAG architect embedding this prompt into a retry controller within a larger agentic or pipeline architecture.
Prompt
Multi-Hop Query Plan Repair Prompt After Retrieval Failure

When to Use This Prompt
Defines the production context for deploying a multi-hop query plan repair prompt and clarifies when it should and should not be used.
This prompt must be used inside a strict retry loop with a maximum repair attempt limit (e.g., 2-3 attempts) to prevent infinite loops. It takes the original user question, the full failed query plan, the index of the failed hop, and the retrieved results (if any) as input. It outputs a repaired plan segment with alternative queries or a revised dependency path. This prompt is not a substitute for initial query plan generation; it must be paired with an upstream 'Multi-Hop Query Chain Generation Prompt'. It is also not designed to handle ambiguous or unanswerable user questions; those cases should be triaged and refused by an upstream intent classifier or a 'Query Disambiguation and Ambiguity Resolution Prompt' before a query plan is ever generated. Using this prompt on a fundamentally broken question will result in plausible but incorrect query repairs that silently change the user's intent.
Before integrating this prompt, ensure your retrieval pipeline emits structured failure signals, including the hop index, the query that was executed, the result count, and a relevance score. The repair prompt's effectiveness is directly tied to the quality of this failure context. A common failure mode is the repair prompt generating a query that is semantically similar to the original failed query but does not resolve the underlying dependency gap, leading to a second failure on the same hop. To mitigate this, the harness should validate that the repaired query is structurally different from the failed query (e.g., using a simple lexical overlap check) before execution. Proceed by wiring this prompt into your retry controller and pairing it with a 'Dependency Graph Validation Prompt' to pre-check the repaired plan segment for logical consistency before re-executing the retrieval.
Use Case Fit
Where the Multi-Hop Query Plan Repair Prompt delivers value and where it introduces risk. This prompt is a production recovery tool, not a primary query planner.
Good Fit: Automated RAG Pipelines with Strict Latency Budgets
Use when: A production RAG pipeline has a fixed multi-hop plan, and a specific hop returns zero results or falls below a relevance threshold. Guardrail: Trigger the repair prompt only after a retrieval confidence score drops below a calibrated threshold to avoid unnecessary repair calls on marginal results.
Bad Fit: Replacing Initial Query Planning
Avoid when: You are tempted to use this as the primary query decomposition engine. It is designed for localized repair, not holistic plan generation. Guardrail: Use a dedicated Multi-Hop Query Chain Generation Prompt for the initial plan, and reserve this prompt exclusively for the recovery path.
Required Input: The Failed Hop Context
What to watch: The repair prompt cannot function without the original user question, the specific sub-query that failed, the empty or irrelevant results, and the dependency graph. Guardrail: Implement a strict input schema validator in your application harness that rejects the repair call if any of these four fields are missing or null.
Operational Risk: Silent Intent Drift
What to watch: A repaired query might successfully retrieve documents but answer a slightly different question than the user asked, breaking the chain's logical integrity. Guardrail: After generating a repair, run a semantic similarity check between the original failed sub-query and the repaired query. If the cosine similarity drops below 0.85, flag for human review or discard the repair.
Operational Risk: Infinite Repair Loops
What to watch: A broken retrieval index or a fundamentally unanswerable question can cause the system to generate a repair, fail again, and trigger another repair indefinitely. Guardrail: Set a hard limit of 1-2 repair attempts per hop. After the limit is reached, log the failure, abort the chain, and return a partial answer with a confidence disclaimer to the user.
Good Fit: Complex Reasoning Chains with Bridge Entities
Use when: A multi-hop chain fails because a specific bridge entity wasn't found in the knowledge base. The repair prompt can generate alternative bridge entities or rephrase the query to find the connection. Guardrail: Constrain the repair prompt to only suggest entities present in the previously retrieved context to prevent hallucinating plausible but non-existent bridge entities.
Copy-Ready Prompt Template
A reusable system prompt for repairing a multi-hop query plan when a retrieval step returns empty or irrelevant results.
This prompt template is designed to be inserted into your system prompt or as a user message in a tool-calling loop. It receives the original query plan, the specific hop that failed, the empty or irrelevant results, and any evidence gathered from prior successful hops. The model's job is to generate a repaired segment—alternative queries or a revised dependency path—that recovers the retrieval chain without silently altering the user's original intent. The output contract is a strict JSON schema so that downstream orchestration code can parse the repair and inject it back into the execution plan.
textYou are a retrieval plan repair agent. Your task is to fix a failed hop in a multi-hop query plan. # INPUT - Original User Question: [USER_QUESTION] - Full Query Plan (JSON): [QUERY_PLAN] - Failed Hop ID: [FAILED_HOP_ID] - Failed Query Text: [FAILED_QUERY] - Retrieval Results for Failed Hop: [FAILED_RESULTS] - Evidence from Prior Successful Hops: [PRIOR_EVIDENCE] - Failure Reason (empty_results | irrelevance | other): [FAILURE_REASON] # CONSTRAINTS 1. Do not change the user's original intent or the ultimate question being answered. 2. The repaired hop must produce information that the subsequent dependent hops can use. Preserve the dependency contract. 3. If the failure reason is "empty_results," generate broader, synonym-expanded, or structurally relaxed queries. 4. If the failure reason is "irrelevance," generate queries with tighter entity constraints, explicit date ranges, or domain-specific terminology drawn from prior evidence. 5. You may propose splitting one failed hop into two sequential sub-hops if a single query cannot bridge the gap. 6. You may propose a new bridge entity if the original bridge entity was not found. 7. If no plausible repair exists, set `repairable` to false and provide a clear reason. # OUTPUT SCHEMA Return ONLY valid JSON matching this schema: { "repairable": boolean, "repair_strategy": "broaden" | "tighten" | "split" | "replace_bridge_entity" | "none", "repaired_plan_segment": [ { "hop_id": "string (new or reused)", "query": "string", "target_index": "string (optional)", "expected_output_type": "string", "depends_on": ["hop_id"] } ], "rationale": "string explaining why this repair should resolve the failure", "fallback_escalation": "string (if repairable is false, describe what human or alternative workflow is needed)" }
To adapt this template, replace the square-bracket placeholders with values from your orchestration layer. The QUERY_PLAN should be the full JSON plan object, not a summary, so the model can reason about dependencies. The PRIOR_EVIDENCE field should contain structured outputs from earlier hops—entities, facts, and source spans—not raw document chunks. For tool-calling setups, wrap the output schema in a function definition and set tool_choice to "required" to guarantee structured output. Before deploying, run this prompt against a golden set of known plan failures and validate that repairable is correctly set and that repaired queries do not drift from the original question's intent. In high-stakes domains, route repairable: false responses to a human review queue rather than silently halting the pipeline.
Prompt Variables
Inputs required by the Multi-Hop Query Plan Repair Prompt. Validate types and non-null constraints before sending to the model. Missing or malformed variables will cause the repair to fail silently or produce hallucinated query rewrites.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ORIGINAL_USER_QUESTION] | The user's original question that the multi-hop plan was built to answer. Used to check that repairs don't drift from the original intent. | What was the revenue growth of the company that acquired DataStream Inc. last year? | Required. Non-empty string. Must be the exact original question, not a paraphrase. Intent drift check compares repair output against this. |
[FAILED_QUERY_PLAN] | The full multi-hop query plan that was attempted, including all hops, their dependencies, and which hop failed. Provides context for what went wrong. | {"hops": [{"id": "hop1", "query": "Who acquired DataStream Inc.?", "status": "completed"}, {"id": "hop2", "query": "What was the revenue growth of [acquirer]?", "status": "failed", "error": "empty_result_set"}]} | Required. Valid JSON object. Must include hop IDs, query text, status per hop, and error type for failed hops. Schema validation before prompt assembly. |
[FAILED_HOP_ID] | The specific hop identifier that returned empty or irrelevant results. Tells the repair prompt which part of the plan needs rewriting. | hop2 | Required. Non-empty string. Must match an existing hop ID in [FAILED_QUERY_PLAN]. Cross-reference validation before sending. |
[RETRIEVED_EVIDENCE_FOR_FAILED_HOP] | The actual retrieval results returned for the failed hop, even if empty or low-relevance. Helps the model understand why the hop failed. | [{"doc_id": "doc_42", "score": 0.12, "snippet": "Industry trends show..."}] | Required. Array of result objects. May be empty. Each object must include doc_id, score, and snippet. Null allowed only if the retrieval system returned a hard error with no results. |
[INTERMEDIATE_EVIDENCE_FROM_PRIOR_HOPS] | Evidence extracted from hops that completed successfully before the failure. Contains the entities, facts, or values needed to construct the next query. | {"hop1": {"extracted_entities": ["GlobalTech Corp"], "extracted_facts": ["GlobalTech Corp acquired DataStream Inc. in Q3 2023"]}} | Required. Valid JSON object keyed by hop ID. Each hop's evidence must include extracted_entities and extracted_facts arrays. Null allowed only if no prior hops completed successfully. |
[RETRIEVAL_INDEX_SCHEMA] | Schema or description of the available retrieval indexes, including field names, types, and filterable attributes. Constrains repair queries to what the system can actually retrieve. | {"indexes": [{"name": "companies", "fields": ["name", "ticker", "sector"], "filterable": ["sector", "revenue_range"]}]} | Required. Valid JSON object describing available indexes and their capabilities. Must include field names and filterable attributes. Prevents the model from generating queries against nonexistent fields. |
[CONSTRAINTS] | Operational constraints for the repair, including max additional hops allowed, latency budget, and whether the repair can change the dependency structure or only rewrite the failed query text. | {"max_additional_hops": 2, "allow_dependency_restructure": true, "require_intent_preservation": true} | Required. Valid JSON object. max_additional_hops must be a positive integer. allow_dependency_restructure and require_intent_preservation must be boolean. Default to true for intent preservation in production. |
Implementation Harness Notes
How to wire the repair prompt into a production RAG pipeline with retry, validation, and observability.
The repair prompt is not a standalone component; it is a recovery stage inside a multi-hop RAG execution loop. When a hop in the query chain returns zero results, a low-confidence answer, or a retrieval score below a configured threshold, the orchestrator should invoke this prompt with the failed query, the original user question, the evidence collected so far, and the dependency graph. The orchestrator must treat the repair output as a replacement segment of the query plan, not a full replan, to avoid unnecessary latency and cost. The repair prompt's job is to generate alternative queries or revised dependency paths for the specific failed hop while preserving the intent of the original question.
Wire the prompt into an execution harness that enforces a strict contract. The harness should: (1) extract the failed hop's position in the dependency graph; (2) assemble the [FAILED_QUERY], [ORIGINAL_QUESTION], [COLLECTED_EVIDENCE], and [DEPENDENCY_GRAPH] inputs; (3) call the repair prompt with a timeout and a maximum token budget; (4) validate the output against a JSON schema that requires replacement_queries (array of query objects with query_text, target_hop_index, and rationale), intent_preservation_check (boolean), and fallback_strategy (string enum: retry, skip_hop, escalate). If validation fails, retry once with a stricter prompt that includes the schema violation error. If the second attempt fails, log the failure and escalate to the fallback_strategy path. Never silently accept a repair that changes the question's intent—the intent_preservation_check field must be true for the repair to proceed automatically.
Observability is critical because repair loops can mask retrieval quality problems. Log every repair invocation with: the failed query, the generated alternatives, the validator result, the retry count, and whether the repair succeeded in the subsequent retrieval attempt. Emit a metric for repair_rate (fraction of hops that trigger repair) and repair_success_rate (fraction of repairs that produce usable results). Set an alert if repair_rate exceeds 20% of hops or if repair_success_rate drops below 50%, as this indicates systemic retrieval or planning issues. For high-stakes domains, route all repairs where fallback_strategy is escalate to a human review queue with the full trace attached. The repair prompt is a safety net, not a substitute for a well-tuned retrieval pipeline—use the observability data to fix the root cause, not just to patch failures.
Expected Output Contract
Schema for the repaired plan segment returned by the Multi-Hop Query Plan Repair Prompt. Use this contract to validate the model's output before executing the replacement query.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
repair_type | string enum: [query_rewrite, hop_replacement, dependency_restructure, plan_abort] | Must match one of the allowed enum values. Reject any output with an unrecognized repair_type. | |
failed_hop_index | integer >= 0 | Must be a non-negative integer referencing the index of the failed hop in the original [ORIGINAL_QUERY_PLAN]. Reject if index is out of bounds. | |
replacement_queries | array of objects matching [QUERY_SCHEMA] | Array must contain at least 1 query object. Each object must pass the [QUERY_SCHEMA] validator. Reject empty arrays. | |
revised_dependencies | array of integers or null | If present, each integer must reference a valid hop index in the original plan. Use null when repair_type is query_rewrite and dependencies are unchanged. | |
intent_preservation_rationale | string (1-500 chars) | Must be a non-empty string explaining how the repair preserves the original question's intent. Reject if length < 1 or > 500 characters. | |
confidence_score | float between 0.0 and 1.0 | Must be a number between 0.0 and 1.0 inclusive. Trigger human review if below [CONFIDENCE_THRESHOLD]. | |
abort_reason | string or null | Required when repair_type is plan_abort. Must be null for all other repair types. Reject if abort_reason is present but repair_type is not plan_abort. |
Common Failure Modes
When a multi-hop query chain breaks, the repair prompt can silently change the question's intent or hallucinate a bridge entity. These are the most common production failure modes and how to guard against them.
Intent Drift During Repair
What to watch: The repair prompt generates an alternative query that answers a different, simpler question instead of the original multi-hop intent. This happens when the model optimizes for retrieval success over semantic fidelity. Guardrail: Embed the original user question as an immutable constraint in the repair prompt and run a semantic similarity check between the original question and the repaired query plan before execution.
Hallucinated Bridge Entities
What to watch: When a hop fails, the model invents an intermediate entity or relationship that doesn't exist in the knowledge base to connect the broken chain. The repaired plan looks plausible but leads to fabricated answers. Guardrail: Require that any bridge entity proposed in a repair must be validated against a known entity index or prior retrieval results before the next hop executes.
Infinite Repair Loops
What to watch: The repair prompt generates a new query that also fails, triggering another repair, and another, until the system exhausts its retry budget or times out. Each iteration drifts further from the original intent. Guardrail: Set a hard limit of 2 repair attempts per hop and escalate to a human or fallback answer after the budget is exhausted. Log the full repair chain for debugging.
Dependency Chain Corruption
What to watch: Repairing one failed hop breaks the dependency contract with downstream hops that expected specific intermediate outputs. The repaired hop returns a different schema or entity type, causing cascading failures. Guardrail: Validate that the repaired hop's output schema matches the expected input schema of the next dependent hop. If mismatched, regenerate the entire downstream chain from the repair point.
Over-Relaxation of Query Constraints
What to watch: The repair prompt removes temporal filters, entity constraints, or metadata scopes to get any result, returning irrelevant evidence that contaminates the final answer. Guardrail: Track which constraints were present in the original query plan and require the repair prompt to justify any constraint removal. Flag repairs that drop more than one constraint for human review.
Silent Evidence Fabrication
What to watch: Instead of admitting retrieval failure, the repair prompt generates a query that retrieves tangentially related content and the downstream synthesis treats it as authoritative evidence for the original question. Guardrail: After repair and retrieval, run an evidence-to-claim grounding check. If the retrieved passages don't explicitly support the intermediate answer, mark the hop as unverified and propagate uncertainty to the final output.
Evaluation Rubric
Run these checks against a golden dataset of known retrieval failures with expected repairs. Each criterion validates a specific failure mode of the repair prompt.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Intent Preservation | Repaired query plan addresses the same user question without introducing new constraints or dropping original requirements | Repair adds a filter or entity not present in the original question; repair drops a required comparison dimension | Compare original question intent labels against repaired plan intent labels using a held-out intent classifier |
Repair Specificity | Repaired hop targets a different retrieval surface than the failed hop and does not repeat the failed query verbatim | Repaired query is a substring or trivial rephrase of the failed query; repair changes only stop words | Compute normalized edit distance between failed query and repaired query; flag distance below 0.2 threshold |
Dependency Chain Integrity | Repaired plan maintains valid dependency edges: no hop depends on a hop that was removed or reordered without adjustment | Orphan hop references output of a deleted predecessor; circular dependency introduced by repair | Parse dependency graph from repaired plan; run cycle detection and orphan node check; assert zero violations |
Evidence Gap Coverage | Repair addresses the specific gap reported from the failed retrieval round and does not re-query for already-obtained evidence | Repair re-requests evidence already present in prior hop results; repair ignores a documented gap | Diff the gap report entities against repaired query targets; assert overlap with gap entities above 0.8 and overlap with satisfied entities below 0.2 |
Alternative Formulation Diversity | Repair generates a query that uses different terminology, entity surface forms, or retrieval angle than the failed query | Repair uses identical key terms and structure as the failed query; only punctuation or casing changes | Compute cosine similarity between failed query embedding and repaired query embedding; flag similarity above 0.95 |
Hop Budget Discipline | Repair does not add more hops than the remaining budget allows and does not exceed the maximum plan depth | Repaired plan exceeds [MAX_HOPS]; repair adds hops when budget is exhausted | Count hops in repaired plan; assert count <= [MAX_HOPS] minus already-executed hops |
Stop Condition Adherence | Repair terminates the plan when evidence is sufficient or when no viable alternative queries remain | Repair adds speculative hops after evidence sufficiency threshold is met; repair loops on same retrieval surface | Check if prior hop confidence scores exceed [SUFFICIENCY_THRESHOLD]; if true, assert repaired plan is empty or contains only a merge step |
Source Grounding | Repaired queries reference entities and relationships that exist in the retrieval corpus schema or prior evidence | Repair invents an entity name not found in any prior result; repair assumes a relationship not documented in the knowledge graph | Validate all entities in repaired queries against entity catalog from prior hop results; flag any entity with zero matches |
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
Add the full repair context: the original query plan, which hop failed, what intermediate evidence was collected, and the failure signature (empty results, low relevance scores, contradictory evidence). Include a schema for the repaired plan segment so downstream orchestration can consume it. Add a validator that checks the repair doesn't introduce circular dependencies or remove required bridge entities.
codeYou are a query plan repair agent. Given a multi-hop retrieval plan where one hop returned insufficient results, generate a repaired segment. Original question: [USER_QUESTION] Full query plan: [ORIGINAL_QUERY_PLAN] Failed hop index: [FAILED_HOP_INDEX] Failed hop query: [FAILED_QUERY] Failure signature: [FAILURE_SIGNATURE] Evidence collected before failure: [COLLECTED_EVIDENCE] Remaining dependencies: [REMAINING_DEPENDENCIES] Output a repaired plan segment as JSON: { "replacement_hops": [ { "hop_index": [FAILED_HOP_INDEX], "query": "<alternative query>", "target_backend": "<vector|keyword|graph|hybrid>", "expected_output_type": "<entity_list|fact|relationship|document_set>", "rationale": "<why this repair addresses the failure>" } ], "dependency_adjustments": [ { "affected_hop_index": "<index>", "adjustment": "<description of dependency change>" } ] }
Watch for
- Repairs that silently change the question's intent or scope
- Missing dependency adjustments when a replacement hop changes the intermediate answer shape
- Repairs that introduce new entities not grounded in collected evidence
- Format drift in the JSON output under retry conditions

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