This prompt is designed for orchestration engineers who operate a dual-index retrieval architecture: a knowledge graph index for relationship traversal and a vector index for semantic similarity search. Its job is to inspect a user query and decide whether the query is entity-dense, requiring relationship traversal, or semantic, requiring vector similarity search. Use it as a dispatch layer before retrieval execution to reduce latency and improve precision by sending each query to the index best suited to answer it. The core assumption is that your graph index supports relationship-first queries (e.g., 'find all reports authored by people who worked on Project X') and that your vector index handles open-ended natural language questions (e.g., 'what are the best practices for cloud cost optimization?').
Prompt
Entity-Dense Query Routing Prompt for Graph vs Vector Index

When to Use This Prompt
Determine when to deploy the entity-dense query router and when a simpler retrieval strategy is sufficient.
Do not use this prompt when you have a single index, when your graph is purely for metadata filtering on vector search results, or when every query should hit both indexes and merge results. It is also inappropriate when your entity catalog is undefined or incomplete—the router cannot make accurate decisions without a known set of entities and relationship types. This prompt assumes you have a defined entity catalog and that your graph index supports relationship-first queries. If your system lacks these prerequisites, you will get unreliable routing decisions that degrade retrieval quality rather than improve it. The router is a precision tool for a specific architectural pattern, not a general-purpose query classifier.
Before implementing this prompt, verify that your retrieval architecture genuinely benefits from index-level routing. If your vector index already handles entity-heavy queries adequately, or if your graph index is immature, the added complexity of a dispatch layer may not justify the marginal improvement. Start by logging a sample of production queries and manually labeling them as entity-dense or semantic. If fewer than 20% of queries are entity-dense, a simpler 'always vector' strategy with optional graph enrichment may be more maintainable. If you proceed, pair this router with an evaluation pipeline that measures routing accuracy against human-labeled ground truth, and monitor the downstream impact on answer quality, not just routing precision.
Use Case Fit
Where the Entity-Dense Query Routing Prompt delivers value and where it introduces risk. This prompt classifies queries by entity density and relationship complexity to route between graph and vector indexes.
Good Fit: Relationship-Heavy Queries
Use when: user queries involve multi-hop relationships, explicit connections between named entities, or traversal patterns like 'reports to,' 'depends on,' or 'owned by.' Guardrail: confirm the graph index contains the relevant relationship types before routing; otherwise, fall back to vector search with entity-filtered retrieval.
Bad Fit: Abstract or Conceptual Queries
Avoid when: queries express ideas, concepts, or themes without specific named entities or relationship patterns. Guardrail: maintain a confidence threshold for entity extraction; route queries with fewer than two extracted entities directly to vector search to avoid unnecessary graph latency.
Required Input: Entity Extraction Accuracy
Risk: the routing decision depends entirely on entity extraction quality. Missed entities cause incorrect vector routing; hallucinated entities cause empty graph results. Guardrail: log entity extraction confidence scores and route to vector search as a safe default when extraction confidence falls below 0.7, with periodic human review of borderline cases.
Operational Risk: Graph Index Availability
Risk: graph database downtime or latency spikes silently degrade user experience when the router continues sending queries to an unhealthy backend. Guardrail: implement a circuit breaker that monitors graph index health; automatically route all queries to vector search when the graph endpoint exceeds latency thresholds or returns errors above 1% in a rolling window.
Cost Trade-Off: Dual Index Overhead
Risk: running both graph and vector indexes doubles infrastructure cost, but routing all queries to both for comparison defeats the purpose of selective routing. Guardrail: track the percentage of queries routed to each index and the result quality differential; if graph routing provides marginal improvement for fewer than 15% of queries, evaluate whether a single vector index with metadata filtering achieves sufficient quality at lower operational cost.
Evaluation Trap: Synthetic Benchmarks
Risk: entity-dense routing accuracy measured on clean benchmark datasets overestimates production performance where queries contain typos, ambiguous entity names, or mixed-language references. Guardrail: build an evaluation set from production query logs with human-annotated routing labels; measure precision and recall separately for graph-bound and vector-bound decisions, and monitor the false-positive graph routing rate as the primary operational metric.
Copy-Ready Prompt Template
A copy-ready prompt template for classifying a user query and routing it to either a knowledge graph or a vector index, including entity extraction.
The following prompt template is designed to be placed directly into your orchestration layer. It instructs the model to act as a retrieval router, analyzing the incoming user query for entity density and relationship requirements. The core decision is binary: route to a knowledge graph for relationship traversal or to a vector index for semantic similarity. The prompt also requires the model to extract key entities, which serves as both a debugging artifact and a potential input for the downstream retriever.
textSystem: You are a retrieval routing specialist. Your task is to analyze a user query and decide whether it should be answered by traversing a knowledge graph or by searching a vector index. A knowledge graph is optimal for queries that are dense with specific entities and require understanding the relationships between them (e.g., 'Who is the CEO of the company that acquired Acme Corp?'). A vector index is optimal for broad, conceptual, or semantic queries where exact entity relationships are less critical (e.g., 'strategies for entering the European market'). User Query: [USER_QUERY] Analyze the query and produce a JSON object with the following keys: - `strategy`: A string, either "graph" or "vector". - `rationale`: A brief, one-sentence explanation for the routing decision. - `extracted_entities`: A list of the key named entities (people, companies, products, etc.) found in the query. Return an empty list if none are found. [OUTPUT_SCHEMA] { "strategy": "string", "rationale": "string", "extracted_entities": ["string"] }
To adapt this template, replace the [USER_QUERY] placeholder with the raw input from your application. The [OUTPUT_SCHEMA] is provided inline as a strict JSON specification. For production use, you should hardcode this schema into your application's validation layer and remove the [OUTPUT_SCHEMA] token from the prompt itself. The next step after receiving a valid JSON response is to parse the strategy field and use it to dispatch the [USER_QUERY] to the correct retrieval backend. If the strategy is 'graph', you might also use the extracted_entities list as a starting point for a graph traversal query.
Prompt Variables
Inputs the Entity-Dense Query Routing Prompt needs to classify a query and route it to graph or vector retrieval. Validate each variable before the prompt is assembled to prevent silent routing failures.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The raw natural language question from the user that must be classified for routing. | Which investors backed Stripe's Series C and what other companies did they fund? | Required. Must be a non-empty string. Check for injection attempts or malformed text before passing to the classifier. |
[ENTITY_CATALOG] | A list of known entity types the graph index can resolve, used to detect entity-dense queries. | ["PERSON", "ORGANIZATION", "FUNDING_ROUND", "INVESTOR", "ACQUISITION"] | Required. Must be a valid JSON array of strings. If empty, the prompt should default to vector retrieval and log a warning. |
[RELATIONSHIP_TYPES] | The relationship predicates the graph index supports for traversal queries. | ["INVESTED_IN", "ACQUIRED_BY", "FOUNDED", "PARTNERED_WITH", "SUBSIDIARY_OF"] | Required. Must be a valid JSON array of strings. Missing or empty list forces vector-only routing. |
[GRAPH_INDEX_NAME] | The identifier for the graph retrieval backend, used in the routing decision output. | graph_investor_network_v2 | Required. Must be a non-empty string matching a deployed index name. Validate against a registry of active indexes. |
[VECTOR_INDEX_NAME] | The identifier for the vector retrieval backend, used as the fallback routing target. | vector_knowledge_base_v3 | Required. Must be a non-empty string matching a deployed index name. Validate against a registry of active indexes. |
[CONFIDENCE_THRESHOLD] | The minimum confidence score required to route to graph retrieval. Below this, the query falls back to vector. | 0.75 | Required. Must be a float between 0.0 and 1.0. Default to 0.70 if not specified. Values below 0.50 produce excessive false-positive graph routing. |
[OUTPUT_SCHEMA] | The expected JSON structure for the routing decision, including target index, confidence, and extracted entities. | {"target_index": "graph_investor_network_v2", "confidence": 0.92, "extracted_entities": ["Stripe", "Series C"], "reasoning": "Multiple entity relationships detected"} | Required. Must be a valid JSON Schema object. Validate that the model output conforms to this schema before the dispatcher consumes it. |
Implementation Harness Notes
How to wire the entity-dense query routing prompt into a production retrieval dispatch layer with validation, fallback, and observability.
This prompt functions as a classification router that sits between the user's query and your retrieval backends. It should be called synchronously before any index query is executed. The model's output—a routing decision (graph_index, vector_index, or hybrid) and an entity list—must be parsed and used to select the downstream retrieval path. Do not treat this as a conversational prompt; it is a structured decision point in a pipeline. The prompt expects a single user query as [QUERY] and an optional [DOMAIN_CONTEXT] describing the available knowledge domains. The output schema should be enforced via structured output mode (JSON mode or function calling) to avoid parsing errors in production.
Validation and retry logic is critical because a misrouted query silently degrades answer quality. After parsing the model's JSON response, validate that the strategy field is one of the allowed enum values (graph_index, vector_index, hybrid). If the field is missing or invalid, retry the prompt once with a stricter system instruction that emphasizes the enum constraint. If the retry also fails, default to hybrid retrieval and log the failure for review. For the entities array, check that each entry has a non-empty name field and a type value from your supported entity types. Empty entity lists are valid for queries with no detectable entities, but a list of entities where half are malformed suggests a model output issue worth sampling and reviewing.
Model choice matters. This routing prompt benefits from models with strong instruction-following and JSON output discipline. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are all suitable. Avoid smaller or older models that may conflate the routing decision or hallucinate entity types not present in the query. If latency is a concern, consider hosting a fine-tuned classifier model on this specific task rather than using a general-purpose model with a long prompt. Log every routing decision with the query, the model's raw output, the validated strategy, the extracted entities, and the retrieval path taken. This log becomes your evaluation dataset for measuring routing accuracy over time. Sample routing decisions weekly and have a human reviewer check whether the chosen strategy would have retrieved better results than the alternatives. Use these samples to tune your routing thresholds and update few-shot examples in the prompt template.
Integration pattern: In your retrieval orchestrator, call this prompt first. Use the strategy output to branch: graph_index routes to your graph database with a Cypher or SPARQL query generated from the entities; vector_index routes to your dense vector store with the original query; hybrid runs both in parallel and merges results with reciprocal rank fusion. The entities array can be passed as metadata filters or used to construct the graph query. If the model returns hybrid but your latency budget only allows one path, use the confidence score from the output (if you add it to the schema) to break ties. Avoid over-routing to hybrid by monitoring the distribution of strategy selections; if more than 40% of queries route to hybrid, your classification thresholds may need adjustment or your indexes may need better scope definition.
Failure modes to instrument: The most common production failure is the model routing a relationship-heavy query to the vector index because it failed to recognize implicit entity relationships. Instrument a metric for 'graph-routable queries sent to vector' by sampling vector-routed queries and checking if they contain multiple linked entities. A second failure mode is entity extraction hallucination, where the model invents entity names or types not present in the query. Add a post-processing check that each extracted entity string appears verbatim in the original query or is a known canonical form from your entity resolution system. If you maintain an entity catalog, validate extracted entities against it and flag mismatches. Finally, watch for routing instability: if the same query routed through the prompt twice produces different strategies, your temperature may be too high or your prompt constraints too loose. Set temperature to 0 for this routing task in production.
Expected Output Contract
Defines the required JSON structure, field types, and validation rules for the entity-dense query routing prompt output. Use this contract to parse the model response and trigger routing logic.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
routing_decision | string enum: graph | vector | Must be exactly 'graph' or 'vector'. Reject any other value. | |
confidence_score | float (0.0 to 1.0) | Must be a number between 0.0 and 1.0 inclusive. If below [CONFIDENCE_THRESHOLD], trigger fallback to hybrid retrieval. | |
entity_list | array of strings | Must contain at least one non-empty string if routing_decision is 'graph'. Each string must be a canonical entity name, not a pronoun or generic noun. | |
relationship_types | array of strings | Required if routing_decision is 'graph'. Each string must describe a relationship category (e.g., 'works_for', 'subsidiary_of'). Null allowed if routing_decision is 'vector'. | |
reasoning | string | Must be a non-empty string explaining the routing choice. Must reference specific entities or query characteristics. Max 300 characters. | |
fallback_strategy | string enum: hybrid | vector | none | Must be 'hybrid' if confidence_score < [CONFIDENCE_THRESHOLD]. Must be 'none' if confidence_score >= [CONFIDENCE_THRESHOLD]. 'vector' is only valid when routing_decision is 'graph' and confidence is borderline. | |
query_rewrite | string | Required if routing_decision is 'graph'. Must be a rewritten query optimized for graph traversal, including entity names and relationship types. Null allowed if routing_decision is 'vector'. | |
vector_query_override | string | Required if routing_decision is 'vector'. Must be a semantic query string optimized for dense retrieval. Null allowed if routing_decision is 'graph'. |
Common Failure Modes
Entity-dense queries break routing in predictable ways. These cards cover the most common failure patterns when deciding between graph and vector retrieval, with concrete mitigations for each.
Entity Overlap Causes Wrong Index Selection
What to watch: Queries mentioning multiple entity types (people, orgs, products) can trigger vector routing when the relationship between entities is what matters. The prompt sees 'many entities' and misclassifies the query as semantic similarity search. Guardrail: Add a tie-breaker rule in the prompt that prioritizes graph routing when two or more known entity types appear together with a relationship verb (acquired, reports-to, depends-on).
Implicit Relationships Missed by Entity Extraction
What to watch: Queries like 'Who runs the team that owns payment processing?' contain implicit relationships (runs → manages, owns → responsible-for) that naive entity extraction skips. The prompt extracts 'team' and 'payment processing' as entities but misses the structural traversal need. Guardrail: Include a relationship-hint glossary in the prompt mapping common verbs to graph edge types, and require the model to check for traversal intent before defaulting to vector.
High Entity Count Triggers Ambiguity Abandonment
What to watch: When a query contains four or more entities, the routing prompt may return low confidence for both graph and vector paths and fall back to an unfocused hybrid retrieval that satisfies neither. Guardrail: Add a confidence threshold rule: if entity count exceeds three, route to graph retrieval with a decomposition step that breaks the query into sub-traversals rather than abandoning to vector.
Vector Routing on Graph-Shaped Semantic Queries
What to watch: Queries like 'products similar to what Acme Corp customers buy' sound semantic but require graph traversal (customer-of → purchased → similar-products). The prompt routes to vector search based on surface similarity language and misses the structural path. Guardrail: Add a structural-dependency check that scans for chained possession or association patterns (X of Y, Y's X, X that Y Z) and flags them for graph evaluation before vector routing.
Entity Extraction Hallucination on Unknown Entities
What to watch: The prompt invents entity identifiers or relationship types for terms not in the graph schema, producing graph queries that return empty results while vector search would have found relevant content. Guardrail: Require the prompt to output extracted entities with a schema-membership confidence flag, and route to vector when any entity falls below the known-entity threshold rather than forcing a doomed graph query.
Temporal or Stateful Queries Misfrouted to Static Graph
What to watch: Queries like 'Who was the CEO in 2022?' or 'Current open issues for this vendor' mix entity traversal with time or state constraints that a static knowledge graph cannot resolve alone. The prompt routes to graph, which returns outdated or incomplete structural data. Guardrail: Add a temporal-state detection rule: if the query contains time bounds or state qualifiers (current, active, open, as-of), route to vector retrieval over time-stamped documents or trigger a hybrid graph-plus-filtered-vector path.
Evaluation Rubric
Use this rubric to evaluate the Entity-Dense Query Routing Prompt before production deployment. Each criterion targets a specific failure mode in graph vs. vector routing decisions.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Entity Extraction Accuracy | All named entities in [USER_QUERY] are extracted with correct type labels (Person, Organization, Product, Location, Event) | Missing entities or incorrect type assignment (e.g., labeling 'Apple' as Organization when context indicates Product) | Run 50 annotated queries through extraction step; require F1 >= 0.90 on entity span and type |
Entity Density Threshold Calibration | Queries with >= 3 entities AND >= 1 explicit relationship indicator route to graph index; queries with 0-1 entities route to vector index | Edge cases at 2 entities route inconsistently or relationship indicators are ignored | Test boundary set of 30 queries with exactly 2 entities and varied relationship signals; verify routing consistency >= 95% |
Relationship Detection Precision | Explicit relationship indicators (verbs like 'acquired', 'works at', 'depends on', 'reports to') trigger graph routing; implicit relationships without indicators route to vector | Queries with implicit relationships incorrectly routed to graph or explicit relationships missed | Curate 20 query pairs with explicit vs. implicit relationship phrasing; require >= 90% correct discrimination |
Graph Index Routing Confidence | Graph routing decisions include confidence score >= 0.8 when entity count >= 3 and relationship is explicit; score < 0.5 triggers fallback to vector | High-confidence graph routing on queries better suited to vector search or low-confidence scores on clear graph queries | Log confidence scores across 100 routing decisions; verify score distribution aligns with ground-truth routing labels |
Vector Index Routing Appropriateness | Semantic similarity queries, definitional queries, and single-entity lookups route to vector index with confidence >= 0.8 | Entity-dense relationship queries incorrectly routed to vector index due to entity extraction failure | Test 40 semantic queries against routing output; require <= 5% false vector routing on graph-appropriate queries |
Fallback Behavior Correctness | When confidence < 0.5 for both graph and vector, system routes to hybrid retrieval or flags for human review per [FALLBACK_POLICY] | Low-confidence queries silently default to one index without hybrid fallback or review flag | Inject 15 ambiguous queries; verify 100% trigger fallback path and 0% silently route to single index |
Output Schema Compliance | Routing decision returns valid JSON matching [OUTPUT_SCHEMA] with fields: index_target, confidence_score, extracted_entities, relationship_detected, fallback_triggered | Missing required fields, malformed JSON, or extra fields not in schema | Validate 100 routing outputs against JSON Schema; require 100% structural compliance |
Latency Budget Adherence | Entity extraction + routing decision completes within [LATENCY_BUDGET_MS] milliseconds for 95th percentile | Routing adds unacceptable latency overhead to retrieval pipeline, especially on entity-dense queries | Benchmark 200 queries across entity density distribution; measure p50, p95, p99 latency against budget |
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 frontier model (GPT-4o, Claude 3.5 Sonnet). Remove strict output schema requirements initially. Accept plain text routing decisions with entity lists.
codeRoute this query to [GRAPH_INDEX] or [VECTOR_INDEX]. List extracted entities. Query: [USER_QUERY]
Watch for
- Entity extraction misses on compound nouns (e.g., "machine learning pipeline architecture")
- Over-routing to vector when simple relationship traversal would suffice
- No confidence signal when both indexes could partially answer

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