This prompt is designed for platform engineers and RAG architects who need to decompose a complex user query into a set of independently retrievable sub-questions. It is intended to be wired directly into a retrieval pipeline where the output must be a strictly validated JSON object that downstream services can parse without ambiguity. The primary job-to-be-done is transforming a multi-part, comparative, or conditional user question into a machine-readable plan of attack, enabling a retrieval system to gather evidence for each facet of the query in parallel or in a defined sequence.
Prompt
Sub-Question Output Contract and Variable Schema Prompt

When to Use This Prompt
Defines the production use case, ideal user, and boundaries for the Sub-Question Output Contract and Variable Schema Prompt.
Use this prompt when a flat, single-vector similarity search is insufficient to answer the user's question. This typically occurs with queries that contain multiple clauses, require evidence from different data sources, or depend on conditional logic. The prompt enforces a strict JSON contract, making it suitable for high-reliability production systems where a malformed output will break the pipeline. It is not suitable for simple factoid lookups where a single retrieval round is sufficient, as the overhead of decomposition and validation adds unnecessary latency and complexity. The ideal user has a clear understanding of their available retrieval indices and can specify the expected evidence type for each sub-question.
Before implementing this prompt, ensure you have defined the target indices and evidence types your system supports. The prompt's [OUTPUT_SCHEMA] and [CONSTRAINTS] placeholders must be populated with your specific taxonomy. Do not use this prompt without a downstream validation function; the generated JSON must be verified for schema compliance, dependency integrity, and the absence of circular references before any retrieval calls are dispatched. If your use case involves high-stakes decisions, such as in finance or healthcare, a human review step should be inserted after decomposition to confirm the sub-questions fully and safely capture the user's intent before automated retrieval begins.
Use Case Fit
Where the Sub-Question Output Contract and Variable Schema Prompt works well, where it breaks, and what you must provide before wiring it into a RAG harness.
Good Fit: Multi-Hop RAG Pipelines
Use when: your retrieval system must answer complex questions that require chained evidence gathering. This prompt excels at producing a strict JSON array of sub-questions with dependency IDs, target indices, and expected evidence types that a downstream orchestrator can parse reliably. Guardrail: validate the output against the provided JSON schema before executing any retrieval step.
Good Fit: Agentic Research Workflows
Use when: an agent needs a structured research plan with explicit tool targets and evidence expectations for each step. The schema's target_index and expected_evidence_type fields let the agent dispatch sub-questions to the correct retriever without guessing. Guardrail: include a replanning trigger that regenerates sub-questions if any step returns insufficient evidence.
Bad Fit: Simple Factoid Lookups
Avoid when: the user asks a single-hop question answerable from one retrieval round. Decomposition adds latency and token cost without improving recall. A direct query-to-retrieval path is faster and cheaper. Guardrail: use a lightweight intent classifier before the decomposition prompt to route simple queries around it.
Required Input: Source Question and Index Catalog
Risk: without a clear [SOURCE_QUESTION] and a defined [INDEX_CATALOG] listing available retrieval targets, the model invents index names or misses available evidence sources. Guardrail: always inject the current index catalog as a structured list with names and capabilities. Validate that every target_index in the output matches a real index.
Operational Risk: Schema Drift in Production
Risk: model updates or prompt changes can silently alter the JSON structure, breaking downstream parsers that expect specific field names or types. Guardrail: run the provided validation function on every decomposition output. Log schema violations and trigger a retry or fallback to a simpler single-query path.
Operational Risk: Dependency Chain Breakage
Risk: if a sub-question marked with a dependency_id fails to retrieve useful evidence, all dependent sub-questions become unanswerable. The pipeline stalls silently. Guardrail: implement a dependency resolver that checks upstream results before executing dependent steps. If evidence is missing, regenerate the dependent sub-questions or escalate for human review.
Copy-Ready Prompt Template
A production-ready prompt template that decomposes a complex user query into a strict JSON array of sub-questions, each with dependency tracking, target index, and expected evidence type.
This template is designed for platform engineers integrating query decomposition into a RAG harness. It forces the model to output a predictable, machine-readable contract rather than free-text reasoning. The prompt uses explicit schema instructions, a JSON output constraint, and a dedicated field for dependency tracking to ensure that downstream orchestrators can execute sub-questions in the correct order or in parallel. Use this template when you need decomposition results that can be parsed, validated, and fed directly into a retrieval dispatch loop without manual cleanup.
textYou are a query decomposition engine. Your only job is to break a complex user question into a set of smaller, independently answerable sub-questions. ## INPUT User Question: [USER_QUESTION] Available Retrieval Targets: [RETRIEVAL_TARGETS] Conversation Context (if any): [CONVERSATION_CONTEXT] ## OUTPUT SCHEMA Return a single JSON object with a key "sub_questions" containing an array of objects. Each object must have these fields: - "id": string (unique identifier, e.g., "sq1", "sq2") - "question": string (the self-contained sub-question, resolving all pronouns and implicit references) - "depends_on": array of strings (list of sub-question IDs that must be answered before this one; empty array if independent) - "target_index": string (must be one of the available retrieval targets listed above) - "expected_evidence_type": string (one of: "fact", "list", "definition", "procedure", "comparison", "summary") - "rationale": string (brief explanation of why this sub-question is necessary) ## CONSTRAINTS 1. Every sub-question must be fully self-contained. Resolve all pronouns, anaphora, and implicit context. 2. The union of all sub-questions must cover the full intent of the original question. Do not drop any part. 3. Sub-questions must be independently answerable. A single retrieval round against the specified target_index should be sufficient. 4. If the original question is already simple and cannot be decomposed, return a single sub-question. 5. Do not include the original question as a sub-question. Decompose it. 6. Order sub-questions so that independent ones come first, followed by dependent ones. 7. Do not include any text outside the JSON object. ## EXAMPLE User Question: "Compare the pricing and security features of our enterprise plan with the pro plan, and tell me which one supports SAML." Available Retrieval Targets: ["product_docs", "pricing_db", "security_whitepapers"] Output: { "sub_questions": [ { "id": "sq1", "question": "What are the pricing details for the enterprise plan?", "depends_on": [], "target_index": "pricing_db", "expected_evidence_type": "fact", "rationale": "Extract enterprise pricing for comparison." }, { "id": "sq2", "question": "What are the pricing details for the pro plan?", "depends_on": [], "target_index": "pricing_db", "expected_evidence_type": "fact", "rationale": "Extract pro pricing for comparison." }, { "id": "sq3", "question": "What security features does the enterprise plan include?", "depends_on": [], "target_index": "security_whitepapers", "expected_evidence_type": "list", "rationale": "Extract enterprise security features for comparison." }, { "id": "sq4", "question": "What security features does the pro plan include?", "depends_on": [], "target_index": "security_whitepapers", "expected_evidence_type": "list", "rationale": "Extract pro security features for comparison." }, { "id": "sq5", "question": "Does the enterprise plan support SAML authentication?", "depends_on": [], "target_index": "product_docs", "expected_evidence_type": "fact", "rationale": "Answer the specific SAML question for enterprise." }, { "id": "sq6", "question": "Does the pro plan support SAML authentication?", "depends_on": [], "target_index": "product_docs", "expected_evidence_type": "fact", "rationale": "Answer the specific SAML question for pro." } ] }
To adapt this template, replace the placeholders with your application's runtime values. [USER_QUESTION] should be the raw user input. [RETRIEVAL_TARGETS] should be a JSON-serialized array of the index names or tool identifiers available in your system, such as ["vector_db_products", "sql_finance", "graph_entities"]. [CONVERSATION_CONTEXT] is optional but critical for multi-turn chat: include the last N turns so the model can resolve pronouns like "it" or "the second one." If your system uses a single retrieval backend, simplify the target_index constraint to a single value or remove the field. The expected_evidence_type field is a signal for downstream answer synthesis: a "fact" sub-question expects a short extractive answer, while a "list" sub-question expects multiple items. You can extend this enum to match your synthesis templates. After generating the JSON, always run it through a validation function that checks for missing IDs, circular dependencies, and coverage of the original question's intent. A broken dependency chain will cause your orchestrator to hang or skip questions, so validate before execution.
Prompt Variables
Placeholders required by the Sub-Question Output Contract and Variable Schema Prompt. Replace each placeholder with concrete values before sending the prompt to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[COMPLEX_QUERY] | The user's original multi-part or compound question that needs decomposition | What are the pricing differences between Plan A and Plan B, and which one supports SSO for enterprises with over 500 users? | Must be a non-empty string. Reject if only whitespace or fewer than 10 characters. Log a warning if the query contains no question words or comparison signals. |
[MAX_SUB_QUESTIONS] | Upper bound on the number of sub-questions the model may generate | 5 | Must be an integer between 2 and 10. If null or missing, default to 5. Reject values below 2 as decomposition is pointless; reject values above 10 to prevent runaway generation. |
[OUTPUT_SCHEMA] | The exact JSON schema definition the model must conform to for each sub-question object | {"type": "object", "properties": {"id": {"type": "string"}, "text": {"type": "string"}, "dependency": {"type": "string", "enum": ["none", "previous"]}, "target_index": {"type": "string"}, "expected_evidence": {"type": "string"}}, "required": ["id", "text", "dependency", "target_index", "expected_evidence"]} | Must be a valid JSON Schema object. Parse with a JSON Schema validator before injection. Reject if the schema is missing required fields or uses unsupported types for the target model. |
[TARGET_INDICES] | List of available retrieval indices or knowledge bases the sub-questions can target | ["product_docs", "pricing_api", "enterprise_faq", "general_kb"] | Must be a non-empty array of strings. Each string must match a configured index name in the retrieval harness. Reject if any index name is not recognized by the downstream router. |
[DEPENDENCY_MODE] | Controls whether sub-questions can depend on previous answers or must be fully parallel | sequential | Must be one of: "parallel", "sequential", "hybrid". If "parallel", all dependency fields must be "none". If "sequential", at least one sub-question must have a dependency. Validate against the generated output. |
[EVIDENCE_TYPES] | Allowed evidence type labels that sub-questions can request | ["definition", "numeric_value", "boolean_fact", "list", "comparison", "procedure"] | Must be a non-empty array of strings. Each generated sub-question's expected_evidence field must match one of these labels. Reject outputs with unknown evidence types. |
[LANGUAGE_CODE] | ISO 639-1 code for the output language of the sub-questions | en | Must be a valid two-letter ISO 639-1 code. Default to "en" if not provided. Validate against a static allowlist of supported languages in the deployment. |
Implementation Harness Notes
How to wire the Sub-Question Output Contract and Variable Schema Prompt into a production RAG pipeline with validation, retries, and error handling.
This prompt is designed to be a deterministic component inside a larger retrieval pipeline, not a standalone chat interface. The primary integration point is immediately after a complex user query is received and before any retrieval calls are made. The application should call the LLM with this prompt, parse the JSON output, and use the resulting array of sub-question objects to drive parallel or sequential retrieval requests. The strict JSON schema is the contract: if the model's output doesn't parse, the pipeline must not proceed with malformed queries.
Validation is mandatory before retrieval. Implement a JSON schema validator in your application code that checks every object in the sub_questions array for required fields (id, query_text, dependency_ids, target_index, expected_evidence_type). Reject any output where dependency_ids reference non-existent id values, where target_index contains unsupported index names, or where query_text is empty. If validation fails, retry the prompt once with the validation error message appended to the [CONSTRAINTS] section. After a second failure, log the raw output and the original user query for manual review, and fall back to a simpler single-query retrieval strategy. For high-stakes domains like healthcare or finance, route all validation failures to a human review queue instead of silently falling back.
Model choice and tool integration matter here. Use a model with strong JSON mode or structured output support (e.g., GPT-4o with response_format: { type: 'json_schema' }, Claude with tool-use for the output schema, or a fine-tuned open-weight model). Do not rely on prompt instructions alone for JSON compliance. Wire the output schema directly into the model's native structured output API when available. The target_index field should map to a controlled vocabulary of your actual retrieval backends—vector, keyword, graph, hybrid—and your retrieval dispatcher should use this field to route each sub-query to the correct index. For sub-questions with dependency_ids, queue them for execution only after their parent sub-question's retrieval results are available, and inject those results into the [CONTEXT] placeholder of the dependent query's retrieval call.
Observability and debugging require logging the full decomposition at each step. Record the original user query, the generated sub-questions, the validation result, and any retry attempts. In production, monitor the rate of validation failures, the distribution of target_index selections, and the average number of sub-questions generated. A sudden spike in sub-question count or a shift toward a single index type often signals a prompt drift or a change in user query patterns. Set up alerts for validation failure rates exceeding 5% and for any instance where the fallback single-query path is triggered, as these represent degraded retrieval quality that users will notice.
Expected Output Contract
Strict JSON schema contract for sub-question outputs. Use this table to validate every field before passing results to downstream retrieval or agent steps.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
sub_questions | Array of objects | Must be a non-empty array. Reject if length is 0 or not a JSON array. | |
sub_questions[].id | String (kebab-case) | Must match pattern ^sq-[a-z0-9-]+$. Must be unique within the array. Parse check. | |
sub_questions[].query_text | String | Must be non-empty, trimmed, and contain at least one interrogative or retrieval keyword. Length > 10 chars. | |
sub_questions[].depends_on | Array of strings or null | If non-null, every element must match an id of a preceding sub_question in the array. No self-references or forward references allowed. | |
sub_questions[].target_index | Enum string | Must be one of: 'vector', 'keyword', 'hybrid', 'graph', 'sql', 'documentation'. Reject unknown values. | |
sub_questions[].expected_evidence_type | Enum string | Must be one of: 'fact', 'definition', 'list', 'comparison', 'procedure', 'code', 'summary', 'opinion'. Reject unknown values. | |
sub_questions[].confidence | Number (float) | If present, must be between 0.0 and 1.0 inclusive. Null allowed. Used for downstream routing thresholds. | |
metadata.generated_at | String (ISO 8601 UTC) | If present, must parse as a valid UTC datetime. Used for trace logging and cache invalidation. |
Common Failure Modes
When embedding sub-question generation into a RAG harness, the most common failures are not about model intelligence but about contract violations, dependency logic, and retrieval mismatches. These cards cover what breaks first and how to guard against it.
Schema Drift and Parsing Failures
What to watch: The model omits required fields, adds extra keys, or changes the JSON structure under pressure, breaking downstream parsers. This is especially common with complex nested dependencies or when the prompt is long. Guardrail: Implement a strict post-generation validation function that checks for required fields, correct types, and enum membership. On failure, retry with a simplified schema or escalate for human review.
Broken Dependency Chains
What to watch: A sub-question references a dependency_id that does not exist, creating a dead link in the execution plan. This causes the agent to stall or skip steps. Guardrail: After generation, run a topological sort on the dependency graph. Reject any output with unresolved references. Include a repair prompt that asks the model to fix only the broken links while preserving the rest of the plan.
Target Index Mismatch
What to watch: The model assigns a sub-question to a vector index when it requires exact keyword matching, or vice versa. This leads to poor retrieval quality even when the sub-question text is correct. Guardrail: Provide a clear decision tree in the prompt for index selection based on query type. Add a post-hoc check that flags sub-questions with likely mismatched targets and routes them to a fallback hybrid search.
Over-Decomposition into Unanswerable Units
What to watch: The model atomizes the question into sub-questions that are too granular to retrieve meaningful evidence for, resulting in empty or irrelevant context windows. Guardrail: Include a minimum-evidence-viability constraint in the prompt. After retrieval, if a sub-question returns zero results, trigger a recombination step that merges it with its parent or sibling question and retries.
Evidence Type Hallucination
What to watch: The model confidently predicts that a sub-question will return a specific evidence type, such as a date or a definition, but the actual retrieved content is a narrative paragraph. This breaks downstream extraction logic. Guardrail: Treat the expected_evidence_type field as a hint, not a contract. Implement a flexible extraction step that can handle type mismatches gracefully and log discrepancies for prompt refinement.
Ignoring Original Intent Scope
What to watch: The decomposition drifts from the original question, adding sub-questions that explore tangents or omitting a core constraint like a time range or a specific entity. Guardrail: Use an LLM judge to score the generated sub-question set against the original query for completeness and constraint preservation. Fail the generation if the score is below a threshold and retry with explicit scope reminders.
Evaluation Rubric
Use this rubric to evaluate the quality of sub-question outputs generated by the Sub-Question Output Contract and Variable Schema Prompt before integrating them into a production RAG harness. Each criterion targets a specific failure mode common to structured decomposition outputs.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Schema Compliance | Output parses as valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present and no extra keys. | JSON.parse throws an error, required fields like | Automated schema validator function applied to 100% of outputs in a golden test set. |
Sub-Question Independence | Each sub-question can be answered without requiring the answer to another sub-question, unless explicitly linked via [DEPENDENCY_ID]. | A sub-question contains pronouns or references that are only resolvable by reading another sub-question's answer, and no [DEPENDENCY_ID] is set. | Human review of a 20-sample set; automated check for unresolved anaphora when [DEPENDENCY_ID] is null. |
Complete Intent Coverage | The union of all sub-questions addresses every constraint, entity, and facet present in the original [USER_QUERY]. | A named entity, time period, or explicit constraint from the original query is absent from all generated sub-questions. | LLM-as-judge using a coverage rubric comparing original query entities to sub-question entities; spot-check 50 samples. |
Target Index Appropriateness | The | A sub-question requiring a specific fact is routed to a | Rule-based check mapping |
Dependency Graph Validity | All [DEPENDENCY_ID] values reference existing | A [DEPENDENCY_ID] references a non-existent ID, or a circular dependency is detected. | Automated graph traversal script checking for missing nodes and cycles on every output. |
Query Text Retrievability | Each | A | Execute top-5 retrieval for each sub-question against a test index; fail if zero relevant results are returned for a known-answer query. |
Expected Evidence Type Specificity | The | The field contains a generic value like 'information' or a value not in the allowed enum, providing no guidance for downstream retrieval or validation. | Enum membership check plus human review of 30 samples to confirm the type matches the sub-question's actual evidence need. |
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
Use the base prompt with a simple JSON parser and minimal validation. Replace the strict schema with a looser structure that accepts partial outputs during experimentation. Focus on getting the decomposition logic right before locking down the contract.
Watch for
- Missing
dependency_idscausing downstream merge failures - Sub-questions that are not independently answerable
- Overly broad
target_indexvalues that defeat retrieval routing

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