Inferensys

Prompt

Sub-Question Dependency Graph Construction Prompt

A practical prompt playbook for decomposing complex questions into a validated dependency graph for multi-hop retrieval and agent workflows.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Sub-Question Dependency Graph Construction Prompt.

This prompt is for RAG architects and agent developers who need to answer complex questions that cannot be resolved with a single round-trip to a vector database. The core job is to decompose a multi-part user question into its constituent sub-questions and output a machine-readable directed acyclic graph (DAG) that defines the execution order. You should use this prompt when a question contains nested logic, requires information from one retrieval to formulate the next query, or combines multiple entities and relationships that must be resolved sequentially. The ideal user is an engineer building a multi-hop retrieval pipeline who needs a structured plan—not just a list of queries—to orchestrate downstream tool calls and evidence collection.

This prompt is not a general-purpose query rewriter. Do not use it for simple factoid lookups, single-hop retrieval, or synonym expansion. It is also not a substitute for an agent's planning module if your system already uses a fine-tuned planner. The prompt assumes you have a mechanism to execute the generated sub-queries and merge their results; it only produces the dependency structure. You must provide the original complex question as [USER_QUESTION], and optionally any known [DOMAIN_CONSTRAINTS] or [KNOWN_ENTITIES] that can ground the decomposition. The output is a strict JSON schema representing nodes (sub-questions) and edges (dependencies), which your application code will parse to manage parallel execution batches and sequential waits.

Before integrating this prompt into a production pipeline, validate the generated graph for cycles, orphan nodes, and redundant paths using the companion 'Dependency Graph Validation Prompt for Query Plans.' In high-stakes domains like legal research or clinical literature review, a malformed graph can silently skip critical evidence. Always log the generated graph alongside the final answer for auditability. If your latency budget is tight, consider pairing this prompt with the 'Multi-Hop Query Execution Order Optimization Prompt' to minimize total retrieval rounds after the graph is built.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Sub-Question Dependency Graph Construction Prompt delivers value and where it introduces risk. Use this to decide whether to deploy it in your pipeline.

01

Good Fit: Complex Multi-Hop Questions

Use when: A user question requires chaining multiple retrieval steps where later queries depend on earlier answers. Guardrail: Validate that the generated graph contains at least one explicit dependency edge before executing the plan.

02

Bad Fit: Simple Factoid Lookups

Avoid when: The question can be answered with a single retrieval round. Guardrail: Run a lightweight complexity classifier first. If the question is a simple lookup, skip graph construction to avoid unnecessary latency and cost.

03

Required Input: Well-Formed Question

Risk: Ambiguous or underspecified questions produce graphs with spurious dependencies or missing sub-questions. Guardrail: Pre-process the input with a disambiguation prompt or require a minimum specificity score before graph generation.

04

Operational Risk: Cyclic Dependency Graphs

Risk: The model may output a graph with circular dependencies that cause infinite execution loops. Guardrail: Run a cycle-detection validator on every generated graph. Reject and regenerate any graph that is not a strict DAG.

05

Operational Risk: Orphan Sub-Questions

Risk: The graph may contain sub-questions that are not connected to the root question or the final answer node. Guardrail: Traverse the graph from root to leaf. Flag any node with zero inbound or outbound edges for human review or automated pruning.

06

Latency Risk: Over-Decomposition

Risk: The model decomposes a question into too many fine-grained sub-questions, causing excessive retrieval rounds. Guardrail: Set a maximum node count. If exceeded, prompt the model to merge redundant sub-questions or escalate for human simplification.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for decomposing a complex question into a validated directed acyclic graph of dependent sub-questions.

This prompt template is the core instruction set you will send to the model. It is designed to accept a complex user question and output a structured dependency graph of sub-questions. The graph explicitly defines which sub-questions must be answered before others, enabling your agent or RAG orchestrator to execute a valid multi-hop retrieval plan. The template uses square-bracket placeholders for all dynamic inputs, making it ready for programmatic injection in your application code.

text
You are a precise query planner. Your task is to decompose a complex user question into a set of sub-questions and output a directed acyclic graph (DAG) of their dependencies.

**Input Question:**
[USER_QUESTION]

**Instructions:**
1. Decompose the question into the smallest set of independent sub-questions required to answer it fully.
2. For each sub-question, identify its dependencies: which other sub-questions must be answered first.
3. Output a JSON object conforming to the schema below. The graph must be acyclic.

**Output Schema:**
{
  "sub_questions": [
    {
      "id": "string (unique identifier, e.g., 'Q1')",
      "question": "string (the full text of the sub-question)",
      "depends_on": ["string (list of sub-question IDs that must be answered before this one)"],
      "expected_answer_type": "string (e.g., 'entity', 'date', 'boolean', 'list_of_facts')"
    }
  ],
  "root_questions": ["string (list of sub-question IDs with no dependencies)"]
}

**Constraints:**
- [CONSTRAINTS]

**Examples:**
[EXAMPLES]

To adapt this template, replace the placeholders with your application's specific needs. [USER_QUESTION] is the only strictly required input. Use [CONSTRAINTS] to inject rules like 'Do not create more than 5 sub-questions' or 'Prefer parallelizable questions.' Use [EXAMPLES] to provide few-shot demonstrations of the desired decomposition style for your domain. Before wiring this into a production pipeline, ensure your application layer validates the output against the schema and checks for cycles, as covered in the Implementation Harness section.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Sub-Question Dependency Graph Construction Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe pre-flight checks to prevent malformed graphs.

PlaceholderPurposeExampleValidation Notes

[COMPLEX_QUESTION]

The user's original multi-part or multi-hop question that requires decomposition

What was the revenue impact of the security incident disclosed in Q3, and how did the stock price react in the 30 days following the disclosure?

Non-empty string. Must contain at least one conjunction, conditional, or multi-entity reference. Reject single-fact lookup questions.

[MAX_SUB_QUESTIONS]

Upper bound on the number of sub-questions the model may generate to prevent graph explosion

8

Integer between 2 and 20. Values above 20 risk unmanageable graphs. Default to 10 if not specified.

[ALLOWED_DEPENDENCY_TYPES]

Permitted edge labels for the dependency graph to constrain relationship vocabulary

["requires_answer_of", "requires_context_from", "filters_results_of"]

JSON array of strings. Each value must be a valid snake_case identifier. Reject empty arrays. Use this to enforce a controlled vocabulary in the output graph.

[KNOWN_ENTITIES]

Pre-identified entities from the question to anchor decomposition and prevent hallucinated entity references

["Acme Corp", "Q3 2024", "security incident"]

JSON array of strings or null. If provided, all sub-questions must reference only these entities or explicitly derived entities. Null allowed when no prior extraction exists.

[OUTPUT_SCHEMA]

The exact JSON schema the dependency graph output must conform to

{"nodes": [{"id": "string", "question": "string", "entity_refs": ["string"]}], "edges": [{"source": "string", "target": "string", "type": "string"}]}

Valid JSON Schema object. Must define nodes with id and question fields, and edges with source, target, and type fields. Reject schemas missing required properties.

[MAX_GRAPH_DEPTH]

Maximum depth of the dependency DAG to prevent overly deep chains that cause latency blowout

4

Integer between 1 and 10. Depth is measured as the longest path from any root node to any leaf node. Reject plans exceeding this depth in post-generation validation.

[PARALLELISM_HINT]

Whether the prompt should prefer parallelizable sub-questions when possible to optimize execution time

Boolean. When true, the prompt instruction should bias toward identifying independent sub-questions that can run concurrently. When false, sequential ordering is preferred for clarity.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Sub-Question Dependency Graph Construction Prompt into a production RAG or agent pipeline with validation, retries, and observability.

This prompt is not a standalone utility; it is a planning step inside a larger retrieval pipeline. The typical integration point is after intent classification and before any retrieval execution. When a user question is flagged as complex or multi-hop, the application calls this prompt to produce a dependency graph. The graph is then consumed by an execution engine that respects the directed acyclic structure: parallel-safe sub-questions are dispatched concurrently, while dependent sub-questions wait for their upstream results. The output of this prompt should be treated as a machine-readable plan, not a final answer to the user. Store the raw graph JSON alongside the session trace for debugging and audit.

Validation is the most critical harness component. Before the graph is executed, run a structural validator that checks for cycles (a topological sort must succeed), orphan nodes (every node except root nodes must have at least one incoming edge), and redundant paths (if A→B and A→C→B both exist, flag the shorter path as potentially sufficient). Additionally, validate that every sub-question is independently answerable: if a sub-question contains unresolved pronouns or references that depend on another sub-question's output, that dependency must be explicitly represented as an edge. A common failure mode is the model producing a flat list of sub-questions with no edges, which defeats the purpose of dependency-aware execution. The harness should reject graphs with zero edges when the question contains clear multi-hop structure, and fall back to a simpler sequential plan or escalate for human review.

Model choice matters here. This task requires strong reasoning about logical dependencies and benefits from models with explicit chain-of-thought capabilities. In testing, smaller or faster models often produce graphs with missing edges or hallucinated dependencies. Consider routing this prompt to a larger reasoning model while using smaller models for simpler query decomposition tasks. Implement a retry strategy with a maximum of two attempts: if the first output fails structural validation, feed the validation errors back into a retry prompt that asks the model to repair the graph. If the second attempt also fails, log the failure, fall back to a sequential execution plan, and surface the incident to the operations dashboard. Do not silently execute a broken graph.

Observability requires logging the input question, the generated graph, validation results, and the final executed plan. Tag each trace with the graph's node count, edge count, and whether validation passed on the first attempt. This data is essential for tuning the prompt over time and identifying question categories where dependency detection is unreliable. For high-stakes domains such as legal, financial, or clinical question answering, add a human-in-the-loop approval gate before executing any graph with more than a configurable threshold of nodes, or when the model's confidence score falls below a defined cutoff. The graph should be presented to a reviewer with the original question and a clear visualization of the proposed dependencies.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the dependency graph JSON object. Use this contract to parse and validate the model's output before passing it to an execution engine.

Field or ElementType or FormatRequiredValidation Rule

graph

object

Top-level object must contain 'nodes' and 'edges' arrays.

graph.nodes

array of objects

Array must not be empty. Each node must have a unique 'id'.

graph.nodes[].id

string

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

graph.nodes[].question

string

Must be a non-empty, self-contained question string. Must not reference other node IDs.

graph.nodes[].status

string (enum)

Must be one of: 'pending', 'ready', 'complete'. Defaults to 'pending'.

graph.edges

array of objects

Array can be empty for single-hop questions. Each edge must reference valid node IDs.

graph.edges[].source

string

Must match an existing 'id' in graph.nodes. Represents the prerequisite question.

graph.edges[].target

string

Must match an existing 'id' in graph.nodes. Represents the dependent question.

graph.edges[].type

string (enum)

If present, must be one of: 'information', 'entity', 'temporal'. Defaults to 'information'.

graph.cycles_detected

boolean

Must be 'false' for a valid DAG. If 'true', the graph must be rejected and retried.

graph.orphan_nodes

array of strings

Must be an empty array for a fully connected graph. Contains IDs of nodes with no edges.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when generating sub-question dependency graphs and how to guard against it in production.

01

Cyclic Dependencies in Generated Graphs

What to watch: The model outputs a dependency graph where Sub-Question A depends on B, and B depends on A, creating an unresolvable loop. This often happens with comparative or symmetric questions where the model confuses mutual dependence. Guardrail: Run a post-generation cycle-detection validator (e.g., DFS with visited set) on every graph before execution. Reject any plan with cycles and request regeneration with an explicit anti-cycle constraint in the retry prompt.

02

Orphan Sub-Questions with No Path to the Final Answer

What to watch: The graph includes sub-questions that are not connected to the root question or any dependency chain that leads to the final answer synthesis. These orphans waste retrieval compute and can inject irrelevant context into downstream reasoning. Guardrail: Validate that every node in the graph has a directed path to the designated final answer node. Remove or flag orphan nodes before execution. Include a 'reachability check' in your graph validation harness.

03

Redundant Sub-Questions That Duplicate Retrieval Work

What to watch: The model generates multiple sub-questions that are semantically equivalent or will retrieve the same evidence, inflating latency and token costs without adding signal. This is common when the model over-decomposes a simple fact need. Guardrail: Apply semantic similarity deduplication (e.g., cosine similarity > 0.9 on query embeddings) to the generated sub-question set before execution. Merge or prune near-duplicate queries and log the reduction for observability.

04

Missing Intermediate Bridge Questions

What to watch: The graph assumes a direct connection between two sub-questions that actually requires an intermediate retrieval step to resolve an entity or relationship. The chain silently breaks at runtime when the second query references an entity not yet retrieved. Guardrail: For each dependency edge, verify that the output schema of the upstream question contains the entity type or value required as input by the downstream question. Flag edges where the output-input type contract is violated and insert a bridge extraction step.

05

Over-Serialization of Parallelizable Sub-Questions

What to watch: The model marks sub-questions as dependent when they are actually independent and could run in parallel. This unnecessarily multiplies end-to-end latency by forcing sequential execution. Guardrail: After graph generation, run a parallelizability check: if two sub-questions share no transitive dependency and neither requires the other's output, they are safe to batch. Re-label these edges and log the latency savings opportunity. Include a 'max parallel batch' constraint in the prompt.

06

Hallucinated Entities Propagating Across Hops

What to watch: An early sub-question retrieves a hallucinated or incorrect entity, and that entity is used as input to downstream sub-questions, cascading the error through the entire chain. The final answer becomes confidently wrong. Guardrail: For each hop output, validate extracted entities against the retrieved source spans before passing them to the next query. If an entity cannot be grounded in the evidence, halt the chain and trigger a re-retrieval or clarification step. Never pass ungrounded bridge entities forward.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of generated sub-question dependency graphs before integrating the prompt into a production RAG or agent pipeline. Each criterion targets a specific failure mode common in graph construction.

CriterionPass StandardFailure SignalTest Method

Graph Completeness

All atomic sub-questions from the original input are represented as nodes. No part of the complex question is omitted.

A sub-question from the input is missing from the graph. The final answer cannot be synthesized without guessing.

Manual review of node list against a pre-labeled decomposition of the input. Automated check: count of extracted sub-questions matches expected count.

Dependency Correctness

Every directed edge correctly identifies a prerequisite relationship. Node B depends on Node A only if A's answer is required to formulate B's query.

A spurious dependency is added, forcing sequential execution of parallel-safe queries. A true dependency is missing, causing a query to be executed without necessary context.

Automated check against a golden dependency matrix. Manual spot-check: for each edge, verify that the target node's query text contains a placeholder for the source node's expected output.

Cycle-Free Guarantee

The output graph is a strict Directed Acyclic Graph (DAG). No cycles exist.

A cycle is detected (e.g., A -> B -> C -> A). This creates an unresolvable execution plan.

Automated topological sort. If the sort fails, the graph is invalid. Unit test with a known cyclic input to ensure the prompt rejects it.

Node Atomicity

Each sub-question node targets a single, independently retrievable fact or entity. No compound questions exist within a single node.

A node contains a conjunction ('and') or a multi-part question that would require its own decomposition. This leads to retrieval failure for that hop.

Parse each node's query text. Fail if it contains coordinating conjunctions joining multiple distinct information needs. Manual review for implicit compound questions.

Parallel Execution Identification

Nodes with no mutual dependencies are correctly identified as parallel-safe. The output schema explicitly groups them.

Two nodes with no dependency are incorrectly sequenced. This increases end-to-end latency without benefit.

Compare the generated execution schedule to a topological ordering. Any sequential ordering of independent nodes is a failure. Check for a 'parallel_group' label in the output.

Orphan Node Prevention

Every node is connected to the graph. There are no orphan nodes that are neither a root nor a leaf reachable from the final question.

A sub-question is generated but has no edges connecting it to any other node. It is unclear when or if it should be executed.

Automated graph traversal from all root nodes. Flag any node that is not visited. Manual check: verify the orphaned question is not implicitly required for the final answer.

Output Schema Adherence

The generated JSON strictly matches the expected schema, including node IDs, query text, dependency lists, and parallel group markers.

The model outputs a valid graph structure but uses wrong field names (e.g., 'depends_on' vs 'dependencies') or nests data incorrectly, breaking the parser.

Pydantic or JSON Schema validation in the test harness. The test must fail if the output cannot be deserialized into the expected application object without repair.

Redundant Path Elimination

The graph contains no redundant edges. If A depends on B and B depends on C, a direct edge from A to C is not included.

A transitive dependency is explicitly added as a direct edge. This clutters the graph and can cause incorrect parallelization logic.

Compute the transitive reduction of the generated graph. Compare edge count. Flag any direct edge that is already represented by a longer path.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet) and minimal validation. Remove the cycle-detection and orphan-node checks from the output schema to keep the initial implementation simple. Focus on getting a valid DAG structure first.

code
[SYSTEM]
You are a query planner. Decompose the user's question into sub-questions and output a dependency graph as JSON.

[OUTPUT_SCHEMA]
{
  "sub_questions": [{"id": "q1", "text": "..."}],
  "dependencies": [{"from": "q1", "to": "q2", "reason": "..."}]
}

Watch for

  • Missing dependency reasons that make the graph unverifiable
  • Overly broad sub-questions that don't isolate retrievable facts
  • The model generating sub-questions that answer the original question directly instead of decomposing it
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.