This prompt is designed for vector search engineers and RAG developers who need to improve retrieval precision when user queries contain homonyms—words that are spelled the same but have different meanings. The core job-to-be-done is transforming an ambiguous user query into a contextually disambiguated query that is optimized for dense vector retrieval. The ideal user is someone who has already observed precision failures in their retrieval system, specifically where a query for 'bank' returns financial documents when the user wanted river-related content, or vice versa. You should use this prompt when your vector search index contains documents spanning multiple domains where homonyms are common, and when your existing retrieval pipeline lacks a pre-retrieval disambiguation step.
Prompt
Homonym Resolution Prompt for Vector Search

When to Use This Prompt
Define the job, the reader, and the operational constraints for the homonym resolution prompt.
This prompt is not a general-purpose query rewriter. Do not use it for queries that are ambiguous due to underspecification, missing temporal constraints, or entity collisions that are not homonym-based. It is also not a substitute for a full entity linking system or a knowledge graph. The prompt assumes you have already identified that homonym confusion is a measurable problem in your retrieval metrics. Before implementing, you should have a test set of homonym-heavy queries with known relevant documents so you can measure recall improvement. The prompt requires a domain context to function—without a description of the corpus or the user's likely intent domain, it cannot reliably choose the correct sense of a homonym. In high-stakes domains like legal or medical search, always route the disambiguated query through a human review step before returning results to the user.
After reading this section, you should assess whether homonym confusion is a top-3 retrieval failure mode in your system. If yes, proceed to the prompt template and implementation harness. If your precision problems stem from other ambiguity types—such as acronyms, underspecified constraints, or anaphora—use one of the sibling playbooks in the Query Disambiguation and Ambiguity Resolution group instead. The next section provides the copy-ready prompt template with placeholders you can adapt to your domain.
Use Case Fit
Where the Homonym Resolution Prompt works, where it fails, and the operational preconditions for safe deployment in a vector search pipeline.
Good Fit: Pre-Retrieval Query Rewriting
Use when: the prompt sits between the user and the vector index, rewriting the query before embedding. Guardrail: always log the original query alongside the rewritten form for debugging and regression testing.
Bad Fit: Real-Time Chat Without Latency Budget
Avoid when: the system requires sub-100ms responses and cannot absorb an extra LLM call. Guardrail: implement a fast-path that skips disambiguation for short, low-risk queries based on a lightweight classifier.
Required Input: Domain Context
Risk: without domain context, the model guesses the homonym sense and produces confidently wrong rewrites. Guardrail: always pass a domain label or a short list of canonical entity descriptions as part of the prompt context.
Required Input: User Session History
Risk: treating every query as isolated ignores prior turns that disambiguate the current query. Guardrail: include the last 2-3 turns of the conversation or the active document context in the prompt payload.
Operational Risk: Silent Sense Drift
What to watch: the model resolves the homonym to a plausible but wrong sense, and downstream retrieval returns irrelevant results with no error signal. Guardrail: add a retrieval-relevance eval step that compares result sets from the original and rewritten queries.
Operational Risk: Over-Expansion Noise
What to watch: the prompt generates too many synonym expansions, diluting precision. Guardrail: cap the number of expansion terms and weight the original query terms higher in the final hybrid retrieval query.
Copy-Ready Prompt Template
A reusable prompt that identifies homonyms in a query, generates contextually appropriate replacements, and outputs a rewritten query optimized for dense vector retrieval.
The prompt below is designed to be dropped into a retrieval pipeline before the embedding step. It takes a raw user query and a domain context description, identifies terms with multiple meanings, selects the most likely interpretation based on the domain, and produces a rewritten query that replaces ambiguous terms with disambiguated phrases. The output includes both the rewritten query and a structured explanation of each homonym resolution so downstream systems can audit the transformation.
textYou are a query disambiguation engine for a vector search system. Your job is to detect homonyms in a user query and rewrite the query to resolve ambiguity before it is embedded for dense retrieval. ## INPUT User query: [USER_QUERY] Domain context: [DOMAIN_CONTEXT] ## TASK 1. Identify any terms in the user query that are homonyms—words with multiple distinct meanings that could cause the vector search to retrieve irrelevant documents. 2. For each homonym, determine which meaning is most likely given the domain context. 3. Rewrite the query by replacing each homonym with a short, unambiguous phrase that captures the intended meaning. Do not add new constraints or change the query's intent. 4. If no homonyms are detected, return the original query unchanged. ## OUTPUT SCHEMA Return a valid JSON object with these fields: - "original_query": string, the input query exactly as received - "homonyms_detected": array of objects, each with: - "term": string, the homonym word - "possible_meanings": array of strings, the distinct meanings identified - "selected_meaning": string, the meaning chosen based on domain context - "confidence": string, one of "high", "medium", or "low" - "rewritten_query": string, the query with homonyms replaced by disambiguated phrases - "no_homonyms_found": boolean, true if no homonyms were detected ## CONSTRAINTS - Preserve the original query's intent, scope, and specificity. - Do not introduce new entities, filters, or constraints not implied by the original query. - If confidence is "low" for any homonym, set a top-level field "requires_clarification": true and include a "clarification_question": string field with a concise question to ask the user. - Use the domain context to disambiguate. If the domain context is insufficient, default to the most common general meaning and flag low confidence. ## EXAMPLES Example 1: User query: "How do I set up a bank account for my mobile app?" Domain context: "Fintech application development documentation" Output: { "original_query": "How do I set up a bank account for my mobile app?", "homonyms_detected": [ { "term": "bank", "possible_meanings": ["financial institution", "river bank"], "selected_meaning": "financial institution", "confidence": "high" } ], "rewritten_query": "How do I set up a financial institution account for my mobile app?", "no_homonyms_found": false } Example 2: User query: "What is the current rate for a crane?" Domain context: "Construction equipment rental marketplace" Output: { "original_query": "What is the current rate for a crane?", "homonyms_detected": [ { "term": "crane", "possible_meanings": ["lifting machine", "bird species"], "selected_meaning": "lifting machine", "confidence": "high" } ], "rewritten_query": "What is the current rate for a lifting machine crane?", "no_homonyms_found": false } Example 3: User query: "Show me the latest pitch deck" Domain context: "Sales enablement platform" Output: { "original_query": "Show me the latest pitch deck", "homonyms_detected": [ { "term": "pitch", "possible_meanings": ["sales presentation", "sports field", "musical tone", "angle of slope"], "selected_meaning": "sales presentation", "confidence": "high" } ], "rewritten_query": "Show me the latest sales presentation deck", "no_homonyms_found": false }
To adapt this template, replace [USER_QUERY] with the raw user input and [DOMAIN_CONTEXT] with a short description of the knowledge base domain—such as "enterprise HR policy documents" or "medical device regulatory filings." The domain context is the primary signal for disambiguation, so make it specific enough to distinguish between common homonym meanings. If your system has access to user session history or role metadata, consider extending the prompt with a [USER_CONTEXT] placeholder that provides additional disambiguation signals. For production deployments, validate the output JSON against the schema before passing the rewritten query to your embedding model. If requires_clarification is true, route to a human review or clarification step rather than proceeding with a low-confidence rewrite.
Prompt Variables
Required inputs for the Homonym Resolution Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to check that the input is well-formed and safe.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The raw user query containing potential homonyms to resolve | I need a crane for my project | Non-empty string. Check for minimum length of 3 characters. Reject empty or whitespace-only input. |
[DOMAIN_CONTEXT] | Optional domain hint to bias homonym resolution toward a specific field | construction | Must be one of the allowed domain labels if provided: construction, wildlife, manufacturing, finance, computing, or null. Validate against allowed enum. |
[SESSION_HISTORY] | Prior conversation turns for contextual disambiguation of anaphora or topic continuity | User: I'm building a house. Assistant: What materials do you need? | Array of turn objects with role and content fields. May be empty array. Each turn must have valid role: user, assistant, or system. |
[KNOWLEDGE_BASE_TERMS] | List of domain-specific terms and their definitions from the target retrieval corpus | crane: a large machine for lifting heavy objects; crane: a tall wading bird | Array of term objects with term and definition fields. Minimum 1 entry. Each definition must be a non-empty string. Null allowed if no KB is available. |
[OUTPUT_SCHEMA] | The exact JSON schema the model must use for its response | See output contract table for field definitions | Valid JSON Schema object. Must include type: object at root. Validate with a JSON Schema parser before injection. Reject if schema is not parseable. |
[MAX_CANDIDATES] | Maximum number of disambiguated query candidates to return | 3 | Integer between 1 and 5. Default to 3 if not specified. Reject values outside range. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score required to accept a single resolution without generating fallback candidates | 0.7 | Float between 0.0 and 1.0. Default to 0.7. Reject values outside range. If null, prompt should use its own judgment. |
Implementation Harness Notes
How to wire the homonym resolution prompt into a production vector search pipeline with validation, retries, and observability.
This prompt is designed to sit between the user's raw query and your dense retrieval index. It should be called as a pre-retrieval transformation step: the user submits a query, your application sends it to the LLM with this prompt template, receives the disambiguated query and candidate expansions, and then executes the vector search using the rewritten output. The prompt is not a chatbot response—it is a structured query rewriter that must produce machine-consumable output. Wire it as a synchronous step in your retrieval pipeline, not as an optional enhancement. Latency budget is critical here; expect 200-500ms of added latency for the LLM call, which means you should set aggressive timeouts (1-2 seconds) and have a fallback path that sends the original query directly to retrieval if the LLM call fails or times out.
The output schema must be validated before the rewritten query hits your vector database. Require the model to return a JSON object with at minimum a rewritten_query field (the primary query to embed and search) and an expansions array of alternative phrasings for multi-query fusion. Validate that rewritten_query is a non-empty string, that expansions contains no more than [MAX_EXPANSIONS] items, and that none of the outputs are identical to the original query (which would indicate the model failed to detect or resolve any homonym). If validation fails, retry once with the same prompt plus the validation error message appended as a [CORRECTION_FEEDBACK] block. If the retry also fails, log the failure, fall back to the original query, and increment a homonym_resolution_failure metric. For high-stakes domains where incorrect disambiguation could surface misleading results, add a confidence threshold check: if the model's confidence score falls below [CONFIDENCE_THRESHOLD], route the query to a human review queue instead of proceeding automatically.
Model choice matters for this workflow. Smaller or older models often struggle with homonym detection because it requires world knowledge and contextual reasoning. Use a capable instruction-following model (GPT-4-class or equivalent) and set temperature to 0 or very low (0.0-0.1) to maximize deterministic, repeatable outputs. If you are operating in a high-throughput search system where per-query LLM calls are cost-prohibitive, consider caching: maintain an LRU cache keyed by normalized query strings so that repeated queries skip the LLM step entirely. For observability, log every resolution event with the original query, the rewritten query, the detected homonyms, the confidence score, the model version, and whether the result was served from cache, generated fresh, or fell back. This trace data is essential for debugging recall regressions and for building the homonym-heavy test sets that will measure whether this prompt actually improves retrieval precision over time.
Expected Output Contract
Defines the structure, types, and validation rules for the homonym resolution output. Use this contract to parse, validate, and integrate the model response into a vector search pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
resolved_query | string | Must be non-empty and differ from [ORIGINAL_QUERY] if a homonym was detected. If no homonym found, must equal [ORIGINAL_QUERY]. | |
homonym_detected | boolean | Must be true or false. If true, the 'homonyms' array must contain at least one entry. | |
homonyms | array of objects | Each object must have 'term', 'detected_sense', and 'resolved_sense' fields. Array length must be >= 1 if 'homonym_detected' is true. | |
homonyms[].term | string | Must be a substring of [ORIGINAL_QUERY]. Case-insensitive match is acceptable. | |
homonyms[].detected_sense | string | Must describe the ambiguous meaning that could cause retrieval errors. Cannot be null or empty. | |
homonyms[].resolved_sense | string | Must describe the contextually correct meaning based on [CONTEXT] or domain defaults. Cannot be identical to 'detected_sense'. | |
expansion_terms | array of strings | If present, each term must be a single word or short phrase relevant to the resolved sense. Used for query expansion in dense retrieval. | |
confidence | number | Must be a float between 0.0 and 1.0. If no homonym is detected, confidence must be >= 0.9. If a homonym is detected, confidence reflects resolution certainty. |
Common Failure Modes
Homonym resolution prompts fail in predictable ways that degrade retrieval precision. These cards cover the most common failure patterns and how to guard against them before they reach production.
Context Collapse in Short Queries
What to watch: Single-word or very short queries like 'jaguar' or 'apple' provide no surrounding context for the model to disambiguate. The prompt defaults to the most common interpretation, which is often wrong for domain-specific corpora. Guardrail: Require a minimum query length or prepend a domain context field such as '[DOMAIN: automotive]' before the prompt runs. If the query is too short, route to a clarifying question flow instead of guessing.
Over-Expansion Diluting Vector Similarity
What to watch: The prompt generates too many synonym replacements or expansions for a single homonym, producing a rewritten query that drifts semantically from the original intent. The resulting vector embedding retrieves irrelevant documents because the expansion terms dominate the query signal. Guardrail: Cap the number of expansion terms per homonym to 2-3 and validate that the rewritten query embedding cosine similarity to the original query embedding stays above a defined threshold such as 0.85 before executing retrieval.
Domain Blindness in Generic Models
What to watch: A general-purpose model lacks knowledge of your internal terminology, product names, or industry-specific homonyms. It resolves 'CRP' as C-reactive protein when your corpus uses it for Capacity Requirements Planning. Guardrail: Include a domain glossary or controlled vocabulary in the prompt context. Test against a golden dataset of domain-specific homonyms and measure resolution accuracy. If accuracy drops below 90%, switch to a fine-tuned model or add retrieval-augmented term lookup before disambiguation.
Silent Misresolution Without Confidence Signals
What to watch: The prompt confidently picks the wrong homonym interpretation and outputs a rewritten query without any indication of uncertainty. Downstream retrieval returns authoritative-looking but irrelevant results, and the error goes undetected. Guardrail: Require the prompt to output a confidence score alongside the rewritten query. Route low-confidence outputs to a human review queue or fallback multi-candidate retrieval. Log all low-confidence resolutions for eval analysis.
Entity Collision Across Document Collections
What to watch: The same homonym maps to different entities in different sub-collections of your corpus. 'Mercury' could be a planet, an element, a car model, or a Roman god depending on which index partition is queried. A single global disambiguation produces wrong results for targeted searches. Guardrail: Pass the target collection or index name as an input variable to the prompt. Generate collection-aware disambiguations. If the search spans multiple collections, produce separate rewritten queries per collection rather than one compromise query.
Prompt Drift After Vocabulary Updates
What to watch: Your domain vocabulary, product names, or acronym list changes over time, but the prompt still references stale terms. New homonyms enter the corpus and go unresolved, while old resolutions become incorrect. Guardrail: Version your domain glossary alongside the prompt. Run regression tests against an updated golden dataset whenever the vocabulary changes. Automate a periodic audit that compares prompt-resolved terms against the current controlled vocabulary and flags mismatches.
Evaluation Rubric
Use this rubric to test whether the homonym resolution prompt produces safe, correct, and useful rewrites before deploying to production vector search. Each criterion targets a specific failure mode observed in homonym-heavy retrieval pipelines.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Homonym Detection Recall | All homonyms in [QUERY] are identified and listed in the output | A known homonym from the test set is missing from the detected terms list | Run against a golden set of 50 queries containing known homonyms; require recall >= 0.95 |
Contextual Sense Selection Accuracy | The selected sense for each homonym matches the ground-truth label given the [CONTEXT] field | The prompt selects the wrong sense for a homonym (e.g., 'bat' as animal when context indicates sports) | Evaluate on a labeled homonym disambiguation benchmark; require accuracy >= 0.90 |
Replacement Term Appropriateness | Each replacement term is a valid synonym or expansion for the resolved sense and does not introduce new ambiguity | Replacement term is unrelated to the resolved sense, is itself a homonym, or is a hallucinated word | Spot-check 100 outputs; flag any replacement not found in a controlled vocabulary or embedding neighbor check |
Output Schema Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed | Output is missing required fields, contains extra untyped keys, or is not parseable as JSON | Automated schema validation in CI; reject any response that fails JSON Schema validation |
Query Rewrite Semantic Preservation | The rewritten query preserves the original user intent while resolving homonym ambiguity | The rewrite changes the meaning of the original query or drops a constraint present in the input | Compute cosine similarity between original and rewritten query embeddings; require similarity >= 0.85 on intent-preserving pairs |
No Over-Resolution of Non-Homonyms | Non-homonym terms are left unchanged in the rewritten query | The prompt incorrectly flags a non-homonym as ambiguous and replaces it, distorting the query | Run against a negative test set of queries with no homonyms; require zero false-positive replacements |
Confidence Score Calibration | The [CONFIDENCE] score correlates with actual correctness: high scores for correct resolutions, low scores for incorrect ones | High-confidence outputs are frequently wrong, or low-confidence outputs are frequently correct | Binned reliability diagram check; require ECE (Expected Calibration Error) <= 0.10 on a held-out test set |
Latency Budget Compliance | End-to-end prompt execution completes within the defined latency budget for pre-retrieval rewriting | Prompt exceeds the latency budget, causing downstream retrieval timeout or user-facing delay | Measure p95 latency over 1000 requests; require p95 <= [LATENCY_BUDGET_MS] milliseconds |
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 homonym resolution prompt and a small test set of 20-30 ambiguous queries. Remove strict output schema requirements initially—accept free-text JSON or even a simple rewritten query string. Focus on getting the model to identify the homonym and produce a plausible replacement before adding validation.
codeYou are a query disambiguation assistant. Given a user query that may contain a homonym, identify the ambiguous term, list its possible meanings, and rewrite the query using the most likely meaning for a general knowledge base. Query: [USER_QUERY]
Watch for
- The model may hallucinate homonyms where none exist, over-flagging unambiguous terms
- Rewrites may drift semantically from the original intent when the model guesses wrong
- Without a domain context signal, resolution defaults to the most common meaning, which may be incorrect for your corpus

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