Inferensys

Prompt

Session-Aware Sub-Question Generation Prompt

A practical prompt playbook for decomposing complex, context-dependent follow-up questions into independently retrievable sub-questions while preserving dependencies established in prior conversation turns.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for session-aware sub-question generation.

This prompt is for RAG architects and agent builders who need to answer complex, multi-part follow-up questions that cannot be resolved with a single retrieval round. The core job-to-be-done is decomposing a user's current question into a set of independently retrievable sub-questions while preserving the dependencies and constraints established in prior conversation turns. Without this step, a retrieval system treats each turn in isolation, losing critical context like 'What about the second one?' or 'How does that compare to the previous approach?' and producing irrelevant or incomplete results.

The ideal user is an engineer integrating this prompt into a retrieval pipeline or an agent loop where the system must gather evidence across multiple documents before synthesizing an answer. Required context includes the full conversation history, the current user query, and optionally a schema of the available knowledge base to ground sub-questions in retrievable entities. Do not use this prompt for simple factual lookups, single-turn Q&A, or cases where the follow-up is a trivial clarification. It is also not a substitute for a full dialogue state tracker; it assumes the prior turns contain the necessary referents and does not ask the user for missing information.

Before wiring this into production, define clear failure boundaries. The prompt can over-decompose a simple question into unnecessary sub-questions, wasting retrieval budget and latency. It can also hallucinate dependencies that do not exist in the conversation history, creating retrieval paths that lead to fabricated answers. Always validate that generated sub-questions are grounded in explicit prior-turn content, and implement a circuit breaker that limits the number of sub-questions per turn. Pair this prompt with a regression suite that includes cross-turn dependency tests: anaphora, ellipsis, comparative references, and implicit topic carry-forward.

PRACTICAL GUARDRAILS

Use Case Fit

Where session-aware sub-question generation delivers value and where it introduces risk. Use these cards to decide if this prompt fits your retrieval architecture.

01

Good Fit: Multi-Turn Complex Reasoning

Use when: Users ask follow-up questions that depend on entities, constraints, or findings from prior turns. The prompt excels at breaking compound questions into ordered sub-questions that respect cross-turn dependencies. Guardrail: Validate that each generated sub-question references only entities present in the provided session context, not hallucinated facts.

02

Bad Fit: Single-Turn Factoid Lookup

Avoid when: The user asks a standalone question with no conversational history. Decomposition adds latency and token cost without improving retrieval quality. Guardrail: Implement a turn-count gate. If session history is empty or the query is self-contained, route directly to a simpler query rewrite prompt instead.

03

Required Inputs

What you must provide: The current user question, the full conversation history (or a structured summary of prior turns), and the original system context or task description. Guardrail: If conversation history exceeds the model's context window, preprocess with a session summarization prompt before passing to sub-question generation. Missing history causes unresolved anaphora.

04

Operational Risk: Dependency Chain Breaks

What to watch: The prompt may generate sub-questions that assume a prior sub-question was answered successfully. If retrieval for an early sub-question returns empty or irrelevant results, downstream sub-questions become unanswerable. Guardrail: Wrap each sub-question retrieval in a result check. On empty results, halt the chain and either relax the query or escalate to the user for clarification.

05

Operational Risk: Latency Amplification

What to watch: Each sub-question triggers a separate retrieval round. For 4-6 sub-questions, end-to-end latency multiplies and can exceed user tolerance in synchronous chat. Guardrail: Parallelize independent sub-questions where the prompt marks them as non-sequential. Set a maximum sub-question limit (e.g., 5) and a total timeout. Fall back to a single merged query if the clock expires.

06

Operational Risk: Context Pollution Across Turns

What to watch: The prompt may carry forward constraints from earlier turns that the user has implicitly abandoned or overridden. This produces sub-questions that chase stale intent. Guardrail: Include a turn-relevance check before decomposition. Score each prior turn's relevance to the current query. Exclude turns below a threshold from the session context passed to the prompt.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for decomposing session-aware follow-up questions into dependency-respecting sub-questions.

This section provides the core prompt template for session-aware sub-question generation. The prompt instructs the model to decompose a follow-up question into independently answerable sub-questions while preserving dependencies established in prior conversation turns. Use this template as the foundation for your decomposition step in multi-turn RAG pipelines where compound questions require stepwise evidence gathering across retrieval rounds.

text
You are a query decomposition engine for a multi-turn retrieval system. Your job is to break a follow-up question into a sequence of sub-questions that can be answered independently, respecting dependencies established in the conversation history.

## CONVERSATION HISTORY
[CONVERSATION_HISTORY]

## CURRENT QUESTION
[CURRENT_QUESTION]

## OUTPUT SCHEMA
Return a JSON object with the following structure:
{
  "original_question": "string (the current question exactly as provided)",
  "dependencies_from_history": [
    {
      "turn_index": "integer (which prior turn this dependency comes from)",
      "entity_or_fact": "string (the specific entity, fact, or constraint carried forward)",
      "resolution": "string (how this dependency is resolved in the current context)"
    }
  ],
  "sub_questions": [
    {
      "order": "integer (execution order, starting at 1)",
      "question": "string (a self-contained question that can be answered independently)",
      "depends_on": ["integer (list of sub_question order numbers this question depends on, empty array if none)"],
      "expected_answer_type": "string (entity, list, fact, comparison, summary, yes_no, or numeric)",
      "reasoning": "string (why this sub-question is necessary and how it relates to dependencies)"
    }
  ],
  "decomposition_strategy": "string (brief explanation of the overall decomposition approach)"
}

## CONSTRAINTS
- Every sub-question must be self-contained and answerable without referring back to the conversation.
- Resolve all pronouns, implicit references, and elliptical constructions before writing sub-questions.
- If the current question is already simple and self-contained, return a single sub-question.
- Order sub-questions so that dependency questions appear before the questions that depend on them.
- Do not invent facts not present in the conversation history or current question.
- If a dependency from history is ambiguous, flag it in the dependencies_from_history array with a note in the resolution field.
- Maximum of [MAX_SUB_QUESTIONS] sub-questions. If decomposition would exceed this, prioritize the most critical questions and note the truncation in decomposition_strategy.

## EXAMPLES
[FEW_SHOT_EXAMPLES]

## RISK LEVEL
[RISK_LEVEL]

Adapt this template by adjusting the output schema fields to match your downstream retrieval and answering architecture. If your system uses structured metadata filters, add a metadata_filters field to each sub-question. For agentic systems that execute tool calls between sub-questions, add a required_tools array. Replace [FEW_SHOT_EXAMPLES] with 2-3 annotated examples showing correct dependency resolution across turns. Set [MAX_SUB_QUESTIONS] based on your latency budget—typically 3-5 for interactive systems, up to 10 for batch or async workflows. The [RISK_LEVEL] placeholder should be set to low, medium, or high to trigger appropriate validation behavior in your harness. Before deploying, validate that the model correctly resolves cross-turn dependencies by running the test cases described in the evaluation section of this playbook.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Session-Aware Sub-Question Generation Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[CURRENT_QUESTION]

The user's latest follow-up question that may depend on prior conversation context

What about the pricing model?

Non-empty string check. Must differ from [PRIOR_QUESTION] when session context exists. Null not allowed.

[CONVERSATION_HISTORY]

Prior turns in the session, including user questions and assistant responses, needed to resolve dependencies

User: What is the enterprise plan? Assistant: The enterprise plan includes...

Array of turn objects with role and content fields. Minimum 1 prior turn required for session-aware behavior. Schema check: each turn must have 'role' in ['user', 'assistant'].

[SESSION_TOPICS]

Extracted topic summary from prior turns to anchor sub-question generation

Enterprise pricing, seat licensing, annual billing

String or array of strings. Can be null if no topics extracted. If provided, must not contradict [CONVERSATION_HISTORY] content.

[MAX_SUB_QUESTIONS]

Upper bound on the number of sub-questions the model should generate

5

Integer between 1 and 10. Default 5 if not specified. Parse check: must be a valid integer.

[RETRIEVAL_SYSTEM_CAPABILITIES]

Description of what the downstream retrieval system can handle, to constrain sub-question formulation

Supports keyword search over product docs and vector search over FAQs

Non-empty string. Should describe index types, document scopes, and any query format constraints. Null not allowed.

[DEPENDENCY_MARKERS]

Labels or flags indicating which prior-turn entities, constraints, or answers must carry forward into sub-questions

pricing_model, enterprise_plan, annual_billing

Array of strings or comma-separated string. Can be empty if no dependencies detected. Each marker should correspond to an entity or constraint present in [CONVERSATION_HISTORY].

[OUTPUT_FORMAT]

Schema specification for the expected sub-question output structure

JSON array of objects with 'sub_question', 'dependency_source', 'retrieval_target' fields

Must be a valid schema description string. Parse check: downstream parser must be able to validate output against this schema. Null not allowed.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Session-Aware Sub-Question Generation prompt into a production RAG pipeline with validation, retries, and logging.

Wiring this prompt into an application requires treating it as a structured pre-retrieval step within a multi-turn RAG pipeline. The prompt expects two primary inputs: the current user query and a serialized representation of the conversation history. Before calling the model, the application must assemble the history by extracting prior user turns and assistant responses from the session store, formatting them as a clear dialogue transcript. The model choice matters here—use a model with strong instruction-following and structured output capabilities (such as GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro) because the decomposition task requires precise dependency tracking. Set the temperature low (0.0–0.2) to maximize deterministic, repeatable sub-question generation across identical inputs.

The output must be parsed as structured JSON containing an array of sub-question objects, each with a question string, a dependency field indicating which prior sub-question index it depends on (or null if independent), and a rationale explaining the decomposition logic. Implement a post-processing validator that checks: (1) the output is valid JSON, (2) all dependency indices reference existing sub-questions, (3) no circular dependencies exist in the dependency graph, and (4) every sub-question is a self-contained, answerable query. If validation fails, retry the prompt once with the validation error appended as feedback. If the retry also fails, log the failure, fall back to treating the original user query as a single retrieval query, and flag the session for review. For high-stakes domains, route sessions with persistent decomposition failures to a human review queue rather than silently degrading.

Logging and observability are critical for debugging cross-turn dependency resolution. Log the full prompt input, the raw model output, the parsed sub-questions, the dependency graph, and any validation failures. Instrument metrics for decomposition depth (number of sub-questions generated), dependency chain length, validation pass rate, and retry frequency. These metrics will surface when the model over-decomposes simple queries, creates unnecessary dependencies, or fails to resolve anaphora from the conversation history. When deploying, start with a canary release on a subset of sessions and compare retrieval precision and answer completeness against a baseline that treats follow-up questions as standalone queries. If the decomposition step adds latency that violates your p95 targets, consider caching decomposition results for identical query-history pairs or using a smaller, faster model for simple single-hop queries detected by a lightweight classifier upstream.

PRACTICAL GUARDRAILS

Common Failure Modes

Session-aware sub-question generation fails in predictable ways. These failures stem from dependency resolution errors, context window mismanagement, and incorrect assumption carry-forward. Each card below identifies a specific failure mode and the guardrail that prevents it in production.

01

Phantom Dependency Creation

What to watch: The model invents a relationship between the current question and a prior turn that does not exist, creating a sub-question that chases a hallucinated dependency. This often occurs when the user shifts topics but the model overfits to session context. Guardrail: Include an explicit instruction to verify that each generated sub-question references only entities and facts explicitly established in prior turns. Add a validator that checks each sub-question's entities against a session entity set extracted from the conversation history.

02

Unresolved Anaphora in Sub-Questions

What to watch: The model generates sub-questions that still contain pronouns or referring expressions from the original follow-up, failing to resolve them against prior turns. This produces sub-questions that are not independently retrievable. Guardrail: Add a post-generation check that scans each sub-question for unresolved pronouns, demonstratives, and definite descriptions. If any remain, route the sub-question through a dedicated anaphora resolution prompt before retrieval execution.

03

Context Window Truncation of Critical Dependencies

What to watch: The conversation history is too long, and the turns that establish the dependencies needed for decomposition fall outside the context window. The model then generates sub-questions based on incomplete or missing dependency information. Guardrail: Implement a context pruning step that scores each prior turn for relevance to the current question before decomposition. Only include turns above a relevance threshold. Log which turns were included so operators can audit dependency completeness.

04

Over-Decomposition of Simple Follow-Ups

What to watch: The model breaks a straightforward follow-up question into too many sub-questions, introducing unnecessary retrieval steps that increase latency and compound error risk. This often happens when the decomposition prompt lacks a complexity threshold. Guardrail: Add a pre-decomposition classification step that assesses whether the follow-up requires decomposition at all. For simple clarifications or single-fact lookups, bypass decomposition and generate a single rewritten query instead.

05

Implicit Assumption Carry-Forward

What to watch: The model carries forward assumptions from prior turns that the user has implicitly revised or abandoned, generating sub-questions that reflect stale constraints. This is common when users correct themselves or change scope without explicit negation. Guardrail: Include a turn-by-turn assumption tracker in the prompt that lists active constraints and marks them as confirmed, revised, or abandoned. Require the model to reference this tracker when generating sub-questions and flag any sub-question that depends on an unconfirmed assumption.

06

Sub-Question Ordering Violations

What to watch: The model generates sub-questions in an order that violates dependency chains, placing a dependent sub-question before the sub-question that resolves its prerequisite. This breaks stepwise retrieval pipelines that execute sub-questions sequentially. Guardrail: Require the model to output sub-questions with explicit dependency labels and a topological sort instruction. Add a post-generation validator that checks the dependency graph for cycles and ordering violations, reordering sub-questions if necessary before execution.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Session-Aware Sub-Question Generation Prompt before shipping. Each criterion targets a specific failure mode in cross-turn dependency resolution. Run these checks against a golden dataset of multi-turn conversations with known dependencies.

CriterionPass StandardFailure SignalTest Method

Dependency Preservation

All sub-questions required to resolve anaphora or ellipsis from prior turns are present in the output

Missing sub-questions that would be required to resolve a pronoun or implicit reference from [CONVERSATION_HISTORY]

Compare generated sub-questions against a dependency graph extracted from the golden conversation. Flag any unresolved antecedent.

No Hallucinated Dependencies

Zero sub-questions reference entities, constraints, or topics not present in [CONVERSATION_HISTORY] or [CURRENT_QUESTION]

A generated sub-question introduces a filter, entity, or assumption not grounded in the session context

Diff extracted entities from generated sub-questions against a session entity list. Require human review for any novel entity.

Sub-Question Independence

Each sub-question can be answered independently without requiring the output of another sub-question in the same turn

A sub-question contains a reference like 'based on the answer to the previous question' or embeds a chained dependency

Parse each sub-question for intra-turn references. Flag any that require another sub-question's answer as input.

Complete Decomposition

The union of all generated sub-questions covers every information need expressed or implied in [CURRENT_QUESTION] given [CONVERSATION_HISTORY]

A required piece of information from the current question is not addressed by any sub-question

Map each clause and entity in [CURRENT_QUESTION] to at least one sub-question. Flag uncovered clauses.

No Redundant Sub-Questions

No two sub-questions request semantically identical information

Two sub-questions differ only in phrasing but would retrieve the same evidence

Compute pairwise semantic similarity across generated sub-questions. Flag pairs above a 0.9 cosine similarity threshold.

Temporal Reference Resolution

All relative time expressions are resolved to absolute ranges or explicit anchors using session context

A sub-question retains a relative term like 'last quarter' or 'recently' without grounding it to a concrete date range

Scan each sub-question for relative time tokens. Cross-reference against temporal anchors extracted from [CONVERSATION_HISTORY].

Entity Disambiguation

Ambiguous entity mentions are resolved to the correct canonical identifier based on prior turn context

A sub-question uses an ambiguous name without the qualifier or ID needed to distinguish it from other entities in the session

Check each entity mention against a session entity disambiguation map. Flag unresolved collisions.

Output Schema Compliance

Generated output strictly matches [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing required field, extra field, or incorrect type in the JSON output

Validate output against the JSON Schema defined in [OUTPUT_SCHEMA]. Reject on any schema violation and trigger retry.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single model call and minimal validation. Focus on getting the decomposition logic right before adding infrastructure. Start with a static conversation history window of 3-5 turns passed as [CONVERSATION_HISTORY] and a simple [CURRENT_QUESTION] input. Accept raw text output and manually inspect sub-question quality.

Watch for

  • Sub-questions that repeat the original question verbatim instead of decomposing it
  • Missing dependency markers between sub-questions (e.g., Q2 depends on Q1's answer)
  • Over-decomposition of simple follow-ups that don't need splitting
  • Hallucinated entities not present in the conversation history
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.