Inferensys

Prompt

Agentic Query Plan Generation Prompt

A practical prompt playbook for using Agentic Query Plan Generation Prompt in production AI workflows.
Developer designing multi-agent workflow on laptop, architecture diagram on screen, casual home office setup with afternoon light.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the ideal job-to-be-done, target user, and clear boundaries for the Agentic Query Plan Generation Prompt.

This prompt is for agent builders who need to convert a complex, multi-faceted user objective into a dynamic, stepwise research plan. It is designed for systems where the agent has access to multiple tools—such as search, database query, code execution, or internal APIs—and must decide which tool to use, what query to send, and what evidence to expect at each step. The ideal user is an AI engineer or technical decision maker building an autonomous or semi-autonomous agent that cannot resolve a user's request in a single retrieval round. The required context includes a clear user objective, a defined set of available tools with their capabilities, and an understanding of the evidence types needed to satisfy the objective.

Use this prompt when a single retrieval round is insufficient and the agent must orchestrate a sequence of information-gathering actions. It is appropriate for multi-hop research tasks, comparative analyses requiring data from disparate sources, diagnostic workflows that must rule out causes sequentially, or any objective where the retrieval strategy must adapt based on intermediate findings. The prompt includes a built-in plan validation check that verifies each step's query is answerable by its assigned tool, and a replanning trigger that activates when initial steps return insufficient or contradictory results. This makes it suitable for production systems where the cost of a bad plan is high and the agent must self-correct.

Do not use this prompt for simple factual lookups, single-hop Q&A, or workflows where the retrieval strategy is static and known in advance. If the user's question can be answered by a single well-formed search query, a standard RAG prompt with query rewriting is more efficient and less error-prone. Avoid this prompt when the tool set is a single vector database with no functional variation between queries, as the planning overhead adds latency without improving results. Also avoid it in latency-critical applications where the planning step itself introduces unacceptable delay, unless you implement plan caching for repeated objective types. For high-risk domains such as healthcare or legal, always route the generated plan through a human reviewer before execution, and ensure each step's evidence is logged for auditability.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Agentic Query Plan Generation Prompt works well and where it introduces risk. This prompt is designed for complex, multi-step research objectives that require tool orchestration, not for simple fact retrieval or single-hop questions.

01

Good Fit: Multi-Step Research Objectives

Use when: The user's objective requires gathering evidence from multiple sources, tools, or indexes before a final answer can be synthesized. Why: The prompt produces a stepwise plan with explicit tool assignments, making it ideal for agentic RAG pipelines where a flat retrieval call would miss dependencies.

02

Bad Fit: Simple Fact Retrieval

Avoid when: The user asks a single-hop question answerable from one search call. Risk: The prompt will over-engineer a multi-step plan, adding latency and token cost for no benefit. Guardrail: Route simple queries to a direct RAG prompt and only invoke this planner when complexity is detected by an upstream classifier.

03

Required Inputs

What you must provide: A complex user objective, a list of available tools with their descriptions and argument schemas, and any known constraints or domain context. Risk: Without accurate tool definitions, the planner will hallucinate tool names or arguments, breaking the agent execution loop.

04

Operational Risk: Plan Drift

What to watch: The generated plan may become invalid after the first few retrieval steps if intermediate results change the understanding of the problem. Guardrail: Implement a replanning trigger that re-invokes this prompt with the original objective plus accumulated evidence when a step returns insufficient or surprising results.

05

Operational Risk: Infinite Loops

What to watch: The replanning trigger can cause the agent to cycle indefinitely if the plan never converges. Guardrail: Set a hard maximum on replanning iterations and a total step budget. If exceeded, force the agent to synthesize a best-effort answer from partial evidence and escalate for human review.

06

Latency and Cost Sensitivity

What to watch: Each planning call adds latency and LLM token cost before any retrieval work begins. Guardrail: Cache plans for similar objectives, use a faster model for plan generation than for final synthesis, and skip the planner entirely for objectives that match a known, pre-validated plan template.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that generates a dynamic, stepwise research plan from a complex objective, specifying the query, target tool, and expected evidence for each step.

This prompt template is the core of the Agentic Query Plan Generation workflow. It instructs the model to act as a research planner, decomposing a complex objective into a sequence of discrete, executable steps. Each step must declare its own query, the tool it targets, and the evidence it expects to find. The prompt includes a built-in validation step and a replanning trigger, making it suitable for use inside an agent loop where retrieval results can be fed back for plan adjustment.

text
You are an expert research planner. Your task is to create a dynamic, stepwise research plan to achieve a complex objective. You have access to a set of tools, each with a specific capability. Your plan must be executable by an agent that can use these tools one step at a time.

**Objective:** [OBJECTIVE]

**Available Tools:**
[TOOLS]

**Instructions:**
1.  **Decompose the Objective:** Break down the objective into a sequence of discrete, independently executable steps. Each step should gather a specific piece of evidence needed to answer the main question.
2.  **Define Each Step:** For every step, provide the following in a strict JSON format:
    *   `step_id`: A unique integer for the step, starting from 1.
    *   `description`: A brief, human-readable explanation of what this step aims to accomplish.
    *   `query`: The exact string query to be executed by the target tool.
    *   `target_tool`: The name of the tool from the available list that is best suited for this query.
    *   `expected_evidence`: A clear description of the type of information this step should return if successful.
    *   `depends_on`: A list of `step_id`s that must be completed before this step can begin. Use an empty list `[]` if there are no dependencies.
3.  **Plan Validation:** After generating the plan, add a final step (`step_id: "validation"`) that is not a query. This step must contain a `validation_check` field with a boolean question: "Does this plan, if executed successfully, gather all necessary evidence to fully answer the objective?" and a `replanning_trigger` field with a string instruction: "If any step returns insufficient or irrelevant results, identify the evidence gap and generate a new plan to fill it, starting from the last successful step."

**Output Format:**
Return your entire response as a single, valid JSON object with a key `research_plan` containing an array of step objects. Do not include any text outside the JSON.

```json
{
  "research_plan": [
    {
      "step_id": 1,
      "description": "...",
      "query": "...",
      "target_tool": "...",
      "expected_evidence": "...",
      "depends_on": []
    },
    ...
    {
      "step_id": "validation",
      "validation_check": "...",
      "replanning_trigger": "..."
    }
  ]
}

To adapt this template, replace the [OBJECTIVE] and [TOOLS] placeholders. The [TOOLS] input should be a clear description of each tool's name and function, for example: 1. search_knowledge_base(query: str) -> list[Document]: Retrieves internal documents. 2. web_search(query: str) -> list[Result]: Searches the public web. The strict JSON output contract is critical for a downstream agent harness to parse and execute the plan. The validation step is not optional; it forces the model to self-critique the plan's completeness before execution begins, and the replanning trigger provides a clear, programmatic entry point for the agent to loop back if a step fails. When implementing, ensure your parser can handle the validation step as a special object that does not contain a query field.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Agentic Query Plan Generation Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[USER_OBJECTIVE]

The complex, multi-part question or research goal the agent must plan for.

Compare the pricing models, compliance certifications, and data residency options of AWS, Azure, and GCP for a healthcare SaaS startup.

Check that the string is non-empty, contains at least one interrogative or directive phrase, and exceeds 20 characters. Reject single-token or trivial queries.

[AVAILABLE_TOOLS]

A structured list of tools the agent can use, each with a name, description, and input schema.

[{"name": "vector_search", "description": "Semantic search over internal docs", "parameters": {"query": "string", "top_k": "int"}}]

Validate that the input is a valid JSON array. Each tool object must have non-empty 'name' and 'description' fields. Reject if the array is empty.

[CONSTRAINTS]

Operational limits such as max plan steps, forbidden actions, required confirmation gates, or timeouts.

Maximum 5 steps. Do not search external websites. Require human approval before any file write operation.

Parse as a string or list of strings. Check for the presence of at least one explicit boundary (step limit, tool restriction, or approval rule). Null is allowed if no constraints exist.

[OUTPUT_SCHEMA]

The exact JSON schema the plan output must conform to, including fields for step_id, query, tool, expected_evidence, and dependencies.

{"type": "object", "properties": {"steps": {"type": "array", "items": {"type": "object", "properties": {"step_id": {"type": "integer"}}}}}}

Validate that the input is a valid JSON Schema object. Confirm it includes required fields for step-level output. Reject if the schema is missing or unparseable.

[PRIOR_KNOWLEDGE]

Optional context already known about the domain, entities, or previous partial results that should inform the plan.

The user's company is SOC 2 Type II certified and operates in the EU. AWS was previously evaluated for compute but not for compliance.

Null is allowed. If provided, check that the string is non-empty and does not exceed the context window budget. Trim or summarize if it exceeds 2000 tokens.

[REPLAN_TRIGGER_CONDITION]

The specific condition that should cause the agent to regenerate the plan after a retrieval step returns insufficient results.

If any step returns fewer than 3 relevant documents or a confidence score below 0.7, mark the step as incomplete and generate a revised plan for the remaining objective.

Validate that the condition is a non-empty string describing a measurable threshold. Check for the presence of a numeric or boolean trigger. Reject vague triggers like 'if results are bad'.

[MAX_RETRIES]

The maximum number of times the agent is allowed to replan before escalating to a human or returning a partial answer.

3

Parse as an integer. Must be between 1 and 10. Reject values of 0 or negative numbers. Default to 3 if null.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Agentic Query Plan Generation Prompt into a tool-using agent application with validation, retries, and replanning logic.

The Agentic Query Plan Generation Prompt is designed to be called by an orchestrator agent at the start of a complex research task. The orchestrator should pass the user's objective, a list of available tools with their descriptions and input schemas, and any known constraints into the prompt's [OBJECTIVE], [AVAILABLE_TOOLS], and [CONSTRAINTS] placeholders. The model returns a structured JSON plan containing an ordered list of steps, each specifying a tool_name, query, and expected_evidence_type. This plan becomes the execution loop's work queue. Do not treat this prompt as a one-shot answer generator; its output is a machine-readable plan, not a final response to the user.

The implementation harness must parse the JSON output into a plan object and validate it before execution begins. At minimum, validate that every tool_name in the plan exists in the [AVAILABLE_TOOLS] list, that no step depends on a step ID that does not exist, and that the plan is not empty. If validation fails, retry the prompt once with the validation error appended to the [CONSTRAINTS] field. After two failures, fall back to a simpler single-step retrieval or escalate to a human reviewer. During execution, the harness should iterate through steps in dependency order, calling each tool with the specified query and capturing the result. After each step, compare the returned evidence against the expected_evidence_type field. If the evidence is insufficient or off-target, trigger the replanning path: append the step's result and a note about the gap to the conversation context and call the prompt again to generate a revised plan for the remaining steps. Log every plan version, tool call, and replanning event for observability.

Model choice matters here. Use a model with strong instruction-following and JSON output capabilities, such as Claude 3.5 Sonnet or GPT-4o, and set response_format to json_object or use the model's structured output API with the plan schema. The plan schema should include fields for plan_id, steps (array of objects with step_id, tool_name, query, depends_on, expected_evidence_type), and a stop_condition describing when the plan is complete. Implement a maximum step limit (e.g., 10 steps) and a maximum replanning count (e.g., 2 replans) to prevent runaway loops. For high-stakes domains, insert a human approval gate after plan generation but before tool execution, showing the reviewer the proposed steps and allowing them to edit or reject the plan. Never execute tools that modify external state without explicit confirmation. The harness should also track which evidence sources were used and attach them to the final synthesized answer for downstream citation and audit.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the JSON schema for the agentic query plan. Each step must pass these validation rules before execution.

Field or ElementType or FormatRequiredValidation Rule

plan_id

string (UUID v4)

Must match UUID v4 regex. Generated by the model.

objective

string

Non-empty. Must not be a verbatim copy of [USER_QUERY] if [USER_QUERY] is underspecified.

steps

array of objects

Minimum 1 item. Maximum [MAX_PLAN_STEPS] items. Array must not be empty.

steps[].step_id

integer

Sequential, starting at 1. Must be unique within the array.

steps[].query

string

Non-empty. Must differ from the raw [USER_QUERY] unless the plan has exactly 1 step.

steps[].tool

string

Must match an entry in [AVAILABLE_TOOLS] enum. No hallucinated tool names allowed.

steps[].expected_evidence

string

Non-empty. Describes the type of information this step should return (e.g., 'date range', 'entity definition').

steps[].depends_on

array of integers or null

If not null, every integer must reference a valid step_id from a prior step. No self-references or forward references.

PRACTICAL GUARDRAILS

Common Failure Modes

Agentic query plans fail in predictable ways. Here are the most common failure modes and the guardrails that catch them before they corrupt downstream retrieval or agent execution.

01

Plan Over-Specification

What to watch: The model generates an overly rigid plan with too many granular steps, creating unnecessary tool calls, latency, and compounding error risk. Each step becomes a failure point. Guardrail: Add a max_steps constraint in the prompt and require a rationale field for any step beyond a threshold. Validate the plan length before execution and reject plans exceeding the limit.

02

Missing Dependency Declaration

What to watch: A step references evidence from a prior step without declaring the dependency in the plan schema. The orchestrator executes steps in parallel, and the dependent step fails with missing context. Guardrail: Require an explicit depends_on_step_ids array in the output schema. Add a pre-execution validator that checks every referenced step ID exists and that no circular dependencies are present.

03

Tool Hallucination

What to watch: The plan specifies a tool name, endpoint, or parameter that does not exist in the available tool set. The agent fails at runtime with an unrecoverable error. Guardrail: Provide the exact tool manifest in the prompt context. Add a post-generation validation step that checks every tool_name against the allowed list and rejects plans with unknown tools before execution begins.

04

Vague Evidence Criteria

What to watch: Steps define expected evidence with phrases like 'relevant information' or 'sufficient detail,' making it impossible to programmatically determine if a step succeeded. The agent loops or proceeds with weak evidence. Guardrail: Require each step to specify concrete expected_evidence fields such as entity names, numeric ranges, or required fact types. Use an LLM judge after each retrieval round to score evidence against these criteria and trigger replanning on low scores.

05

Replanning Loop Death Spiral

What to watch: When evidence is insufficient, the replanning trigger generates a new plan that also fails, repeating indefinitely. Token costs explode and the system never returns a result. Guardrail: Implement a hard max_replans limit (typically 2-3). After the limit is reached, force the system to synthesize a best-effort answer from available evidence and flag the response with an incomplete_evidence warning rather than continuing to loop.

06

Context Starvation in Later Steps

What to watch: Early steps consume the context window with verbose retrieval results, leaving later steps with truncated or missing evidence. The final synthesis step operates on incomplete information. Guardrail: Enforce per-step evidence summarization before appending to the shared context. Add a context budget check before each step execution that estimates remaining token capacity and triggers evidence compression if the budget is below a threshold.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of generated query plans before integrating them into an agentic retrieval pipeline. Each criterion targets a specific failure mode common in dynamic plan generation.

CriterionPass StandardFailure SignalTest Method

Step Completeness

Plan covers all sub-questions required to fully answer the original objective without missing evidence dependencies.

Plan omits a necessary intermediate query or jumps directly to a conclusion without gathering prerequisite facts.

Manual review against a golden set of 10 complex objectives; check if any required evidence domain is absent from the plan steps.

Tool-Target Alignment

Each step specifies a target tool or index that is appropriate for the query type declared in that step.

A step requiring structured metadata filtering targets a dense vector index, or a fact-lookup step targets a document summary index.

Schema validation: map each step's target_tool field against a whitelist of available tools and their supported query types; flag mismatches.

Dependency Order Correctness

Steps that depend on prior results are correctly ordered and reference the correct upstream step ID.

A step references a dependency ID that does not exist, creates a circular dependency, or executes before its prerequisite.

Parse the dependency_graph field; check for cycles, missing IDs, and topological sort validity using a directed acyclic graph validator.

Expected Evidence Specificity

Each step's expected_evidence field describes a concrete, verifiable piece of information, not a vague restatement of the step's query.

Expected evidence reads as 'information about X' or 'answer to the question' rather than a specific fact, value, or relationship.

LLM-as-judge check: pass expected_evidence strings through a specificity classifier; fail if confidence in concreteness is below 0.8.

Replanning Trigger Validity

The replanning_condition field specifies a measurable signal that would indicate the current step's results are insufficient.

Replanning condition is null for a step that could plausibly return empty results, or describes a condition that cannot be evaluated programmatically.

Static analysis: verify replanning_condition is non-null for any step targeting an index with known coverage gaps; check that condition references a parseable output field.

Plan Length Constraint

Number of steps is between 2 and 7 for a single complex objective, avoiding both under-decomposition and over-fragmentation.

Plan contains 1 step for a multi-facet question, or more than 10 steps with single-fact granularity.

Count steps in generated plan; fail if count equals 1 for a known compound objective or exceeds 10 without a multi-hop justification in the plan rationale.

Original Objective Coverage

The union of all step queries and expected evidence fully addresses the original objective without extraneous off-topic steps.

Plan includes steps that answer a related but different question, or misses a core facet explicitly stated in the objective.

LLM-as-judge pairwise comparison: present original objective and generated plan summary; score coverage on a 1-5 scale; fail below 4.

Output Schema Compliance

The generated plan is valid JSON matching the required schema, including all mandatory fields for each step.

Plan JSON fails to parse, or a step object is missing the query, target_tool, or expected_evidence field.

Automated JSON schema validator run as a post-generation gate; reject any response that does not pass strict validation before downstream consumption.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet). Remove the plan_validation and replanning_trigger fields from the output schema. Accept the raw JSON plan without post-processing. Run 5-10 complex questions manually and inspect whether steps are logically ordered.

Prompt modification

code
Remove these fields from [OUTPUT_SCHEMA]:
- plan_validation
- replanning_trigger
- expected_evidence_type per step

Add: "If a step fails, note it in a comment field."

Watch for

  • Plans that skip dependency ordering entirely
  • Steps that combine multiple retrieval targets into one
  • No distinction between vector search, keyword search, and tool calls
  • Overly broad steps that can't produce discrete evidence
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.