Inferensys

Prompt

Retrieval Strategy Dispatch Prompt Template

A practical prompt playbook for using the Retrieval Strategy Dispatch Prompt Template in production AI workflows. Classifies a user query by complexity and intent, then selects the appropriate retrieval strategy and backend combination.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and boundaries for the Retrieval Strategy Dispatch Prompt Template.

This prompt is for orchestration engineers building retrieval routing layers in RAG systems. Its job is to act as a dispatcher: it receives a raw user query, classifies its intent and complexity, and outputs a structured decision that maps the query to the correct retrieval strategy and backend combination. Use this prompt when your system has multiple retrieval paths (dense vector, sparse keyword, graph, hybrid) and you need a single classification step to avoid sending every query to every backend. The ideal user is an infrastructure or platform engineer who already understands the available retrieval backends and their performance characteristics, and who needs a deterministic, auditable routing decision before query execution.

This prompt assumes you have already defined your available strategies and backends and can pass them as context. You must provide a catalog of retrieval strategies, each with a name, description, supported backends, and typical query patterns they handle. The prompt works best when the strategy catalog is stable and well-documented, because the model's classification accuracy depends on clear strategy definitions. Do not use this prompt when you have only one retrieval backend or when the retrieval strategy is static—a simple if-else rule in application code is cheaper, faster, and more reliable. Do not use this prompt for real-time latency-sensitive paths where sub-10ms decisions are required; model inference adds latency that may violate your SLO. Do not use this prompt when the query itself contains the routing signal in a structured field (e.g., a search_type parameter from the UI), because deterministic routing is always preferred over model-based classification.

Before deploying this prompt, you must define evaluation criteria for classification accuracy. Build a golden dataset of at least 100 queries with human-labeled strategy assignments, and measure whether the prompt's output matches the expected strategy and backend combination. Common failure modes include over-selecting the hybrid strategy for simple keyword queries, misclassifying comparative questions as factoid lookups, and failing to recognize multi-hop queries that require graph traversal. Plan for a human review step when the model's confidence is low or when the query falls into an undefined strategy gap. The next section provides the copy-ready prompt template you can adapt with your own strategy catalog and output schema.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Retrieval Strategy Dispatch Prompt works, where it fails, and what you need before deploying it in a production retrieval pipeline.

01

Good Fit: Heterogeneous Retrieval Architectures

Use when: your system has multiple backends (dense, sparse, graph) and needs per-query routing decisions. Guardrail: validate that each backend referenced in the dispatch output actually exists and is reachable before executing the strategy.

02

Bad Fit: Single-Backend Setups

Avoid when: you only have one retrieval index. A dispatch prompt adds latency and complexity without benefit. Guardrail: use a simple query rewriter instead; only introduce dispatch when you have at least two distinct backends with different strengths.

03

Required Input: Backend Capability Schema

Risk: the model invents backends or capabilities that don't exist. Guardrail: provide a strict, enumerated schema of available backends, their strengths, index types, and constraints as part of the prompt context. Never let the model hallucinate retrieval paths.

04

Required Input: Query Complexity Taxonomy

Risk: inconsistent classification of what counts as 'complex' vs 'simple' across calls. Guardrail: define explicit complexity categories (factoid lookup, comparison, multi-hop, temporal, procedural) with concrete examples so the dispatch decision is reproducible.

05

Operational Risk: Dispatch Latency Budget

Risk: adding a classification step before retrieval increases end-to-end latency, especially problematic for real-time applications. Guardrail: set a timeout on the dispatch call and fall back to a default hybrid strategy if classification exceeds the latency budget.

06

Operational Risk: Strategy Drift Over Time

Risk: as backends evolve or new indexes are added, the dispatch prompt's classification logic becomes stale and routes queries suboptimally. Guardrail: log dispatch decisions and periodically audit a sample against retrieval quality metrics; retest the prompt when backend configurations change.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready template for classifying a user query and dispatching it to the correct retrieval strategy and backend combination.

This template is the core dispatch instruction for your retrieval routing layer. It forces the model to analyze the user's query for complexity, intent, and required capabilities before selecting a strategy. You must replace the square-bracket placeholders with your system's specific retrieval strategies, backend definitions, and routing rules. The template is designed to be stateless and can be called on every user turn before any retrieval is executed.

text
You are a retrieval strategy router. Your job is to analyze a user query and select the most appropriate retrieval strategy and backend combination.

## Available Strategies
[STRATEGY_LIST]

## Available Backends
[BACKEND_LIST]

## Routing Rules
[ROUTING_RULES]

## Input
User Query: [USER_QUERY]
Conversation History (last 3 turns): [CONVERSATION_HISTORY]

## Task
1. Classify the query's primary intent and complexity.
2. Select exactly one strategy from the available list.
3. Select one or more backends required to execute that strategy.
4. Provide a brief justification for your selection.
5. If the query is ambiguous, select the strategy that requests clarification instead of guessing.

## Output Format
Return a valid JSON object with this exact schema:
{
  "classification": {
    "intent": "string",
    "complexity": "simple|moderate|complex",
    "is_ambiguous": boolean
  },
  "selected_strategy": "string",
  "selected_backends": ["string"],
  "justification": "string",
  "requires_clarification": boolean
}

## Constraints
- Do not execute retrieval. Only classify and route.
- If the query contains multiple intents, select the strategy that handles the dominant intent.
- For queries requiring real-time data, prefer backends marked as 'live'.
- For queries with explicit time constraints, include the temporal backend if available.
- If no strategy clearly matches, default to [FALLBACK_STRATEGY].

To adapt this template, start by defining your [STRATEGY_LIST] with clear, mutually exclusive options such as factoid_qa, summarization, comparison, multi_hop, temporal, or clarification_needed. Each strategy should map to a known retrieval pipeline. Your [BACKEND_LIST] should enumerate the actual indexes available, like dense_vector, sparse_keyword, graph_traversal, or hybrid. The [ROUTING_RULES] section is where you encode business logic, such as 'route all compliance queries to the policy backend' or 'queries shorter than 5 words are ambiguous by default.' After copying the template, immediately write a validation function that checks the output JSON against your actual strategy and backend enums to prevent hallucinated routing targets from reaching production.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Retrieval Strategy Dispatch prompt needs to classify a query and select the correct retrieval backend. Validate each before sending the request to prevent routing errors.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw natural language question to classify and route

What are the side effects of drug X?

Required. Must be a non-empty string. Check for injection attempts or command-like strings before passing.

[AVAILABLE_STRATEGIES]

A list of retrieval backends and their descriptions the model can choose from

dense_vector, sparse_keyword, graph_traversal, hybrid_fusion

Required. Must be a valid list of strings. Each entry must map to an operational backend. Null or empty list should abort dispatch.

[STRATEGY_SCHEMA]

The JSON schema defining the expected output structure for the selected strategy

{"strategy": "string", "confidence": "float", "rationale": "string"}

Required. Must be a valid JSON Schema object. Validate with a schema parser before injection. A malformed schema will cause output parsing failures.

[QUERY_HISTORY]

The last N user and assistant turns for context-dependent routing decisions

[{"role": "user", "content": "Tell me about drug X."}]

Optional. If provided, must be a valid JSON array of message objects with role and content keys. Truncate to the last 5 turns to manage context window.

[USER_ROLE]

The access scope or persona of the user making the request, used for permission-aware routing

physician

Optional. If provided, must be a string matching a known role in the authorization system. An unknown role should default to a least-privilege strategy.

[ROUTING_RULES]

Hard constraints that override model discretion, such as mandatory strategies for specific query types

If query contains PII, route to sparse_keyword only.

Optional. If provided, must be a list of clear, parseable rules. Rules are applied post-classification as a safety net. Log any rule-triggered overrides.

[MODEL_CAPABILITIES]

A description of the model's known strengths and weaknesses for self-assessment

Accurate for medical terminology; may miss recent slang.

Optional. If provided, must be a string. Used to calibrate the confidence score. An empty string should not cause a failure.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Retrieval Strategy Dispatch Prompt into a production retrieval pipeline with validation, routing, and observability.

The dispatch prompt is not a standalone component; it is the decision layer in a retrieval routing architecture. In production, this prompt sits between the user input and the retrieval backends. Its output—a strategy label and a set of backend assignments—must be parsed, validated, and used to invoke the correct downstream query rewriters and indexes. The harness should treat the LLM's classification as a control signal, not as the final answer. This means the application layer must enforce the dispatch decision, not trust it blindly.

Wire the prompt into a dispatch handler that receives the raw user query and any available session context. The handler constructs the prompt with the [USER_QUERY], [AVAILABLE_BACKENDS], and [SESSION_CONTEXT] placeholders populated from your retrieval infrastructure's capability registry and the current conversation state. After the LLM returns a classification, validate the output against a known schema: the strategy field must match one of your enumerated strategy types (e.g., factual_lookup, comparative_analysis, procedural_retrieval), and each entry in backends must reference a backend ID that exists in your live configuration. Reject any output that references unknown backends or strategies. On validation failure, retry once with the error injected into the prompt as [PREVIOUS_ERROR]. If the retry also fails, fall back to a safe default strategy (typically hybrid dense-plus-sparse) and log the incident for review.

Logging and observability are critical because dispatch errors cascade into every downstream retrieval step. Log the raw user query, the dispatch prompt version, the model's full classification output, the validation result, any retry attempts, and the final strategy selected. Tag each log entry with a trace ID that follows through to the retrieval backends and the final answer generation. This lets you measure dispatch accuracy by comparing the selected strategy against retrieval quality metrics (recall, precision, answer faithfulness) in your eval pipeline. If you observe that certain query types are consistently misclassified, use those logs to build few-shot examples or fine-tuning data for the dispatch prompt.

Model choice matters for latency and cost. The dispatch prompt is a classification task with a constrained output schema. In most cases, a fast, smaller model (such as GPT-4o-mini, Claude Haiku, or a fine-tuned open-weight model) is sufficient and keeps dispatch latency under 200ms. Reserve larger models for cases where the dispatch prompt must reason about ambiguous or multi-intent queries. Implement a circuit breaker that monitors dispatch latency and error rates; if the dispatch model exceeds your latency budget or error threshold, cut over to a static routing rule (e.g., always use hybrid retrieval) until the model endpoint recovers. Never let a dispatch failure block the user from getting results.

Before shipping, build a golden eval set of at least 200 queries covering each strategy type, edge cases (ambiguous queries, multi-intent questions, out-of-domain inputs), and failure modes you expect in production. For each query, define the expected strategy and acceptable backend assignments. Run this eval set against every prompt change and model upgrade. Track classification accuracy per strategy type, not just overall accuracy—a prompt that scores 95% overall but misclassifies all procedural queries is not ready for production. If your retrieval pipeline serves regulated or high-risk domains, add a human review step for dispatch decisions where the model confidence is below a threshold or where the selected strategy differs from the previous version's choice.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, data types, and validation rules for the JSON response returned by the Retrieval Strategy Dispatch Prompt. Use this contract to parse and validate the model output before routing the query to the selected retrieval backend.

Field or ElementType or FormatRequiredValidation Rule

classification.primary_intent

string (enum)

Must match one of: factual_lookup, summarization, comparison, procedural, exploratory, multi_hop. Reject unknown values.

classification.complexity

string (enum)

Must be simple, moderate, or complex. If multi_hop, complexity must be complex.

classification.requires_filters

boolean

Must be true if any metadata constraints are detected in the query; otherwise false.

selected_strategy

string (enum)

Must be one of: dense_only, sparse_only, hybrid, graph_traversal, decomposition_then_retrieve. Strategy must align with primary_intent mapping rules.

strategy_rationale

string

Non-empty string under 300 characters. Must reference at least one query characteristic that justifies the strategy choice.

target_backends

array of strings

Non-empty array. Allowed values: vector_db, keyword_index, knowledge_graph, document_store. Must include at least one backend compatible with selected_strategy.

confidence

number

Float between 0.0 and 1.0. If below 0.7, the caller should consider a fallback or human review path.

fallback_strategy

string (enum) or null

If confidence is below 0.7, this field is required and must contain a valid strategy enum. Otherwise, null is allowed.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when a Retrieval Strategy Dispatch prompt runs in production, and how to prevent misclassification, backend mismatch, and silent degradation.

01

Intent Misclassification Causes Wrong Backend Selection

What to watch: The prompt classifies a factual lookup as a comparison or a procedural query as a summarization task, routing it to a backend that cannot satisfy the real user need. This is the most common production failure and produces answers that look plausible but are structurally wrong. Guardrail: Include a confidence threshold in the output schema. When classification confidence is below 0.8, fall back to a multi-backend fan-out or escalate for human review. Log all low-confidence classifications for prompt improvement.

02

Over-Specific Strategy Selection Misses Available Evidence

What to watch: The prompt selects a single backend strategy when the query would benefit from hybrid retrieval. For example, routing a query with both semantic and temporal constraints to a dense-only index loses the time-range filtering capability. Guardrail: Add a hybrid fallback rule: if the query contains both conceptual language and explicit constraints, dispatch to both dense and sparse backends and fuse results. Test with queries that mix abstract and concrete requirements.

03

Ambiguous Queries Receive Arbitrary Routing Decisions

What to watch: When a user query is genuinely ambiguous, the prompt picks a strategy based on superficial signals rather than requesting clarification. This produces confident-looking answers to misunderstood questions. Guardrail: Add an ambiguity detection step before strategy selection. If multiple intents are equally plausible, output a clarification request instead of a strategy choice. Include an ambiguity_detected boolean in the output schema.

04

Strategy Drift Under Load Causes Inconsistent Routing

What to watch: Under high throughput or with slight input variations, the same query type gets routed to different backends across requests. Users see inconsistent behavior for similar questions, eroding trust. Guardrail: Cache strategy decisions for canonical query patterns and compare new classifications against cached decisions. Log routing changes with the diff for review. Use few-shot examples that demonstrate consistent routing for boundary cases.

05

Backend Capability Assumptions Become Stale

What to watch: The prompt encodes assumptions about backend capabilities that drift over time. A backend gains new features, an index schema changes, or a retriever is deprecated. The dispatch prompt keeps routing queries to backends that no longer serve them well. Guardrail: Version the backend capability context block separately from the dispatch logic. Validate capability descriptions against actual backend configurations in CI. Include a backend_version field in the output for traceability.

06

Compound Queries Get Single-Strategy Dispatch

What to watch: A user asks a question that requires multiple retrieval strategies in sequence, but the prompt selects only one. For example, 'Compare our Q2 revenue to competitors and explain the trend' needs factual retrieval, entity extraction, and comparison—not just one backend. Guardrail: Add a decomposition check before final strategy selection. If the query contains multiple clauses with different retrieval needs, output a strategy plan with ordered steps rather than a single backend choice. Test with multi-clause queries.

IMPLEMENTATION TABLE

Evaluation Rubric

How to test output quality before shipping. Run these checks against a golden dataset of at least 50 labeled queries covering all defined strategies.

CriterionPass StandardFailure SignalTest Method

Strategy Classification Accuracy

Selected strategy matches the ground-truth label for at least 90% of queries in the golden dataset

Strategy mismatch on more than 5 out of 50 queries; confusion between semantically adjacent strategies (e.g., FACTUAL_LOOKUP vs DEFINITION)

Run the prompt against the golden dataset; compute exact-match accuracy and confusion matrix; flag any strategy pair with >10% mutual misclassification

Intent Boundary Adherence

Prompt does not hallucinate strategy names outside the defined [STRATEGY_CATALOG]; output is always one of the allowed enum values

Output contains an unlisted strategy string or a fabricated label not present in the allowed strategy set

Parse the output field against the allowed enum list; any value not in the set is an automatic failure; run a schema validator on every response

Confidence Score Calibration

Confidence score correlates with classification correctness; low-confidence predictions (<0.7) are more likely to be incorrect than high-confidence predictions (>=0.9)

High-confidence predictions are frequently wrong, or low-confidence predictions are rarely wrong, indicating miscalibration

Bucket predictions by confidence decile; plot expected vs observed accuracy per bucket; acceptable if no bucket deviates by more than 15 percentage points

Rationale Grounding

Rationale references specific query features (entities, verbs, structure) that justify the chosen strategy; no generic or circular reasoning

Rationale repeats the strategy name as justification (e.g., 'This is a comparison query because it compares things') or cites features not present in the query

Human review of 20 sampled rationales; pass if >=85% contain at least one query-specific feature reference and zero circular justifications

Multi-Intent Query Handling

For queries with multiple detectable intents, the prompt selects the dominant strategy or returns a ranked list; does not oscillate or return null

Prompt returns null, empty strategy, or alternates between two strategies on repeated identical calls for the same multi-intent query

Include 10 multi-intent queries in the golden set; run each 3 times; pass if strategy is non-null and consistent (same top choice) across >=80% of repeated runs

Edge Case Robustness

Prompt handles empty queries, single-word queries, non-English queries, and queries with only stop words by returning a defined fallback strategy (e.g., CLARIFY or DEFAULT_SEARCH)

Prompt crashes, returns unparseable output, or selects an inappropriate high-specificity strategy for an underspecified query

Create an edge-case subset of 15 queries; pass if 100% return a valid strategy from the catalog and >=80% select the designated fallback or a reasonable low-specificity alternative

Output Schema Compliance

Every response is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing required fields, wrong types (e.g., string instead of number for confidence), or unparseable JSON

Validate every golden-dataset response with a JSON schema validator; pass if 100% of responses are valid; any schema violation is a release blocker

Latency Budget Adherence

Prompt completes within the defined latency budget (e.g., <500ms p95) under expected production load

p95 latency exceeds budget by more than 20% or timeout rate exceeds 1%

Benchmark with 100 concurrent requests against a production-like endpoint; measure p50, p95, p99 latency and timeout rate; compare against [LATENCY_BUDGET_MS]

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict output schema with enum validation on strategy labels. Include a confidence field and a fallback strategy when confidence is below threshold. Wrap the dispatch call in a retry loop that validates the JSON schema before accepting the response. Log every classification decision with query hash, selected strategy, confidence, and latency for offline eval.

code
Analyze [QUERY] and classify into one of: [DENSE_VECTOR, SPARSE_KEYWORD, HYBRID, GRAPH_TRAVERSAL, MULTI_HOP].
Return strict JSON:
{
  "primary_strategy": "<enum>",
  "confidence": 0.0-1.0,
  "fallback_strategy": "<enum>",
  "rationale": "<string>"
}
If confidence < 0.7, default to HYBRID.

Watch for

  • Silent format drift when the model adds extra fields or changes enum casing
  • Confidence scores that are consistently high but wrong—add eval against human-labeled strategy choices
  • Retry loops that mask systemic misclassification by eventually returning valid JSON with bad content
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.