This prompt is for advanced RAG developers building multi-step retrieval agents where a single query cannot gather all necessary evidence. Its job is to plan a sequence of retrieval queries, constraining each step by the user's permissions and knowledge requirements. Use it when a user's question demands chained reasoning across documents, and each hop must respect what the user is authorized to see. This is not for simple fact lookup or single-hop Q&A. It assumes you already have a retrieval engine, a permission model, and a way to execute the planned queries in order.
Prompt
User-Specific Multi-Hop Query Planning Prompt

When to Use This Prompt
Defines the job-to-be-done, ideal user, required context, and clear boundaries for the User-Specific Multi-Hop Query Planning Prompt.
The ideal user is an AI engineer or technical lead who has already instrumented their retrieval pipeline with user identity, role scopes, and access control lists. The prompt requires you to provide a user profile with explicit permissions, the original complex question, and a description of the available document collections. The output is a structured query plan with dependencies, where each step specifies the retrieval query, the required permission scope, and the expected intermediate evidence. You must validate that every planned query falls within the user's authorization boundary before execution; a single over-permissioned hop can leak sensitive data. Implement a hard validation layer that rejects any query step whose scope exceeds the provided user permissions, and log the rejection for audit.
Do not use this prompt for single-hop factual questions, simple keyword searches, or scenarios where a single well-scoped retrieval call can satisfy the user's intent. It is also inappropriate when the user's permissions are flat and uniform across all document collections, because the permission-aware planning adds complexity without benefit. Before adopting this prompt, ensure you have a reliable way to execute the planned queries sequentially and feed intermediate results back into the next retrieval step. If your system cannot handle stateful, multi-turn retrieval with dependency tracking, start by building that execution harness before introducing permission-aware planning.
Use Case Fit
Where this prompt works and where it does not. Multi-hop query planning with user-specific permission scoping is powerful but introduces operational complexity. These cards help you decide when to use it and what to watch for.
Good Fit: Permission-Gated Research
Use when: users with different clearance levels query the same knowledge base and each retrieval step must respect access boundaries. Guardrail: validate that every sub-query in the plan includes the user's permission filters before execution.
Good Fit: Multi-Step Compliance Audits
Use when: answering requires chaining evidence across documents with different classification levels. Guardrail: log the permission scope of each retrieval step so auditors can verify no boundary was crossed during plan execution.
Bad Fit: Single-Hop Fact Lookup
Avoid when: the question can be answered with one retrieval call. Multi-hop planning adds latency and token cost with no benefit. Guardrail: add a pre-check step that classifies query complexity and routes simple queries to a single-hop path.
Bad Fit: Public-Facing Open Search
Avoid when: all users share the same access level and documents are unclassified. The permission-scoping overhead is wasted compute. Guardrail: detect uniform access environments and skip permission injection to reduce plan generation cost.
Required Inputs
Required: user query, user permission profile with document scope boundaries, and retrieval capability descriptions. Guardrail: reject plan generation if the permission profile is missing or stale; return a clear error rather than generating an unscoped plan.
Operational Risk: Plan Drift
Risk: the generated plan may include steps that drift outside the user's permission boundary as dependencies chain. Guardrail: run a permission-boundary validator on the full plan before any retrieval step executes, and abort if any sub-query violates scope.
Copy-Ready Prompt Template
A reusable prompt template for generating a permission-aware, multi-hop query plan from a user's complex question and their access profile.
This prompt instructs the model to act as a retrieval planner that decomposes a complex user question into a sequence of dependent retrieval steps. Each step is constrained by the user's specific permissions, ensuring that no query in the plan attempts to access data outside the user's authorized scope. The template is designed to be dropped into an agentic RAG system where a planner module must produce a structured, executable plan before any retrieval calls are made.
Below is the copy-ready prompt template. It uses square-bracket placeholders for all dynamic inputs. The [USER_QUESTION] is the original multi-part query. [USER_ACCESS_PROFILE] is a structured description of the user's permissions, roles, and data scopes (e.g., 'Can access: project Alpha, Beta; Denied: financial reports'). [AVAILABLE_RETRIEVAL_TOOLS] is a list of tool signatures the planner can use, such as vector_search(query, filters), keyword_search(query, filters), or get_document(id). [PLAN_OUTPUT_SCHEMA] defines the exact JSON structure for the plan, including fields for step_id, depends_on, query, tool, filters, and justification. [CONSTRAINTS] can include rules like 'Maximum 5 steps' or 'No speculative queries about salary data.' [EXAMPLES] should contain one or two few-shot demonstrations of a user question, access profile, and the correct query plan output.
textYou are a retrieval planning agent. Your task is to decompose a complex user question into a sequence of retrieval queries that can be executed step-by-step. Each query must be strictly scoped to the user's access permissions. **User Question:** [USER_QUESTION] **User Access Profile:** [USER_ACCESS_PROFILE] **Available Retrieval Tools:** [AVAILABLE_RETRIEVAL_TOOLS] **Constraints:** [CONSTRAINTS] **Examples of Correct Plans:** [EXAMPLES] Generate a multi-hop query plan that answers the user's question. For each step, specify the query, the tool to use, any required filters derived from the access profile, and which previous steps it depends on. Ensure no step requests data outside the user's authorized scope. If the question cannot be answered within the user's permissions, output a plan that explains the limitation instead of attempting unauthorized retrieval. **Output Plan:** [PLAN_OUTPUT_SCHEMA]
To adapt this template, start by defining your [PLAN_OUTPUT_SCHEMA] as a strict JSON schema that your execution engine can parse. The [USER_ACCESS_PROFILE] should be generated programmatically from your auth system, not typed by the user. For high-stakes deployments, add a post-generation validation step that checks every query and filter in the plan against the original access profile before execution. If a step fails this check, either reject the entire plan and log an anomaly, or route it for human review. Begin testing with simple two-hop questions and a single permission boundary before scaling to complex plans.
Prompt Variables
Inputs required by the User-Specific Multi-Hop Query Planning Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to check the input quality and prevent common failures.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The original, complex user question requiring multi-step retrieval. | What are the compliance risks for our new payment product in the EU and how do they compare to our existing US risks? | Check for minimum length (>20 chars). Reject empty or whitespace-only input. Log original query for traceability. |
[USER_PROFILE] | Structured object containing user role, department, clearance level, and organizational attributes. | {"role": "compliance_officer", "department": "legal", "clearance": "confidential", "region": "EU"} | Validate JSON schema. Check that required fields (role, clearance) are present and non-null. Reject if clearance level is undefined. |
[ACCESS_POLICIES] | List of document scopes, data classifications, and permission boundaries the user is authorized to access. | ["scope:eu_regulatory", "scope:global_policy", "classification:internal", "classification:confidential"] | Ensure at least one scope is present. Validate against known policy schema. Flag if policy list is empty (possible misconfiguration). |
[RETRIEVAL_TOOLS] | Array of available retrieval functions with their capabilities, indexes, and required parameters. | [{"name": "search_regulatory_db", "index": "eu_finance_regs", "type": "vector"}, {"name": "search_internal_policies", "index": "corp_compliance", "type": "hybrid"}] | Check that each tool has a name and index. Validate that tool names match registered functions. Reject if no tools are provided. |
[MAX_PLAN_STEPS] | Integer limit on the number of retrieval steps in the generated query plan. | 5 | Must be a positive integer between 1 and 10. Default to 5 if not specified. Reject values over 10 to prevent runaway plans. |
[USER_HISTORY_SUMMARY] | Optional condensed summary of user's recent queries, document interactions, and resolved entities from the current session. | "Previously queried about EU payment directives; reviewed PSD2 and GDPR overlap docs." | If provided, check for non-empty string. If null, skip history injection. Validate that summary does not contain PII or raw document content. |
[ORGANIZATION_TERMINOLOGY] | Optional mapping of organization-specific acronyms, entity names, and controlled vocabulary terms. | {"PSD2": "Payment Services Directive 2", "GDPR": "General Data Protection Regulation", "risk_assessment": "compliance_risk_evaluation"} | If provided, validate JSON structure with string key-value pairs. Check for duplicate keys. If null, skip terminology injection. |
Implementation Harness Notes
How to wire the multi-hop query planning prompt into a secure, auditable retrieval agent.
This prompt is not a standalone module; it is the planning step in a multi-step retrieval agent. The application must call the LLM with this prompt, parse the structured query plan, validate each step against the user's permission profile, execute the steps in dependency order, and feed intermediate results into subsequent retrieval calls. The harness is responsible for enforcing that no retrieval step exceeds the user's authorized document scopes, even if the model hallucinates a disallowed filter. Treat the model's output as a proposal, not an execution command.
Implement a validate-plan-authorize-execute loop. After receiving the JSON plan, run a deterministic validator that checks: (1) every step's scope or filter field is a subset of the user's entitlements; (2) dependency references resolve to valid step IDs; (3) the plan does not exceed a configurable max_steps limit (default 5). Reject the plan and re-prompt with the violation details if validation fails. For execution, use a retrieval function that applies the user's access control list (ACL) as a mandatory pre-filter on every call, regardless of what the plan specifies. Log the proposed plan, the validated plan, any rejections, and the final retrieved documents for auditability. For high-risk domains, insert a human approval step before executing plans that touch sensitive data partitions.
Model choice matters here. Use a model with strong instruction-following and JSON mode support (e.g., GPT-4o, Claude 3.5 Sonnet) because the output must be machine-parseable and structurally consistent. Set temperature=0 or very low to minimize plan variation. Implement a retry with backoff if the output fails JSON schema validation or if the plan validator rejects the proposal more than twice. After two rejections, fall back to a single-hop retrieval with the user's full ACL applied and log the escalation. Never execute a partially validated plan. The next step after successful execution is to pass the retrieved evidence to a synthesis prompt that answers the original question, citing sources and respecting the user's permission boundaries.
Expected Output Contract
Defines the structure, types, and validation rules for the multi-hop query plan. Use this contract to parse the model output and reject malformed plans before execution.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
plan_title | string | Non-empty string. Max 120 characters. Must summarize the user's goal. | |
user_context_summary | string | Non-empty string. Must reference [USER_ROLE] or [USER_PERMISSIONS]. Cannot contain PII placeholders. | |
steps | array of objects | Array length >= 1. If length > 5, flag for human review. Each element must match the step schema. | |
steps[].step_id | integer | Sequential integer starting at 1. Must be unique within the array. | |
steps[].query | string | Non-empty string. Must not contain terms outside [USER_PERMISSIONS] scope. Check against deny-list terms. | |
steps[].retrieval_source | string | Must match one of the allowed sources in [AVAILABLE_SOURCES]. Enum check required. | |
steps[].depends_on_step_id | integer or null | If not null, must reference a valid step_id < current step_id. Null for the first step. | |
steps[].permission_scope | string | Must be a subset of [USER_PERMISSIONS]. Regex match against allowed scope patterns. Reject if scope is broader than user's access. |
Common Failure Modes
Multi-hop query planning with user-specific permissions introduces complex failure modes where authorization gaps, stale dependencies, and plan drift can silently corrupt retrieval results. These cards identify the most common production failures and provide concrete guardrails to catch them before they reach the user.
Permission Drift Across Hops
What to watch: The planner generates a sequence of queries where later steps access document scopes the user is not authorized to see, because the permission check only validated the initial query. Guardrail: Validate every generated sub-query against the user's full permission profile before execution. Implement a pre-retrieval authorization gate that rejects or rewrites any hop touching unauthorized scopes.
Stale Dependency Propagation
What to watch: An intermediate retrieval step returns outdated or irrelevant results, and the planner blindly feeds that stale context into subsequent query generation steps, compounding errors across the chain. Guardrail: Add a confidence or freshness check after each hop. If intermediate results fall below a relevance threshold, halt the plan and request re-planning rather than continuing with bad evidence.
Unnecessary Hop Inflation
What to watch: The planner generates excessive sub-queries for a question that could be answered in one or two retrieval rounds, wasting latency and compute while increasing the surface area for errors. Guardrail: Require the planner to justify each hop's necessity. Implement a maximum hop limit and a cost-aware evaluator that scores plan efficiency. Reject plans exceeding a hop budget without clear dependency justification.
Entity Resolution Collapse Across Steps
What to watch: An entity mentioned in the user's query resolves to one identifier in the first hop, but a different identifier surfaces in later hops due to ambiguous terminology or role-specific mappings, breaking the chain of evidence. Guardrail: Resolve all entities against the user's role-specific entity map before generating the plan. Freeze entity identifiers across all hops and validate that each step references the same resolved entities.
Silent Authorization Gap in Intermediate Context
What to watch: The planner correctly scopes queries to the user's permissions, but retrieved documents contain references or excerpts from unauthorized sources that leak into the final answer through the multi-hop synthesis step. Guardrail: Apply the same permission filters to retrieved context that you apply to query generation. Post-retrieval, strip or redact content from documents outside the user's access scope before feeding context into subsequent hops.
Plan Execution Order Violation
What to watch: The planner outputs a correct dependency graph, but the execution engine runs hops in the wrong order or skips a prerequisite step, causing later queries to execute without the required intermediate evidence. Guardrail: Enforce topological execution of the dependency graph. Validate that each hop's required inputs exist in the accumulated context before execution. Abort and re-plan if a prerequisite step fails or returns empty results.
Evaluation Rubric
Criteria for testing whether a generated multi-hop query plan is correct, authorized, and efficient before integrating it into a production retrieval agent.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Plan Authorization Alignment | Every sub-query in the plan is within the scope defined by [USER_PERMISSIONS] and [ACCESS_SCOPE]. No sub-query requests data from a restricted partition. | A sub-query includes a filter value, entity ID, or document scope that is explicitly denied in the user's permission profile. | Static analysis: diff the generated plan's access constraints against a known permission set. Flag any sub-query with a scope not present in the allow-list. |
Hop Necessity | Each hop after the first depends on the output of a prior hop. No redundant or independent queries are chained as hops. | Two or more hops can be executed in parallel with no data dependency, or a hop retrieves information already available from a prior step. | Dependency graph check: build a DAG from the plan. Fail if any node has zero inbound edges after the first hop, or if a node's output is unused by any downstream hop. |
Step Completeness | The plan contains all sub-queries required to answer the original [USER_QUERY] given the available retrieval tools. | A human evaluator identifies a missing piece of evidence that is required to answer the query but has no corresponding sub-query in the plan. | Gap analysis: map the final answer requirements to the plan's expected outputs. Flag any requirement with no producing step. Use a golden set of multi-hop questions with known required evidence types. |
Query Specificity | Each sub-query is a concrete, executable retrieval query with explicit search terms, filters, or entity IDs. No vague or placeholder language. | A sub-query contains phrases like 'look up relevant info' or 'search for the thing from the previous step' without specifying what to search for. | Parse check: each sub-query string must contain at least one concrete entity, filter clause, or specific search term derived from prior context. Reject plans with unresolved anaphora. |
Tool Binding Correctness | Each sub-query is assigned to a retrieval tool from [AVAILABLE_TOOLS] that is capable of executing it. No tool mismatch. | A sub-query requiring vector similarity search is assigned to a keyword index tool, or a metadata filter query is sent to a dense embedding endpoint. | Schema validation: for each step, verify the query type matches the tool's input contract. Maintain a mapping of tool capabilities and check each assignment. |
Permission Propagation | When a hop's output is used to construct a subsequent query, the permission constraints from the original user are preserved and not widened. | A downstream hop uses an entity ID from a prior result to query a broader scope than the user is authorized for, or drops a required access filter. | Taint tracking: mark all data from initial retrieval as carrying the user's permission boundary. Verify that any downstream query built from that data includes the same boundary constraints. |
Plan Efficiency | The plan uses the minimum number of hops required. No unnecessary sequential steps that could be parallelized. | The plan contains 5+ hops when a 2-hop plan is sufficient, or includes a hop that retrieves data already available from the initial context. | Compare hop count to a reference plan from a human expert or a validated plan library. Flag plans exceeding the reference hop count by more than 1 without justification. |
Error Handling Awareness | The plan includes a contingency for any hop that may return empty results, such as a fallback query or a termination condition. | A hop that depends on a prior result has no instruction for what to do if the prior hop returns null or an empty set. | Inject a simulated empty result into each hop. Verify the plan either specifies a fallback, a relaxation step, or a graceful termination message. |
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 static permission map passed as [USER_PERMISSIONS]. Use a single model call to generate the query plan. Skip step-level authorization validation in the prototype phase—focus on plan structure and dependency correctness.
code[USER_QUERY] [USER_PERMISSIONS] [AVAILABLE_RETRIEVAL_TOOLS]
Watch for
- Plans that include steps the user cannot execute
- Missing dependency declarations between steps
- Overly broad retrieval steps that ignore permission scope

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