Inferensys

Prompt

Dependency-Aware Query Decomposition for Hybrid Search Prompt

A practical prompt playbook for using Dependency-Aware Query Decomposition for Hybrid Search Prompt in production AI workflows.
Developer reviewing semantic search engine results on laptop, relevance scores visible, technical search demo.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, the ideal user, required context, and the boundaries where this prompt should not be applied.

This prompt is designed for infrastructure teams operating multi-index retrieval systems—specifically those managing vector, keyword, and graph backends simultaneously. The core job-to-be-done is translating a complex, multi-hop user question into a structured execution plan that assigns each decomposed sub-query to the most appropriate retrieval backend. You should use this prompt when a single retrieval round is insufficient, and the question requires chaining evidence from different types of indexes (e.g., finding a person via a keyword search, then using their entity ID to traverse a graph for relationships, then performing a semantic search on related documents). The ideal user is an AI engineer or search architect who already has a routing or orchestration layer and needs a reliable decomposition step that respects backend capabilities.

This prompt is not a general-purpose query rewriter. Do not use it for simple factoid questions answerable from a single vector index, or for pure conversational context expansion. It is also not a substitute for a query router—it assumes you have already determined that the question requires decomposition and hybrid retrieval. The prompt requires you to provide a catalog of available backends with their capabilities (e.g., [BACKEND_CATALOG]), so if your system only has one index type, this prompt adds unnecessary complexity. Avoid using this prompt in latency-sensitive, real-time chat without caching or pre-computation, as the decomposition step itself consumes tokens and time before any retrieval begins. It is also inappropriate for questions where the dependency chain is ambiguous and requires user clarification—this prompt plans, it does not interactively disambiguate.

Before implementing, ensure you have a validation harness that checks the output plan for backend assignment correctness, dependency cycle detection, and orphan sub-queries. The prompt outputs a machine-readable plan, but you must verify that the assigned backends actually support the query types specified. Next, proceed to the Prompt Template section to copy the base template, then review the Implementation Harness for wiring it into a production retrieval pipeline with retries, logging, and fallback strategies.

PRACTICAL GUARDRAILS

Use Case Fit

Where dependency-aware query decomposition for hybrid search delivers value and where it introduces unnecessary complexity or risk.

01

Good Fit: Multi-Index Architectures

Use when: your retrieval system spans vector, keyword, and graph indexes, and a single user question requires evidence from more than one backend. Guardrail: validate that the decomposition plan assigns each sub-query to a backend that actually exists and is reachable at runtime.

02

Good Fit: Compound Questions with Mixed Information Needs

Use when: a question mixes factual lookup, relationship traversal, and semantic similarity needs that no single index can satisfy. Guardrail: confirm that the prompt distinguishes between sub-queries that can run in parallel and those that must wait for intermediate results.

03

Bad Fit: Single-Index Simplicity

Avoid when: all retrieval happens against one vector database or one keyword index. Decomposition adds latency and planning overhead without improving recall. Guardrail: route simple queries directly to the single backend and skip the decomposition step entirely.

04

Bad Fit: Latency-Sensitive Real-Time Systems

Avoid when: end-to-end response must complete in under 200ms. Multi-hop planning plus sequential backend calls multiplies latency. Guardrail: set a maximum hop budget and enforce early-exit conditions when time thresholds are exceeded.

05

Required Input: Backend Capability Descriptions

Risk: the model assigns sub-queries to backends that don't exist or misunderstands what each index can retrieve. Guardrail: provide explicit backend schemas with supported query types, index contents, and example queries so the model can make informed routing decisions.

06

Operational Risk: Phantom Dependencies

Risk: the model invents dependencies between sub-queries that are actually independent, forcing unnecessary sequential execution. Guardrail: run a dependency graph validator after decomposition to identify and break false sequential chains before execution.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for decomposing a multi-hop question and mapping sub-queries to the optimal retrieval backend.

This template is the core instruction set for a dependency-aware query decomposition engine. It takes a complex user question and a description of available retrieval backends, then produces a structured plan. The plan identifies sub-queries, their dependencies, and the most suitable search index for each. Use this as the system prompt for a capable frontier model when building an orchestration layer for a multi-index RAG system.

text
You are a query planner for a multi-index retrieval system. Your job is to analyze a user's question and decompose it into a set of sub-queries. For each sub-query, you must assign it to the optimal retrieval backend and define its dependencies on other sub-queries.

## Available Backends
[BACKEND_DESCRIPTIONS]

## Task
1.  **Analyze the Question:** Identify the core information needs, implicit assumptions, and the type of reasoning required (e.g., factual lookup, entity traversal, comparison, temporal sequencing).
2.  **Decompose into Sub-Queries:** Break the question into the smallest set of independent or dependent sub-queries needed to gather all evidence.
3.  **Assign Backends:** For each sub-query, select the single best backend from the list above based on the query's characteristics (e.g., precise entity match, semantic similarity, relationship traversal, time-bound filter).
4.  **Define Dependencies:** Explicitly state which sub-query IDs must be executed before another. Mark sub-queries that can run in parallel.
5.  **Output Plan:** Generate a JSON object strictly conforming to the [OUTPUT_SCHEMA].

## Constraints
[CONSTRAINTS]

## Examples of Good Decomposition
[EXAMPLES]

## User Question
[USER_QUESTION]

To adapt this template, you must provide concrete values for the square-bracket placeholders. The [BACKEND_DESCRIPTIONS] should be a detailed list of your available indexes, including their strengths, weaknesses, and ideal query types (e.g., 'keyword_index: Best for exact entity names and IDs. Weak for paraphrases.'). The [CONSTRAINTS] field is critical for controlling cost and latency; use it to specify rules like 'Generate no more than 5 sub-queries' or 'Prefer parallel execution when possible.' The [OUTPUT_SCHEMA] placeholder should be replaced with a strict JSON schema definition, which you will use to validate the model's output before execution. The [EXAMPLES] placeholder is your most powerful lever for improving performance; provide 2-3 few-shot examples of a complex question and its correct decomposition plan to teach the model your specific routing logic and dependency syntax. After copying this template, integrate it into your application harness where the [USER_QUESTION] is injected at runtime.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Dependency-Aware Query Decomposition prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[USER_QUESTION]

The multi-hop question to decompose into sub-queries

What safety incidents were reported by suppliers who also failed a quality audit in Q3?

Must be non-empty string. Check for compound structure: contains multiple clauses, entities, or temporal constraints. Single-hop questions should route to a simpler prompt.

[AVAILABLE_BACKENDS]

List of retrieval backends available with their capabilities and index types

vector: dense semantic search over incident reports; keyword: BM25 over audit logs; graph: entity relationship traversal over supplier network

Must be a valid JSON array of backend objects with 'name', 'type', and 'description' fields. Validate that each backend maps to a real, reachable index. Empty array triggers fallback to single-backend decomposition.

[BACKEND_CAPABILITIES]

Detailed schema of what each backend can retrieve, including field names, filterable attributes, and entity types

vector: fields=[description, root_cause, severity], filters=[date_range, supplier_id]; graph: entity_types=[Supplier, Facility, Incident], relationships=[SUPPLIED_BY, OCCURRED_AT]

Must be a valid JSON object keyed by backend name. Validate that field names match the actual index schema. Missing capability descriptions cause the model to hallucinate filter clauses.

[MAX_SUB_QUERIES]

Upper bound on the number of sub-queries to generate

5

Must be an integer between 1 and 20. Values above 10 increase risk of redundant or low-value sub-queries. Set based on latency budget and parallel execution capacity.

[PARALLEL_EXECUTION]

Whether sub-queries without dependencies can run in parallel

Must be boolean. When true, the prompt must label parallel-safe sub-queries explicitly. When false, all sub-queries are treated as sequential regardless of actual dependencies.

[OUTPUT_SCHEMA]

Expected JSON structure for the decomposition plan

{"sub_queries": [{"id": "string", "query_text": "string", "backend": "string", "depends_on": ["string"], "parallel_safe": boolean, "expected_output_type": "string"}]}

Must be a valid JSON Schema or example structure. Validate that the schema includes dependency tracking fields. Missing 'depends_on' field causes the harness to treat all sub-queries as independent.

[DOMAIN_TERMINOLOGY]

Optional mapping of user-facing terms to canonical index terms to improve backend assignment accuracy

{"safety incident": "incident_report", "quality audit": "supplier_audit", "Q3": "date_range:2024-07-01_to_2024-09-30"}

Can be null or empty object. If provided, validate that each term maps to a real field or filter value in at least one backend. Stale terminology mappings cause incorrect backend routing.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for backend assignment before the sub-query is flagged for human review

0.7

Must be a float between 0.0 and 1.0. Sub-queries with backend assignment confidence below this threshold should be routed to a human-in-the-loop review step. Set to 0.0 to disable threshold gating.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the dependency-aware decomposition prompt into a production hybrid search pipeline with validation, routing, and observability.

This prompt is not a standalone chatbot. It is a planning stage inside a multi-index retrieval pipeline. The application calls the model with a user question, receives a structured decomposition plan, and then executes each sub-query against the assigned backend. The harness is responsible for validating the plan before execution, routing sub-queries to the correct index, collecting results, and feeding them into a downstream synthesis step. Treat the model output as an untrusted plan that must pass structural and logical checks before any retrieval I/O occurs.

Validation and routing logic must run in application code, not in the prompt. After parsing the JSON output, validate that every backend field is one of your allowed values (vector, keyword, graph). Check that sub-queries marked as dependent on a prior step reference a depends_on ID that actually exists in the plan. Reject plans with circular dependencies or orphaned steps. For each sub-query, confirm that the assigned backend matches the query characteristics: keyword queries should contain literal terms and filters, vector queries should be natural-language passages, and graph queries should specify entity types and relationship traversals. If validation fails, log the rejection reason, increment a plan_rejection metric, and retry with a stricter prompt variant or fall back to a simpler single-hop retrieval.

Execution order must respect the dependency graph. Topological sort the sub-queries so that independent steps run in parallel and dependent steps wait for their upstream results. For each completed step, extract the structured intermediate answer (entities, IDs, date ranges) and inject it into the dependent sub-query's template before execution. The prompt's [INTERMEDIATE_CONTEXT] placeholder is filled by the harness, not by the model at plan time. Log every sub-query, its assigned backend, latency, result count, and any empty-result-set events. These logs feed eval dashboards that track decomposition accuracy, backend assignment precision, and end-to-end answer quality. If a sub-query returns zero results, trigger a repair path: re-prompt with the failed step and ask for an alternative query or backend reassignment, but cap repair attempts at two to avoid latency spirals.

Model choice and latency budgeting matter here. This prompt produces structured JSON with dependency logic, so use a model with strong instruction-following and JSON output reliability (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set response_format to json_object or use structured output mode if available. Budget 2-4 seconds for plan generation; if latency exceeds this, consider caching common decomposition patterns or using a smaller model for simple single-hop questions and only invoking this prompt when a classifier detects multi-hop intent. Wire the entire pipeline through an observability layer that traces each sub-query from plan generation through retrieval to final synthesis, so you can attribute answer failures to decomposition errors, backend misassignment, or retrieval gaps.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the dependency-aware query decomposition plan. Use this contract to parse and validate the model's output before executing the retrieval plan.

Field or ElementType or FormatRequiredValidation Rule

query_plan

Array of objects

Must be a non-empty JSON array. If empty, retry with a lower decomposition threshold.

query_plan[].sub_query_id

String

Must match pattern ^SQ-[0-9]+$. Must be unique within the plan. Parse check.

query_plan[].query_text

String

Must be a non-empty string. Must not be identical to the original user question unless it is the only sub-query.

query_plan[].target_backend

Enum: ['vector', 'keyword', 'graph']

Must be one of the three allowed values. Validate against the list; reject unknown backends.

query_plan[].depends_on

Array of strings or null

Must be null or an array of valid sub_query_id strings from the same plan. No self-references allowed. Parse check for dangling references.

query_plan[].information_need

String

Must be a non-empty string describing the type of fact or evidence sought. Used to justify the target_backend assignment.

query_plan[].expected_output_schema

Object

Must be a valid JSON schema object describing the shape of the expected intermediate result. Schema check.

execution_order

Array of arrays of strings

Must be a topologically sorted batch list of sub_query_id values. All IDs must be present. No cycles allowed. Graph validation required.

PRACTICAL GUARDRAILS

Common Failure Modes

Dependency-aware query decomposition fails in predictable ways. These cards cover the most common production failure modes and the guardrails that catch them before they corrupt downstream retrieval.

01

Phantom Dependencies

What to watch: The prompt declares a dependency between two sub-queries when none exists, forcing sequential execution that wastes latency and budget. This often happens when the model over-cautiously chains queries that could run in parallel. Guardrail: Validate the decomposition plan against a parallel-safety check. Flag any dependency edge where the downstream query contains no entity, value, or constraint that must come from the upstream result. Require explicit justification for each declared dependency before accepting a sequential plan.

02

Missing Bridge Queries

What to watch: The decomposition plan jumps directly from a broad starting query to a specific target query without generating the intermediate hop that connects them. The final answer is hallucinated because the retrieval chain has a logical gap. Guardrail: Run a graph connectivity check on every decomposition plan. For each terminal sub-query, trace backward to the root query. If any path requires an entity or fact not yet retrieved, flag the plan as incomplete and request a bridge query insertion before execution.

03

Backend Mismatch for Query Type

What to watch: The prompt assigns a sub-query to the wrong retrieval backend—for example, sending a precise entity lookup to dense vector search when a keyword index would return the exact match, or routing a semantic similarity query to a graph index that has no embedding support. Guardrail: Validate each backend assignment against query characteristics. Keyword queries with exact identifiers, codes, or proper names should route to sparse or exact-match indexes. Semantic or paraphrased queries should route to vector indexes. Graph traversal queries must target a graph index with the required relationship types. Reject assignments that violate these heuristics.

04

Hallucinated Intermediate Entities

What to watch: The decomposition plan references entities, IDs, or values in downstream sub-queries that were not actually retrieved in upstream results. The model invents bridge entities to make the plan look complete, and the downstream retrieval returns irrelevant or empty results. Guardrail: After each hop executes, extract the claimed bridge entities from the upstream result with strict span citation. If the entity does not appear in the retrieved text, block the downstream query and either re-query the upstream hop or flag for human review. Never allow a downstream query to use an unverified bridge entity.

05

Over-Decomposition into Unanswerable Sub-Queries

What to watch: The prompt breaks the question into sub-queries that are individually too narrow or abstract to return useful results—for example, querying for a subjective judgment or a future prediction as if it were a retrievable fact. Each hop returns empty or low-relevance results, and the pipeline degrades into noise. Guardrail: Classify each generated sub-query by answerability type. If a sub-query asks for an opinion, prediction, counterfactual, or abstract inference rather than a retrievable fact, reject it and request reformulation. Sub-queries must target document-retrievable information. Flag unanswerable sub-queries before they consume retrieval budget.

06

Dependency Cycle or Self-Referencing Chain

What to watch: The decomposition plan contains a cycle where sub-query A depends on B, and B depends on A, or a sub-query depends on itself. The plan is logically invalid and cannot execute. This occurs when the model confuses symmetric relationships or generates redundant query steps. Guardrail: Run cycle detection on the dependency graph before execution. If a cycle is found, reject the plan and request regeneration with an explicit constraint that the dependency graph must be a directed acyclic graph. Log the cycle for prompt improvement. Never attempt to execute a cyclic plan.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the dependency-aware query decomposition prompt before production deployment. Each criterion targets a specific failure mode common in multi-index retrieval planning.

CriterionPass StandardFailure SignalTest Method

Sub-query completeness

All information needs from [USER_QUESTION] are covered by at least one sub-query in the plan

Missing sub-query for a required fact, entity, or constraint present in the original question

Manual review of 50 golden questions: compare sub-query set against human-annotated required information needs

Backend assignment accuracy

Each sub-query is assigned to the correct retrieval backend based on its information need type

Vector query assigned to keyword index, graph traversal assigned to vector index, or metadata filter sent to graph

Automated check: validate [BACKEND] field against a ruleset mapping query characteristics to expected backends

Dependency graph correctness

All inter-query dependencies are correctly labeled with type and direction; no false dependencies or missing edges

Parallel-safe queries marked as sequential, missing dependency where sub-query B requires output from sub-query A

Graph validation: check for cycles, orphan nodes, and compare dependency edges against human-annotated ground truth on 30 multi-hop questions

Output schema compliance

Response parses as valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing required fields, wrong types, extra fields that violate schema, or unparseable JSON

Schema validation: parse output with JSON Schema validator; fail if validation errors exist; measure strict pass rate across 100 test runs

Query text specificity

Each sub-query contains concrete terms, entities, and constraints sufficient for retrieval without relying on implicit context from other sub-queries

Vague sub-query like 'find information about it' where 'it' refers to an entity from another hop without explicit naming

Spot-check 20 sub-queries: each must contain at least one specific entity or constraint term; fail if any sub-query uses unresolved pronouns or references

No hallucinated backends

Only backends from the provided [AVAILABLE_BACKENDS] list are used in assignments

Backend name appears in output that is not in the allowed list, or fabricated backend capabilities are referenced

Enum check: extract all unique backend values from output; assert each exists in [AVAILABLE_BACKENDS]; fail on any mismatch

Parallel execution identification

Sub-queries with no mutual dependencies are correctly flagged for parallel execution

Sequential ordering imposed on independent sub-queries, or parallel flag set to true for queries with unresolved dependencies

Dependency analysis: for each pair of sub-queries marked parallel, verify no dependency path exists between them in the output graph; measure false-sequential rate

Confidence score calibration

Confidence scores for backend assignments correlate with assignment correctness; low-confidence assignments should predict actual errors

High confidence on incorrect backend assignments, or uniformly high confidence regardless of query ambiguity

Calibration check: bin outputs by confidence score; measure actual error rate per bin; expect error rate to decrease as confidence increases; flag if high-confidence bin exceeds 10% error rate

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single hybrid index. Remove the backend-assignment validation step and let the model output free-text sub-queries with suggested backend labels. Use a simple JSON schema without strict enum checks on backend types.

code
Decompose [QUESTION] into sub-queries. For each, suggest whether it fits vector, keyword, or graph retrieval. Output as JSON array.

Watch for

  • Model inventing backend types you don't have (e.g., "sql", "image")
  • Sub-queries that are too vague to execute against any index
  • Missing dependency labels between sub-queries
  • Over-decomposition of simple questions that don't need multiple hops
Prasad Kumkar

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.