This prompt is designed for infrastructure teams operating retrieval pipelines that span multiple backend types—dense vector stores, sparse keyword indexes (like BM25), and graph databases—where each backend has a distinct schema, query language, and performance profile. The core job-to-be-done is translating a single, unstructured user question into a structured query plan that maps the user's intent to backend-specific query formulations. Without this step, teams often resort to sending the same raw query string to every index, which leads to poor recall on sparse backends, nonsensical graph traversals, and wasted compute. The ideal user is a platform engineer, search architect, or RAG pipeline owner who already has a routing or fan-out dispatch layer and needs a reliable, machine-readable plan to drive it.
Prompt
Index-Aware Query Planning Prompt for Heterogeneous Backends

When to Use This Prompt
Determine if your multi-backend retrieval infrastructure requires an index-aware query planning step before dispatch.
You should use this prompt when your retrieval topology includes at least two backends with materially different capabilities—for example, a dense index that expects natural language passages and a graph index that requires explicit entity IDs and relationship types. It is also appropriate when your indexes have different metadata schemas, requiring date filters on one backend but not another, or when one backend supports faceted search while another does not. The prompt expects you to provide a description of each available backend, including its schema, supported query operations, and any constraints (e.g., 'graph index only supports single-hop traversals'). The output is a JSON plan that can be parsed by your dispatch service to construct and execute backend-specific queries in parallel. Do not use this prompt for single-backend deployments, for setups where all indexes share an identical schema, or for simple synonym expansion tasks that don't require backend awareness.
Before adopting this prompt, verify that your retrieval dispatch layer can consume a structured plan with per-backend query objects. If your current architecture simply broadcasts a raw string to every index, you'll need to add a plan-parsing step. Start by running the prompt against a representative sample of user queries and manually inspecting whether the generated plans respect each backend's documented capabilities. Common failure modes include the model inventing query operators that don't exist for a given backend or omitting a backend that should have been included. If your retrieval pipeline is high-stakes—for example, in regulated domains where missed documents have compliance implications—add a validation layer that checks each generated query against the backend's actual query schema before execution, and log plan-to-execution traces for auditability.
Use Case Fit
This prompt is designed for infrastructure teams managing multiple index types with different schemas. It maps a user question to backend-specific query formulations, respecting each index's capabilities, schema, and performance characteristics. Below are the scenarios where it excels and where it introduces risk.
Good Fit: Heterogeneous Retrieval Pipelines
Use when: Your system routes queries across dense vector, sparse keyword, and graph backends simultaneously. The prompt excels at producing a unified plan that respects each backend's schema and query language. Guardrail: Validate the generated plan against a live schema registry before execution to catch hallucinated field names or unsupported operators.
Bad Fit: Single-Backend or Simple RAG Setups
Avoid when: You only have one retrieval index or a simple vector database. The overhead of generating a multi-backend plan adds latency and complexity without benefit. Guardrail: Use a lightweight query rewriter or direct embedding generation instead. Reserve this prompt for systems with at least two distinct index types.
Required Input: Live Schema and Capability Definitions
What to watch: Without explicit schema definitions, the model will hallucinate field names, filter syntax, or query operators that don't exist in your backends. Guardrail: Always inject a machine-readable schema for each backend into the prompt context. Validate generated queries against that schema before retrieval execution.
Required Input: User Query with Explicit Intent
What to watch: Vague or underspecified user queries produce vague plans. The model cannot infer which backends are relevant without clear signals. Guardrail: Pre-process user queries with an intent classifier before passing them to this prompt. If intent is ambiguous, route to a disambiguation step rather than generating a low-confidence plan.
Operational Risk: Plan Execution Ordering
What to watch: The prompt may generate a plan with implicit dependencies between backends but fail to specify execution order. Running dependent queries in parallel can cause failures or wasted compute. Guardrail: Parse the generated plan for dependency declarations. If none exist, assume parallel execution is safe. If dependencies are implied but not explicit, flag for human review before execution.
Operational Risk: Backend Capability Drift
What to watch: Backend schemas and capabilities change over time. A prompt that worked last week may generate invalid queries today if a field was renamed or an index was deprecated. Guardrail: Version your schema definitions alongside your prompt. Run a daily validation job that tests generated plans against current backend capabilities and alerts on schema mismatch failures.
Copy-Ready Prompt Template
A reusable prompt that maps a user question to backend-specific query formulations, respecting each index's schema and capabilities.
This prompt template is the core instruction set for an LLM acting as a query planner over heterogeneous retrieval backends. It forces the model to reason about each available index's strengths, schema constraints, and query language before producing a structured plan. The output is not a single query but a mapping of backend identifiers to their respective query formulations, along with a justification for each choice. Use this template when your retrieval architecture includes at least two distinct index types (e.g., a dense vector store, a BM25 keyword index, and a graph database) that require different query shapes.
codeYou are a query planner for a multi-backend retrieval system. Your job is to analyze a user's question and produce a query plan that maps the question to backend-specific query formulations. You must respect each backend's capabilities, schema, and query language. Do not generate a single query for all backends; instead, produce a plan that assigns the right query shape to each backend. ## AVAILABLE BACKENDS [BACKEND_DEFINITIONS] ## USER QUESTION [USER_QUESTION] ## CONVERSATION CONTEXT (if any) [CONVERSATION_HISTORY] ## CONSTRAINTS - Each backend query must be valid for that backend's query language and schema. - Do not assign a query to a backend that cannot answer the question type. - If a backend is irrelevant, mark it as "SKIP" with a brief reason. - Prefer parallel execution where dependencies allow; mark sequential dependencies explicitly. - Include any metadata filters, date ranges, or entity constraints extracted from the question. - If the question is ambiguous, generate clarifying variants rather than guessing. ## OUTPUT SCHEMA Return a JSON object with this exact structure: { "plan_id": "string, unique identifier for this plan", "question_analysis": { "intent": "string, classified intent of the question", "required_capabilities": ["list of required retrieval capabilities"], "extracted_entities": ["list of entities mentioned"], "extracted_filters": {"field": "value"}, "ambiguity_notes": "string or null" }, "backend_plans": [ { "backend_id": "string, matches BACKEND_DEFINITIONS", "action": "QUERY | SKIP", "skip_reason": "string if SKIP, otherwise null", "query_formulation": { "query_type": "string, e.g., dense_vector, bm25_keyword, graph_traversal, hybrid", "query_body": "string, the actual query text or structured query object", "filters": {}, "top_k": number, "embedding_hint": "string or null, guidance for embedding model selection" }, "justification": "string, why this formulation fits this backend and question", "depends_on": ["backend_id or null, if this query needs results from another backend first"] } ], "execution_order": ["ordered list of backend_ids for sequential execution"], "merge_strategy": "string, brief note on how results should be combined" } ## EXAMPLES [FEW_SHOT_EXAMPLES] ## RISK LEVEL [RISK_LEVEL]
To adapt this template, start by populating [BACKEND_DEFINITIONS] with a structured description of each available index. For each backend, specify its type (dense, sparse, graph, hybrid), its query language or API constraints, its schema fields, and the kinds of questions it handles well. The [FEW_SHOT_EXAMPLES] placeholder should contain at least two worked examples showing a user question and the correct output plan. For high-stakes domains where incorrect retrieval could cause harm, set [RISK_LEVEL] to HIGH and add a human-review step before query execution. The [CONVERSATION_HISTORY] placeholder is optional but critical for multi-turn retrieval scenarios where the current question depends on prior context. Before deploying, validate that the model's output conforms to the JSON schema using a structural validator, and run at least five test questions through the plan to check that backend assignments are correct and query formulations are executable against your actual indexes.
Prompt Variables
Required and optional inputs for the Index-Aware Query Planning Prompt. Validate each variable before sending the prompt to avoid schema violations, missing backend definitions, or ungrounded query plans.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUESTION] | The natural language question to plan retrieval for | What were Q3 revenue trends in the EMEA region for enterprise accounts? | Non-empty string; max 500 chars; must contain a question or information need |
[BACKEND_CATALOG] | JSON array describing available index types, their schemas, capabilities, and query syntax constraints | [{"backend_id":"dense_v1","type":"dense_vector","embedding_model":"text-embedding-3-large","supported_operators":["semantic_search"],"schema_fields":["content","title","date"]}] | Valid JSON array; each entry requires backend_id, type, and schema_fields; type must be one of dense_vector, sparse_keyword, graph, hybrid |
[BACKEND_SCHEMAS] | Detailed field definitions, data types, and filterable attributes for each backend | {"dense_v1":{"fields":{"content":"text","title":"text","date":"date","region":"keyword"}}} | Valid JSON object keyed by backend_id; each field must declare a type; date fields must specify format if non-ISO |
[CONSTRAINTS] | Operational limits: max queries per backend, latency budget, result count targets, required filters | {"max_queries_per_backend":3,"latency_budget_ms":200,"min_results_per_backend":5,"required_filters":["region=EMEA"]} | Valid JSON object; numeric fields must be positive integers; required_filters must reference fields present in BACKEND_SCHEMAS |
[OUTPUT_SCHEMA] | Expected structure for the query plan output | {"plan":[{"backend_id":"string","query_variant":"string","query_type":"string","filters":{},"weight":0.0}]} | Valid JSON schema; must include plan array with backend_id, query_variant, and query_type fields; weight must be float 0.0-1.0 |
[FEW_SHOT_EXAMPLES] | Optional array of example user questions with correct query plans for in-context learning | [{"question":"Show me recent security incidents","plan":[{"backend_id":"sparse_v1","query_variant":"security incident 2024 2025","query_type":"keyword_phrase","filters":{},"weight":0.6}]}] | If provided, must be valid JSON array; each example requires question and plan fields matching OUTPUT_SCHEMA; null allowed |
[DOMAIN_TERMINOLOGY] | Optional mapping of domain-specific terms, entity IDs, or controlled vocabulary for query normalization | {"EMEA":["Europe","Middle East","Africa"],"enterprise":"account_tier=enterprise"} | If provided, valid JSON object; keys are canonical terms; values are arrays of synonyms or filter mappings; null allowed |
Implementation Harness Notes
How to wire the index-aware query planning prompt into a production retrieval pipeline with validation, routing, and observability.
This prompt is designed to sit at the entry point of a multi-backend retrieval pipeline. It receives a raw user question and produces a structured query plan that maps the question to backend-specific query formulations. The output is not a final answer but a machine-readable plan consumed by downstream orchestrators. You should treat this prompt as a planning step, not a retrieval step. Its job is to decide what to ask each index, not to execute those queries. In production, the prompt runs once per user question before any retrieval calls are made. The resulting plan is then dispatched to a fan-out execution layer that sends each backend-specific query to its respective index in parallel or in dependency order.
Integration pattern: Wrap the prompt in a lightweight service or serverless function that accepts a user_query string and an optional session_context object. The function should inject the available backend capabilities and schemas from a configuration store or environment variable, not from user input. A typical request payload includes [USER_QUESTION], [BACKEND_CAPABILITIES] (a JSON array describing each index type, its schema, supported operators, and performance characteristics), and [CONSTRAINTS] (latency budgets, result count targets, and any mandatory filters). The model returns a JSON plan with a backends array, each entry containing a backend_type, a query_formulation, and optional dependency_on fields for multi-hop ordering. Validation layer: Before the plan reaches the execution layer, run structural validation: check that every backend_type in the plan exists in the declared capabilities, that no query formulation references fields or operators the backend doesn't support, and that dependency chains are acyclic. If validation fails, log the failure, capture the raw model output, and either retry with a more explicit constraint message or fall back to a default single-backend query. For high-stakes applications, add a human review gate for plans that introduce new backend combinations not seen in the evaluation dataset.
Model choice and latency: This is a reasoning-heavy prompt that benefits from models with strong instruction-following and structured output capabilities. GPT-4o, Claude 3.5 Sonnet, and similarly capable models perform well. Expect 1-3 seconds of latency for plan generation. Cache the backend capabilities schema in the system prompt prefix to reduce token reprocessing. Observability: Log every generated plan alongside the user query, the backend capabilities snapshot, validation results, and the eventual retrieval quality metrics (recall@k, precision, or task-specific scores). This traceability lets you debug when a poor retrieval result traces back to a bad query plan rather than a bad index. Failure modes to monitor: Plans that route all queries to a single backend despite available alternatives (under-utilization), plans that generate syntactically valid but semantically empty queries for a backend, and plans with circular dependencies. Set up alerts on validation failure rate and on plan-to-execution latency exceeding your retrieval SLA. Next step: After the plan executes and results return, feed the plan and results into a result harmonization prompt to merge, deduplicate, and rank the multi-backend output into a unified result set.
Expected Output Contract
Defines the required fields, types, and validation rules for the query plan object returned by the Index-Aware Query Planning Prompt. Use this contract to parse, validate, and route the model output before executing backend queries.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
plan_id | string (UUID v4) | Must be a valid UUID v4 string. Reject if missing or malformed. | |
original_query | string | Must match the [USER_QUESTION] input exactly. Fail if altered or truncated. | |
backend_assignments | array of objects | Array length must be >= 1 and <= number of backends in [AVAILABLE_BACKENDS]. Reject if empty or contains duplicate backend_name values. | |
backend_assignments[].backend_name | string | Must exactly match a name in the [AVAILABLE_BACKENDS] list. Case-sensitive match required. | |
backend_assignments[].query_formulation | string | Must be a non-empty string. Reject if identical to original_query for all backends without justification in formulation_rationale. | |
backend_assignments[].formulation_rationale | string | Must be 1-3 sentences explaining why this formulation suits the backend. Reject if empty or generic boilerplate. | |
backend_assignments[].schema_compliance_notes | string | If present, must reference specific schema fields from the backend definition. Null allowed when no schema constraints apply. | |
execution_order | array of strings | Must list backend_name values in recommended execution sequence. All assigned backends must appear. Reject if missing any backend or containing unassigned names. |
Common Failure Modes
When a single prompt must plan queries across dense, sparse, and graph backends, failures cascade quickly. These are the most common breakages and how to prevent them before they reach production.
Schema Hallucination
What to watch: The model invents field names, filter operators, or index capabilities that don't exist in your actual backend schemas. A query plan referencing vector_index.semantic_score or graph.traverse_depth may look plausible but will fail at execution time. Guardrail: Provide the exact schema for each backend as a structured [INDEX_CAPABILITIES] block in the prompt. Validate every generated query field against an allowlist before execution. Reject plans that reference undefined fields rather than silently dropping them.
Backend Mismatch
What to watch: The model routes a query to the wrong backend type—sending a precise keyword lookup to a dense vector index or a broad conceptual question to a graph traversal engine. The query executes but returns irrelevant or empty results because the formulation doesn't match the retrieval mechanism. Guardrail: Include explicit backend capability descriptions in the prompt: what each index is optimized for, its query syntax, and its failure characteristics. Add a pre-execution classifier that verifies the planned backend matches the query type before dispatching.
Constraint Dropping
What to watch: The user's question contains implicit constraints—date ranges, source filters, entity types—that the query planner silently omits when generating backend-specific formulations. The sparse query keeps the date filter but the dense variant drops it, producing results from all time periods that pollute the final merged output. Guardrail: Extract all explicit and implicit constraints into a [CONSTRAINTS] block before query generation. Require every backend-specific query variant to reference or explicitly exclude each constraint with a rationale. Post-generation, diff each variant against the constraint list.
Variant Collapse
What to watch: The model generates multiple query variants that are near-duplicates—same terms, same structure, same intent—defeating the purpose of multi-backend retrieval. You pay the compute cost of parallel execution but get no diversity benefit because all variants retrieve the same documents. Guardrail: Add a diversity requirement to the prompt specifying minimum semantic distance between variants. Implement a post-generation deduplication check using embedding similarity or Jaccard distance on token sets. Reject and regenerate variants that fall below a similarity threshold.
Unresolved Entity References
What to watch: The user mentions an entity by name, acronym, or shorthand that the query planner passes through without resolution. The graph backend needs a canonical entity ID, the sparse backend needs the full name, and the dense backend needs context—but the generated query uses the raw user string across all three, producing inconsistent or empty results. Guardrail: Run entity resolution before query planning. Provide a resolved [ENTITIES] block with canonical IDs, aliases, and types. Require the planner to use resolved identifiers in structured backends and expanded forms in text backends. Flag unresolved entities for human review.
Execution Order Violation
What to watch: The planner generates a multi-step query plan where step 2 depends on results from step 1, but the generated queries are submitted in parallel or in the wrong order. The dependent query executes against stale or empty context, producing garbage that cascades into the final answer. Guardrail: Require the planner to output explicit dependency edges between query steps. Validate the execution DAG before dispatch—reject plans with cycles or missing upstream results. Use a workflow engine that enforces step ordering rather than trusting the model's implicit sequencing.
Evaluation Rubric
Criteria for testing the quality and safety of an Index-Aware Query Plan before it is executed in a production retrieval pipeline. Use these checks to gate plan generation and catch regressions.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Schema Compliance | Every generated backend query block strictly matches the declared schema for that index type (e.g., required fields present, no extra fields). | Schema validation error; missing required field like 'vector_query' or 'keyword_clause'; unknown field present. | Automated JSON Schema validation against the backend-specific schema definitions provided in [INDEX_SCHEMAS]. |
Backend Capability Match | Each sub-query uses only operators and query types supported by its assigned backend (e.g., no semantic similarity clause on a pure keyword index). | Plan assigns a dense vector query to a BM25-only backend; uses graph traversal syntax on a flat index. | Static analysis of the plan against a capability matrix; check that query type matches backend capabilities in [BACKEND_CAPABILITIES]. |
Query Intent Preservation | The union of all generated sub-queries covers the full semantic intent of the original [USER_QUESTION] without introducing conflicting constraints. | A critical constraint from the user question is dropped; two sub-queries impose contradictory filters (e.g., date:>2023 and date:<2022). | LLM-as-Judge pairwise comparison: rate whether the plan's combined constraints capture all elements of the original question. Human review for high-stakes queries. |
Constraint Grounding | All explicit constraints (filters, date ranges, entity IDs) in the plan are directly derived from [USER_QUESTION] or [SESSION_CONTEXT], with no hallucinated values. | Plan includes a filter for 'region=EMEA' when the user only mentioned 'Europe'; invents a specific entity ID not present in the input. | Entity extraction diff: compare extracted constraints against a ground-truth extraction from the input. Flag any constraint not traceable to the source text. |
Backend Assignment Logic | Each sub-query is assigned to the most appropriate backend based on its semantic type (e.g., exact match to keyword, conceptual to dense, relationship to graph). | A sub-query requiring exact SKU matching is routed to a dense vector index; a graph traversal is sent to a keyword index. | Rule-based check: verify that the sub-query type matches the routing rules defined in [ROUTING_STRATEGY]. Spot-check with domain experts. |
Plan Feasibility | The plan contains no impossible operations, such as requiring a join between two backends that have no shared key or requesting a hop count that exceeds the graph's depth. | Plan specifies a join on a field that doesn't exist in both schemas; requests a 5-hop traversal on a graph with a max depth of 2. | Automated feasibility check against [INDEX_SCHEMAS] and [BACKEND_CAPABILITIES]; simulate plan execution in a dry-run mode if available. |
Output Format Adherence | The final output is a valid, parseable JSON object conforming exactly to [OUTPUT_SCHEMA], with no extra commentary or markdown fences. | JSON parsing fails; output is wrapped in markdown code blocks; contains top-level explanatory text outside the JSON structure. | Automated JSON parse test followed by structural validation against the expected [OUTPUT_SCHEMA]. |
Ambiguity Handling | When [USER_QUESTION] is ambiguous (e.g., 'Apple'), the plan either generates disambiguating sub-queries for multiple interpretations or flags the ambiguity in a designated field. | Plan silently assumes one interpretation without generating alternatives or flagging the ambiguity; produces a single, over-confident query for an ambiguous term. | Test with a curated set of ambiguous queries; check for the presence of multiple query variants or a populated 'ambiguity_notes' field in the output. |
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 single backend schema. Replace the multi-backend plan with a simpler mapping: one user question → one backend-specific query. Use a lightweight JSON schema for the output and skip the feasibility checks.
codeYou are a query planner for a [BACKEND_TYPE] index with schema [SCHEMA]. Given a user question, produce a single query object optimized for this backend. User question: [QUESTION] Backend schema: [SCHEMA]
Watch for
- Schema fields that don't exist in your actual index
- Overly complex query syntax your backend doesn't support
- Missing validation of field names against the real schema

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