This prompt is for platform engineers and RAG architects who need to programmatically configure a multi-stage retrieval pipeline. Instead of manually wiring rewriters, expanders, and backend-specific query formatters for every query type, this prompt takes a user query and a registry of available retrieval components and produces a complete, executable configuration. Use this when you are building a retrieval orchestration layer that must dynamically assemble the right sequence of query transformations based on the query's intent, complexity, and the capabilities of your available indexes. This is not a prompt for rewriting a single query; it is a meta-configuration prompt that generates the plan for how a query should be processed.
Prompt
Retrieval Pipeline Configuration Prompt for Query Generation

When to Use This Prompt
Understand the job-to-be-done, the ideal user, and the boundaries for the Retrieval Pipeline Configuration Prompt.
The ideal user is an infrastructure engineer who already has a catalog of retrieval components—such as a dense vector rewriter, a BM25 keyword expander, a metadata filter extractor, and a graph traversal constructor—each with a known interface and capability description. The prompt requires a structured [COMPONENT_REGISTRY] that defines each component's name, input/output contract, and constraints. The output is a [PIPELINE_CONFIG] object that specifies the ordered sequence of components to invoke, the arguments to pass between them, and the final backend targets. This configuration should be directly executable by your orchestration engine without manual intervention.
Do not use this prompt when you have a single, static retrieval backend or when the query transformation logic is simple enough to be hardcoded. If your system only ever performs dense vector search with a single rewriter, a meta-configuration prompt adds unnecessary latency and complexity. Similarly, avoid this prompt for real-time, latency-critical paths where dynamic planning overhead is unacceptable; instead, precompute pipeline templates for known query classes. Finally, this prompt is not a substitute for a proper feature store or A/B testing framework—use it to generate candidate configurations, but always validate pipeline effectiveness against your retrieval metrics before promoting to production.
Use Case Fit
Where this prompt works and where it does not.
Good Fit: Heterogeneous Index Architectures
Use when: your retrieval pipeline spans dense vectors, sparse keywords, and graph traversals. This prompt produces a configuration that maps query intent to the right backend mix. Guardrail: validate that every backend referenced in the configuration is actually available and healthy before execution.
Bad Fit: Single-Backend Simplicity
Avoid when: you only have one retrieval index. The configuration overhead adds latency and complexity without benefit. Guardrail: use a single-strategy rewriter prompt instead. Reserve this prompt for pipelines with at least two distinct retrieval backends.
Required Inputs: Backend Registry and Query Type
What to watch: the prompt needs a current backend capability registry and a classified query type. Missing or stale backend metadata produces configurations that fail at runtime. Guardrail: maintain a machine-readable backend registry with schema, health status, and capability tags. Pass it as structured context.
Operational Risk: Configuration Drift
What to watch: backends change, indexes get reindexed, and schemas evolve. A configuration generated last week may reference a deprecated backend. Guardrail: version your backend registry, stamp each generated configuration with a registry version, and validate configurations against the current registry before execution.
Operational Risk: Pipeline Latency Budget
What to watch: the generated configuration may specify too many parallel or sequential backends, exceeding your latency budget. Guardrail: include a latency constraint in the prompt and validate the configuration's estimated fan-out against your SLO before deploying.
Operational Risk: Over-Configuration for Simple Queries
What to watch: the prompt may produce a multi-backend configuration for a query that only needs keyword search. Guardrail: pair this prompt with a query classifier. Route simple queries to single-strategy paths and reserve full pipeline configuration for complex or ambiguous queries.
Copy-Ready Prompt Template
A copy-ready prompt that generates a complete query generation configuration for a multi-stage retrieval pipeline, specifying which rewriters, expanders, and backends to invoke for a given query type.
This prompt template is designed to be pasted directly into your orchestration layer. It instructs the model to act as a retrieval pipeline architect, producing a structured configuration object that maps a user's query type to a specific set of rewriters, expanders, and target backends. The output is not a rewritten query, but a machine-readable plan for your retrieval dispatcher. Replace the square-bracket placeholders with your system's available components, constraints, and the specific user query you need to configure a pipeline for.
textYou are a retrieval pipeline configuration engine. Your task is to analyze a user query and produce a complete query generation configuration. This configuration specifies the exact sequence of rewriters, expanders, and target retrieval backends to invoke for this specific query type. ## Available Components - Rewriters: [AVAILABLE_REWRITERS] - Expanders: [AVAILABLE_EXPANDERS] - Backends: [AVAILABLE_BACKENDS] ## System Constraints - Maximum pipeline stages: [MAX_STAGES] - Latency budget: [LATENCY_BUDGET_MS] - Required backends for all queries: [REQUIRED_BACKENDS] - Forbidden components for this context: [FORBIDDEN_COMPONENTS] ## User Query [USER_QUERY] ## Output Schema Return a valid JSON object with the following structure: { "query_type": "string (classification of the query: factual, comparative, procedural, multi-hop, etc.)", "pipeline_stages": [ { "stage": "integer (execution order, starting from 1)", "component": "string (name of the rewriter, expander, or backend from the available lists)", "action": "rewrite | expand | retrieve", "target_backend": "string | null (required if action is 'retrieve')", "instructions": "string (brief, specific instruction for this stage's execution)" } ], "parallel_groups": [ ["integer (stage numbers that can run in parallel)"] ], "fallback_strategy": "string (description of what to do if primary retrieval returns zero results)", "rationale": "string (brief explanation of why this configuration was chosen for this query type)" } ## Constraints - Do not include components not listed in the available lists. - Respect the maximum pipeline stages limit. - Ensure all 'retrieve' actions specify a valid target_backend. - If the query is ambiguous, include a disambiguation rewriter as the first stage. - For multi-hop queries, ensure stages are ordered to resolve dependencies.
To adapt this template for your system, populate the [AVAILABLE_REWRITERS], [AVAILABLE_EXPANDERS], and [AVAILABLE_BACKENDS] placeholders with the exact names of the components registered in your retrieval dispatch layer. The model will only select from these lists, preventing hallucinated components. The [MAX_STAGES] and [LATENCY_BUDGET_MS] constraints enforce your production limits. After receiving the configuration, your application should validate the JSON against the output schema, confirm that all specified components exist in your registry, and reject any plan that references forbidden components or exceeds stage limits. For high-stakes pipelines, log the generated configuration alongside the query for auditability before execution.
Prompt Variables
Required inputs for the Retrieval Pipeline Configuration Prompt. Each placeholder must be populated before the prompt is sent. Missing or malformed inputs cause configuration generation failures.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY_TYPE] | Classifies the user question by complexity and retrieval need | multi-hop-comparison | Must match one of the defined query type enum values. Invalid types cause routing to default fallback strategy. |
[AVAILABLE_BACKENDS] | Lists retrieval backends with their capabilities and schemas | [{"type":"dense","index":"prod-emb-v3","dim":1536},{"type":"sparse","index":"bm25-main"}] | Must be a valid JSON array. Each backend entry requires type and index fields. Schema mismatch with downstream rewriters produces runtime errors. |
[REWRITER_REGISTRY] | Catalog of available query rewriters with their input and output contracts | [{"name":"synonym-expander","input":"raw-query","output":"expanded-query"}] | Must be a valid JSON array. Each rewriter entry requires name, input, and output fields. Missing rewriter references cause pipeline assembly failures. |
[EXPANDER_REGISTRY] | Catalog of available query expanders with their target backends | [{"name":"keyword-booster","target":"sparse","strategy":"term-weighting"}] | Must be a valid JSON array. Each expander entry requires name and target fields. Expander-to-backend mismatches produce invalid query formulations. |
[LATENCY_BUDGET_MS] | Maximum allowed end-to-end retrieval latency in milliseconds | 350 | Must be a positive integer. Budget violations during pipeline assembly should trigger strategy simplification or backend reduction. |
[RECALL_TARGET] | Minimum acceptable recall rate for the configured pipeline | 0.92 | Must be a float between 0.0 and 1.0. Pipelines that cannot meet the target with available backends should return a gap report rather than a degraded configuration. |
[PIPELINE_OUTPUT_SCHEMA] | Expected output format for the generated pipeline configuration | {"stages":[{"order":1,"rewriter":"intent-detector"}],"backends":["dense","sparse"]} | Must be a valid JSON schema definition. Schema validation failure on the generated configuration triggers retry with schema error feedback. |
[SESSION_CONTEXT] | Prior conversation turns for context-dependent query resolution | [{"role":"user","content":"Compare AWS and GCP pricing"}] | Optional. When present, must be an array of message objects with role and content fields. Null allowed for single-turn queries. |
Implementation Harness Notes
How to wire the Retrieval Pipeline Configuration Prompt into a production query generation service with validation, retries, and observability.
This prompt is designed to be called programmatically as part of a query planning service that sits between user input and your retrieval backends. The service receives a user query, classifies its type, and invokes this prompt to produce a complete pipeline configuration specifying which rewriters, expanders, and backends to use. The output is a structured JSON configuration object that downstream orchestrators consume to execute the retrieval pipeline. Wire this prompt into an API endpoint or a message queue consumer that accepts a [USER_QUERY] and an optional [QUERY_TYPE] hint, then returns the configuration to your retrieval dispatch layer.
Validation and Schema Enforcement: The prompt output must conform to a strict schema before any retrieval execution begins. Implement a JSON Schema validator that checks: (1) the pipeline_stages array contains only recognized stage types (rewrite, expand, backend_query), (2) each backend_query stage references a backend ID that exists in your infrastructure registry, (3) all required fields (stage_id, type, config) are present, and (4) dependency references between stages resolve correctly. If validation fails, log the failure with the raw output and the validation error, then retry the prompt once with the error message appended as a [CONSTRAINTS] update. If the retry also fails, fall back to a default pipeline configuration for the detected query type and alert the on-call channel.
Model Choice and Latency Budget: This is a planning prompt that runs once per user query before retrieval execution, so latency directly adds to the user's perceived wait time. Use a fast model with strong JSON output capabilities—GPT-4o-mini, Claude 3.5 Haiku, or a fine-tuned smaller model if you have sufficient training data. Set a strict timeout (500-800ms) and implement a circuit breaker: if the prompt exceeds the timeout or fails three times within a rolling window, short-circuit to a cached default configuration for that query type. Log every circuit-breaker activation with the query fingerprint for later analysis.
Observability and Logging: Attach a trace ID to every prompt invocation that propagates through the entire retrieval pipeline. Log the input query, the detected query type, the generated configuration, validation results, and the final backends invoked. This trace allows you to measure configuration accuracy by comparing the generated pipeline against retrieval quality metrics (recall@k, precision@k, answer faithfulness) downstream. Store these traces in your observability platform and build a dashboard that tracks configuration change frequency, validation failure rate, and pipeline latency by query type.
Testing and Evaluation: Before deploying changes to this prompt, run it against a golden dataset of 50-100 queries covering all your supported query types (factual lookup, comparison, summarization, procedural, multi-hop). For each test case, verify that the generated configuration invokes the correct backends and applies appropriate rewriters. Automate this as a CI check that blocks prompt changes if configuration accuracy drops below 90%. Additionally, run periodic shadow evaluations in production where you compare the generated configuration against a human-reviewed ideal configuration to detect drift.
What to Avoid: Do not call this prompt synchronously in the user request path without a timeout and fallback—pipeline planning failures should never block the user from getting results. Do not skip schema validation; malformed configurations will cause cascading failures in downstream orchestrators that are harder to debug. Do not treat this prompt's output as the final retrieval plan without checking that the specified backends are healthy and available at execution time—implement a pre-flight check that removes unavailable backends from the configuration before dispatching.
Expected Output Contract
Validation rules for the JSON configuration object generated by the Retrieval Pipeline Configuration Prompt. Use this contract to build a post-processing validator before the configuration is applied to your retrieval infrastructure.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
pipeline_name | string | Must match pattern ^[a-z0-9_-]+$. Reject if empty or contains spaces. | |
query_type | string | Must be one of the predefined enum values: factual_lookup, summarization, comparison, procedural, multi_hop. Reject unknown values. | |
rewriters | array of objects | Array must contain at least 1 item. Each object must have a valid 'type' field from the allowed rewriter registry. Reject if empty array. | |
rewriters[].type | string | Must match an entry in the allowed rewriter list: synonym_expansion, decomposition, metadata_extraction, intent_rewrite, disambiguation, temporal_normalization. Reject unknown types. | |
rewriters[].order | integer | Must be a positive integer. No duplicate order values allowed across rewriters. Reject if order is missing or duplicated. | |
rewriters[].config | object | If present, must conform to the schema registered for the rewriter type. Reject if config keys are unrecognized for the given type. | |
backends | array of objects | Array must contain at least 1 item. Each object must specify 'backend_type' and 'index_name'. Reject if empty array. | |
backends[].backend_type | string | Must be one of: dense_vector, sparse_keyword, graph, hybrid. Reject unknown backend types. | |
backends[].index_name | string | Must match pattern ^[a-z0-9_-]+$. Must correspond to a registered index in the deployment manifest. Reject if index is not found in manifest. | |
backends[].weight | number | If present, must be a float between 0.0 and 1.0. Sum of all backend weights must equal 1.0 if any weight is specified. Reject if sum != 1.0. | |
execution_strategy | string | Must be one of: parallel, sequential, cascading. If sequential, backends array order defines execution order. Reject unknown strategies. | |
fallback_policy | object | Must contain 'max_relaxation_steps' as a non-negative integer. Must contain 'result_threshold' as an integer >= 1. Reject if fields are missing or out of range. | |
fallback_policy.max_relaxation_steps | integer | Must be >= 0 and <= 5. Reject if outside bounds. | |
fallback_policy.result_threshold | integer | Must be >= 1. Reject if 0 or negative. | |
metadata_filters | object | If present, keys must match registered filterable fields in the target indexes. Values must be strings or arrays of strings. Reject if filter field is not in index schema. | |
output_normalization | object | Must contain 'deduplicate' as boolean and 'ranking_strategy' as string. Reject if fields are missing. | |
output_normalization.deduplicate | boolean | Must be true or false. Reject if string or null. | |
output_normalization.ranking_strategy | string | Must be one of: reciprocal_rank_fusion, weighted_sum, round_robin. Reject unknown strategies. |
Common Failure Modes
When a prompt generates a retrieval pipeline configuration instead of executing one, the failures shift from bad search results to bad instructions. These are the most common breakages and how to prevent them before they poison your retrieval quality.
Hallucinated Backend Capabilities
What to watch: The model invents index features, query operators, or filter syntax that your actual backends don't support. A generated config might specify vector_similarity: cosine when your dense index only supports dot product, or reference a graph_traversal backend that doesn't exist. Guardrail: Provide a strict backend capability schema as part of the prompt context. Validate all generated backend references and parameter values against an allowlist before the config is applied. Reject any config referencing unknown backends or unsupported parameters.
Pipeline Stage Ordering Errors
What to watch: The model arranges rewriters, expanders, and backend calls in an illogical or impossible sequence. For example, placing a metadata filter extraction step after the dense vector query has already been dispatched, or ordering a query relaxation stage before the primary retrieval attempt. Guardrail: Enforce a strict stage dependency graph in the output schema. Validate that each stage's inputs are produced by a preceding stage. Test generated pipelines against known valid topological orderings and reject configs with circular dependencies or missing prerequisites.
Over-Engineering for Simple Queries
What to watch: The model generates an expensive multi-stage pipeline with decomposition, expansion, and ensemble fusion for a simple factoid query like 'What is the capital of France?' This wastes compute, increases latency, and can introduce noise that degrades the final answer. Guardrail: Include a complexity classifier as the first logical stage in every generated config. Define explicit thresholds: simple queries route to a single backend, complex queries fan out. Test generated configs against a query complexity benchmark and flag any that apply multi-stage retrieval to simple lookups.
Under-Engineering for Compound Questions
What to watch: The model generates a single flat retrieval step for a multi-hop question like 'What was the revenue of the company that acquired our main competitor last year?' This produces irrelevant results because no single document contains the full answer chain. Guardrail: Require the prompt to explicitly detect multi-hop intent and generate a decomposition plan before backend assignment. Validate that generated configs for compound questions include at least one dependency edge between sub-queries. Test against a multi-hop question dataset and measure whether the config produces the necessary intermediate retrieval steps.
Schema Drift Between Config and Execution
What to watch: The generated config uses field names, parameter types, or output structures that don't match what the retrieval orchestrator expects at runtime. A config might output dense_query while the orchestrator expects vector_query, or pass a string where an array is required. Guardrail: Freeze the output schema with strict typing and field definitions in the prompt. Validate every generated config against the orchestrator's input contract before execution. Run a dry-run parse test in CI that catches schema mismatches before configs reach production.
Ignoring Query Context and Session State
What to watch: The model generates a pipeline config treating each query as isolated, ignoring conversation history, user role, or session context. A follow-up question like 'What about last year?' generates a generic retrieval plan instead of one that incorporates the entity and time context from prior turns. Guardrail: Require session context as a mandatory input field in the prompt template. Include explicit instructions to propagate resolved entities, time ranges, and filters from prior turns into the generated config. Test with multi-turn query sequences and verify that follow-up configs reference context from earlier turns.
Evaluation Rubric
Use this rubric to test the quality of a generated retrieval pipeline configuration before deploying it. Each criterion targets a specific failure mode observed in multi-backend query generation.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Backend Coverage | Every backend listed in [AVAILABLE_BACKENDS] is addressed with at least one rewriter or expander assignment | A backend is silently omitted from the configuration | Parse the output JSON; assert that the set of keys under 'backend_configs' matches the set of [AVAILABLE_BACKENDS] |
Rewriter Validity | All rewriter names used exist in [AVAILABLE_REWRITERS] and are applied to a compatible backend type | A rewriter designed for dense vectors is assigned to a sparse keyword backend | Validate each rewriter assignment against a compatibility matrix defined in [REWRITER_COMPATIBILITY]; flag any mismatches |
Query Type Routing | The configuration includes a routing rule for each query type listed in [QUERY_TYPES] | A query type like 'temporal' or 'comparative' has no routing entry, causing fallback to a default that may be suboptimal | Check that the 'routing_table' object contains a key for every element in [QUERY_TYPES] |
Pipeline Ordering | Multi-stage pipelines specify a strict execution order with explicit dependencies where required | Two independent stages are chained sequentially, or a dependent stage lacks a 'requires' field | Traverse the 'pipeline_stages' array; confirm that any stage with a 'requires' field references a valid prior stage ID |
Constraint Propagation | Global constraints from [CONSTRAINTS] (e.g., max latency, min recall) are reflected in per-backend settings | A global latency budget of 200ms is ignored, and a backend is configured with a 500ms timeout | Extract all numeric constraints from [CONSTRAINTS]; assert that each backend's 'timeout_ms' and 'top_k' values are within the global bounds |
Fallback Configuration | A fallback strategy is defined for each backend, specifying a relaxed variant or an alternative backend | The configuration has no fallback for a sparse index, risking an empty result set on zero keyword matches | Check that every entry in 'backend_configs' includes a non-null 'fallback' object with a valid 'strategy' field |
Schema Compliance | The output strictly matches [OUTPUT_SCHEMA] with all required fields present and no extra fields | An additional 'notes' field is added, or the required 'pipeline_id' field is missing | Validate the JSON output against [OUTPUT_SCHEMA] using a JSON Schema validator; reject on any additional properties or missing required fields |
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 single backend target and minimal validation. Replace the multi-backend configuration schema with a flat list of rewriter instructions. Remove the pipeline efficiency tests and focus only on configuration correctness.
Simplify the output to a single JSON object with rewriters, backends, and query_type fields. Drop the pipeline_efficiency and fallback_plan sections.
Watch for
- Missing schema checks causing downstream parsing failures
- Overly broad
query_typeclassification collapsing distinct query patterns - No validation that specified backends actually exist in your infrastructure
- Rewriter ordering that produces nonsensical intermediate queries

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