This prompt is for search infrastructure teams and RAG orchestration engineers who manage multiple retrieval backends and need a reliable, automated way to decide which retrieval strategy to apply to a given user query. The prompt analyzes query characteristics such as specificity, entity density, natural language complexity, and temporal requirements to classify whether dense vector search, sparse keyword search, or a hybrid combination is optimal. Use this prompt inside a retrieval dispatch layer before query rewriting or index selection occurs. It is not a replacement for A/B testing your retrieval pipelines, nor does it handle the actual execution of the search. It is a decision component that reduces latency and cost by avoiding unnecessary multi-strategy retrieval for queries that a single backend can handle well.
Prompt
Vector vs Keyword vs Hybrid Query Decision Prompt

When to Use This Prompt
Identify the ideal deployment point for the vector vs. keyword vs. hybrid decision prompt within a retrieval dispatch layer.
The ideal user is an engineer who already has at least two retrieval backends running in production—typically a dense vector index and a sparse keyword index—and needs a lightweight classifier to route queries. The prompt requires the user's query text as input and optionally accepts context such as conversation history, user role, or latency budget constraints. It works best when the distinction between backends is clear: vector search for semantic similarity and conceptual queries, keyword search for exact term matching and entity lookup, and hybrid for queries that blend both needs. Do not use this prompt if you only have one retrieval backend, if your backend automatically handles fusion, or if you need the model to generate the actual search queries rather than just the strategy decision.
Before deploying this prompt, ensure you have defined clear evaluation criteria for what constitutes a correct routing decision in your system. Common failure modes include over-routing to hybrid when a simpler strategy would suffice, misclassifying entity-heavy queries as purely semantic, and failing to account for temporal signals that make keyword retrieval more appropriate. Wire the prompt's output into a decision harness that logs every classification alongside the eventual retrieval latency and relevance metrics. This allows you to measure whether the prompt's decisions actually improve system performance. If your retrieval pipelines are still under active development, start by logging decisions in shadow mode before letting the prompt control live traffic.
Use Case Fit
Where the Vector vs Keyword vs Hybrid Query Decision Prompt works and where it introduces risk. Use these cards to decide if this prompt belongs in your retrieval dispatch layer.
Good Fit: Multi-Backend Search Infrastructure
Use when: your system has separate dense vector, sparse keyword (BM25), and hybrid retrieval backends available. The prompt classifies the query and selects the optimal backend before retrieval execution. Guardrail: validate that the selected backend actually exists in your infrastructure before dispatching; a hallucinated backend name will cause a runtime failure.
Bad Fit: Single-Index Retrieval Systems
Avoid when: you only have one retrieval backend. The prompt will still produce a strategy decision, but the routing logic adds latency and complexity with no benefit. Guardrail: check your available backends at runtime and skip the decision prompt entirely if there is only one valid target.
Required Input: Query Characteristics Signal
What to watch: the prompt needs more than the raw user query to make accurate decisions. Without signals like query length, entity density, or expected result type, the model guesses. Guardrail: pre-compute lightweight query features (term count, named entity presence, abstractness score) and include them as structured input alongside the query text.
Operational Risk: Latency Budget Blowout
What to watch: adding a classification step before retrieval increases end-to-end latency. For real-time applications with strict p95 targets, this extra model call may be unacceptable. Guardrail: set a latency budget for the decision step. If the classifier call exceeds 200ms, fall back to a default strategy (hybrid) and log the timeout for offline tuning.
Operational Risk: Strategy Oscillation
What to watch: similar queries may flip between vector and keyword strategies due to minor phrasing differences, causing inconsistent result quality. Guardrail: implement a short-term decision cache keyed on normalized query text. If the same normalized query appears within a configurable TTL window, reuse the prior strategy decision to stabilize results.
Required Input: Retrieval Quality Feedback Loop
What to watch: without feedback on whether the chosen strategy produced good results, the decision prompt cannot improve and may drift over time as your indexes change. Guardrail: log each decision along with downstream relevance signals (click-through, answer rating, null-result flag). Use this data to periodically evaluate and recalibrate the decision prompt against production outcomes.
Copy-Ready Prompt Template
A copy-ready template for classifying a user query and selecting the optimal retrieval backend among dense vector, sparse keyword, or hybrid search.
This template provides a production-ready prompt for a query routing decision. It is designed to be placed inside a retrieval dispatch layer where a user's natural language query must be analyzed before hitting any search index. The prompt forces the model to reason about query structure, entity density, and precision/recall trade-offs before committing to a single strategy. Copy the template below and replace every square-bracket placeholder with your system's specific backends, constraints, and output schema.
textSYSTEM: You are a retrieval strategy router. Your job is to analyze a user's search query and select the optimal retrieval backend: dense vector search, sparse keyword search, or a hybrid combination. You have access to the following backends: - [VECTOR_INDEX_NAME]: Dense embeddings optimized for semantic similarity. Best for conceptual queries, paraphrases, and natural language questions. - [KEYWORD_INDEX_NAME]: Sparse inverted index using [BM25/TF-IDF]. Best for exact term matching, entity names, codes, and rare tokens. - [HYBRID_INDEX_NAME]: Combines vector and keyword results with [RECIPROCAL_RANK_FUSION/LEARNED_WEIGHTING]. Best for queries with both semantic and lexical components. ## Decision Criteria 1. **Exact match priority**: If the query contains proper nouns, product codes, error codes, or rare technical terms, prefer keyword or hybrid. 2. **Conceptual queries**: If the query is a natural language question, description, or paraphrase without specific entity anchors, prefer vector. 3. **Mixed queries**: If the query has both conceptual language and specific entities, prefer hybrid. 4. **Short queries**: Queries under [N] words with no clear entities default to hybrid to balance precision and recall. 5. **Latency budget**: If the user context indicates a strict latency requirement under [LATENCY_BUDGET_MS]ms, prefer vector or keyword alone unless hybrid is essential for relevance. ## Output Format Return a JSON object with the following schema: { "selected_strategy": "vector" | "keyword" | "hybrid", "confidence": 0.0-1.0, "reasoning": "Brief explanation of the decision.", "fallback_strategy": "vector" | "keyword" | "hybrid", "query_type": "exact_lookup" | "conceptual" | "mixed" | "ambiguous" } ## Constraints - Do not select hybrid if the query is clearly an exact term match with no semantic component. - Do not select vector alone if the query contains a product SKU, error code, or legal citation. - If confidence is below [CONFIDENCE_THRESHOLD], set fallback_strategy to hybrid. - Never invent or assume entities not present in the query. USER QUERY: [USER_QUERY] USER CONTEXT (optional): [USER_CONTEXT]
Adaptation guidance: Replace [VECTOR_INDEX_NAME], [KEYWORD_INDEX_NAME], and [HYBRID_INDEX_NAME] with your actual index identifiers. Set [N] to your short-query word-count threshold (commonly 3). Set [LATENCY_BUDGET_MS] to your p95 latency target. Set [CONFIDENCE_THRESHOLD] to your minimum confidence before forcing a hybrid fallback (0.7 is a reasonable starting point). If your system does not support hybrid retrieval, remove that option and adjust the decision criteria to a binary vector vs. keyword choice. The [USER_CONTEXT] field is optional but should be populated with session history, user role, or latency requirements when available to improve routing accuracy.
What to do next: After copying this template, wire it into your retrieval dispatch layer as described in the Implementation Harness section. Before deploying, run the evaluation checks in the Testing and Eval Criteria section to calibrate your confidence threshold and verify that entity-dense queries are not incorrectly routed to vector-only retrieval. If your system uses multiple specialized indexes beyond these three backends, consider extending the output schema with an index_target field rather than overloading the strategy selection.
Prompt Variables
Inputs the prompt needs to work reliably. Validate each before sending the prompt.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The raw user question to analyze for retrieval strategy selection | What are the latest performance benchmarks for the RaptorX chip? | Must be non-empty string. Check for injection patterns. Max 2000 chars. |
[AVAILABLE_STRATEGIES] | List of retrieval strategies the system can execute with their capabilities | ["dense_vector", "sparse_keyword", "hybrid", "graph_traversal"] | Must be valid JSON array. Each entry must match a registered strategy name. Reject unknown strategies. |
[INDEX_METADATA] | Metadata about each available index including latency, cost, and freshness profiles | {"dense_vector": {"latency_ms": 80, "freshness": "daily"}, "sparse_keyword": {"latency_ms": 30, "freshness": "realtime"}} | Must be valid JSON object. Keys must match AVAILABLE_STRATEGIES entries. Latency must be positive number. |
[QUERY_CHARACTERISTICS_SCHEMA] | Schema defining the output structure for query analysis | {"query_type": "string", "entity_density": "low|medium|high", "temporal_requirements": "boolean", "precision_priority": "boolean"} | Must be valid JSON schema. Required fields: query_type, entity_density. Enum values must be enforced. |
[LATENCY_BUDGET_MS] | Maximum acceptable retrieval latency in milliseconds | 200 | Must be positive integer. If null, default to 500ms. Reject values below 10ms as unrealistic. |
[COST_BUDGET_PER_QUERY] | Maximum acceptable cost per retrieval call in USD | 0.005 | Must be positive float or null. If null, cost is not a constraint. Reject negative values. |
[RELEVANCE_THRESHOLD] | Minimum relevance score required to consider a strategy viable | 0.7 | Must be float between 0.0 and 1.0. Default 0.6 if not provided. Values below 0.3 trigger fallback-only mode. |
[SESSION_CONTEXT] | Prior conversation turns for resolving anaphora and implicit references | [{"role": "user", "content": "Show me chip benchmarks"}, {"role": "assistant", "content": "Which chip family?"}] | Must be valid JSON array or null. Each turn must have role and content. Max 10 turns to control prompt length. |
Implementation Harness Notes
How to wire the Vector vs Keyword vs Hybrid Query Decision Prompt into a retrieval dispatch layer as a decision component.
This prompt is not a standalone service. It is a decision component that sits inside a retrieval dispatch layer. Its job is to inspect the user query and return a routing decision—vector, keyword, or hybrid—along with a confidence score and reasoning. The dispatch layer reads that decision and calls the appropriate retrieval backend. Do not treat this prompt as the retrieval step itself; it only decides which retrieval strategy to invoke next. The output must be consumed by application code that maps the decision to actual index calls, latency budgets, and fallback chains.
Wire the prompt into a pre-retrieval hook that fires after query normalization but before any index query. The application should: (1) receive the user query, (2) strip PII and apply any access-control filters, (3) call this decision prompt with the cleaned query and available backend metadata, (4) parse the JSON output and validate the strategy field against an allowlist of ["vector", "keyword", "hybrid"], (5) route to the corresponding retrieval function. If the confidence score falls below a configured threshold (start at 0.7 and tune from production traces), fall back to hybrid retrieval as the safe default. Log every decision—query fingerprint, chosen strategy, confidence, latency, and whether the user accepted or reformulated the results—so you can measure strategy accuracy over time. For high-throughput systems, cache decisions for identical normalized queries with a short TTL (e.g., 5 minutes) to avoid redundant LLM calls.
Add a circuit breaker: if the decision prompt fails, times out, or returns unparseable output after one retry, default to hybrid retrieval and log the failure for investigation. Do not block the user on a decision prompt error. For latency-sensitive applications, consider running this prompt in parallel with a fast keyword fallback so results are ready regardless of the decision path. The next step after implementing this harness is to build an eval set of 200+ queries with ground-truth strategy labels, run the prompt against them, and measure precision and recall per strategy class. Pay special attention to queries that sit on the boundary between vector and hybrid—these are where misclassification costs the most relevance.
Expected Output Contract
Fields, format, and validation rules for the JSON response. Validate every field before routing.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
decision | enum: vector | keyword | hybrid | Must be exactly one of the three allowed string values. Reject any other string. | |
confidence | number | Must be a float between 0.0 and 1.0 inclusive. Reject if out of range or non-numeric. | |
rationale | string | Must be 1-3 sentences explaining the decision. Reject if empty, null, or >500 characters. | |
query_characteristics | object | Must contain at least one key from: entity_density, temporal_scope, ambiguity_level, comparison_intent, procedural_intent, factual_intent. Reject if empty object. | |
query_characteristics.entity_density | enum: low | medium | high | If present, must be one of the three allowed values. Reject invalid strings. | |
query_characteristics.temporal_scope | enum: none | relative | absolute | range | If present, must be one of the four allowed values. Reject invalid strings. | |
query_characteristics.ambiguity_level | enum: none | low | medium | high | If present, must be one of the four allowed values. Reject invalid strings. | |
query_characteristics.comparison_intent | boolean | If present, must be true or false. Reject strings or numbers. | |
query_characteristics.procedural_intent | boolean | If present, must be true or false. Reject strings or numbers. | |
query_characteristics.factual_intent | boolean | If present, must be true or false. Reject strings or numbers. | |
latency_budget | enum: low | medium | high | Must be one of the three allowed values. Reject invalid strings or null. | |
fallback_strategy | string | If present, must be a non-empty string naming a valid fallback retrieval method. Reject empty strings. | |
requires_metadata_filter | boolean | Must be true or false. Reject if null, missing, or non-boolean. | |
suggested_index | string | If present, must be a non-empty string matching a configured index name pattern. Reject empty strings. |
Common Failure Modes
What breaks first when routing queries to vector, keyword, or hybrid retrieval and how to guard against it.
Keyword Queries Treated as Semantic
What to watch: Exact-match queries (product codes, error strings, document IDs) are routed to dense vector retrieval and return semantically similar but factually wrong results. Guardrail: Add a pre-check for literal-match signals (quotes, alphanumeric patterns, known identifiers) and force keyword or hybrid retrieval when detected.
Hybrid Fusion Score Distortion
What to watch: Reciprocal rank fusion or linear combination masks that one retrieval stream dominated the results, burying the only relevant document from the other stream. Guardrail: Log per-stream rank contributions and set a minimum rank threshold per stream. If one stream contributes zero top-N results, re-weight or escalate for review.
Latency Budget Overrun on Hybrid
What to watch: Hybrid retrieval doubles latency by running vector and keyword in sequence instead of parallel, causing timeouts in user-facing applications. Guardrail: Enforce parallel execution with a strict timeout per stream. If one stream exceeds budget, return partial results with a degraded flag rather than blocking the response.
Missed Entity Disambiguation
What to watch: Queries containing ambiguous entities (e.g., 'Apple' the company vs. fruit) are routed to vector search without entity resolution, producing mixed-domain results. Guardrail: Run lightweight entity detection before strategy selection. If multiple entity types are detected with low confidence, route to keyword with metadata filtering or trigger a clarification prompt.
Over-Reliance on Vector for Short Queries
What to watch: Short queries (1-3 words) produce poor dense embeddings due to lack of context, yet the router sends them to vector search by default. Guardrail: Set a minimum query length threshold for pure vector routing. Short queries default to keyword or hybrid with boosted keyword weight.
Strategy Oscillation Across Turns
What to watch: In multi-turn conversations, the router flips between vector, keyword, and hybrid on each turn, causing inconsistent result quality and confusing downstream answer generation. Guardrail: Maintain session-level strategy stickiness. Only change strategy when query type classification confidence exceeds a threshold, and log strategy transitions for review.
Evaluation Rubric
How to test output quality before shipping. Run these checks against a labeled dataset of at least 100 queries covering short keyword, long natural language, mixed entity, and ambiguous queries.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Strategy Selection Accuracy | Predicted strategy matches ground-truth label for >= 90% of queries | Mismatch rate exceeds 10%, especially on ambiguous or mixed-intent queries | Compare model output to labeled dataset; compute precision, recall, F1 per strategy class |
Hybrid Overuse Prevention | Hybrid strategy selected for < 20% of queries that are clearly single-strategy (pure keyword or pure semantic) | Hybrid selected as a default for simple queries, inflating latency and cost without relevance gain | Flag queries with single clear intent; assert hybrid rate below threshold |
Keyword Underuse Detection | Keyword strategy selected for >= 95% of queries containing exact codes, IDs, or rare proper nouns | Vector strategy chosen for SKU, error code, or part number queries where exact match is required | Curate a subset of exact-match queries; assert keyword selection rate |
Latency-Aware Trade-off | Hybrid strategy not selected when query complexity score is low and latency budget is tight | Hybrid recommended for simple queries in latency-sensitive contexts | Inject latency budget context; assert strategy aligns with budget constraint |
Ambiguity Handling | When query is ambiguous, output includes confidence score < 0.8 and fallback strategy | High-confidence single-strategy output for ambiguous queries with multiple valid interpretations | Score ambiguity subset; assert confidence below threshold and fallback present |
Entity-Dense Query Routing | Hybrid or keyword strategy selected for queries with >= 3 distinct named entities | Vector-only strategy chosen for entity-dense queries requiring precise entity matching | Count entities per query; assert strategy selection matches entity density expectation |
Temporal Query Routing | Queries with relative time expressions trigger freshness-aware strategy or temporal index flag | Temporal queries routed to generic vector search without time constraint propagation | Parse output for temporal flag or freshness tier; assert present for time-sensitive queries |
Zero-Result Risk Preemption | Queries with rare terms or over-constrained filters trigger relaxed or fallback strategy | Strict single-strategy output for queries likely to return zero results | Simulate retrieval against sparse index; assert fallback strategy triggered for low-recall query patterns |
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
Start with the base prompt and a single model. Remove latency constraints and use simple pass/fail checks. Focus on getting the three-way classification (vector, keyword, hybrid) correct before tuning trade-off language.
Strip the prompt to essentials:
codeClassify [QUERY] as VECTOR, KEYWORD, or HYBRID.
Watch for
- Over-classifying everything as HYBRID when the query could be served by a single strategy
- Ignoring query length as a signal (short queries often favor keyword; long natural-language queries favor vector)
- No baseline accuracy measurement before adding complexity

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