Inferensys

Prompt

Synonym Expansion with Entity Recognition Boost Prompt

A practical prompt playbook for expanding user queries with synonyms while protecting recognized entities, product names, and proper nouns from inappropriate replacement. Includes entity boundary detection and false-positive tagging checks.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for entity-aware synonym expansion.

This prompt is designed for search engineers and RAG developers who need to improve keyword and vector recall without corrupting named entities. The core job is to take a user query and produce a set of expanded terms that includes synonyms, related concepts, and alternative phrasings, while strictly preserving recognized entities, product names, and proper nouns in their original form. This is not a general-purpose synonym generator; it is a precision tool for enterprise search pipelines where entity integrity is non-negotiable and inappropriate synonym replacement can cause catastrophic relevance failures.

Use this prompt when your retrieval system operates over a corpus with high entity density—product catalogs, technical documentation, legal contracts, or medical literature—and you have a defined entity recognition pipeline or a controlled vocabulary of protected terms. The prompt expects a list of protected entities as input alongside the query, and it will produce expansion candidates that respect entity boundaries. Do not use this prompt for open-domain web search, casual chatbot queries, or scenarios where entity boundaries are ambiguous and no entity list is available. In those cases, a simpler synonym expansion prompt without entity constraints will be more appropriate and less prone to false-positive entity tagging.

Before deploying this prompt, ensure you have a reliable upstream entity recognition step. The prompt's effectiveness depends entirely on the quality of the entity list you provide. If your entity detector misses a product name, the prompt may expand it into inappropriate synonyms. Conversely, if your detector over-tags common nouns as entities, you will lose legitimate expansion opportunities. Plan to pair this prompt with an entity recognition model, a controlled vocabulary lookup, or a regex-based product name matcher. In high-stakes domains like healthcare or legal search, always include a human review step for the expanded query before it hits production retrieval, and log every expansion decision with entity boundary evidence for auditability.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Synonym Expansion with Entity Recognition Boost Prompt delivers value and where it introduces risk.

01

Good Fit: Enterprise Search with Branded Terminology

Use when: your corpus contains product names, SKUs, legal entities, or proper nouns that must not be altered. Guardrail: Provide an entity glossary or extraction schema so the prompt can lock recognized terms before expanding the remaining query tokens.

02

Bad Fit: Open-Domain Web Search

Avoid when: the entity landscape is unknown or unbounded. Risk: The prompt may hallucinate entity boundaries or miss novel proper nouns, leading to false-positive entity tagging. Guardrail: Use a dedicated NER model upstream and fall back to a generic expansion prompt if entity coverage is incomplete.

03

Required Inputs

Must provide: the raw user query, a domain context label, and either an entity list, a glossary, or explicit entity boundary markers. Guardrail: If entity sources are missing, route to a standard synonym expansion prompt and log the gap for coverage review.

04

Operational Risk: Entity Leakage into Synonyms

Risk: Recognized entities bleed into the expansion step and get replaced with inappropriate synonyms. Guardrail: Implement a post-expansion diff check that flags any term marked as an entity in the input that appears altered in the output, then reject or quarantine the result.

05

Operational Risk: False-Positive Entity Tagging

Risk: Common words or domain terms are incorrectly locked as entities, preventing legitimate synonym expansion. Guardrail: Add a confidence threshold for entity tagging. Terms below the threshold should be treated as expandable and logged for entity dictionary review.

06

Latency and Pipeline Complexity

Risk: Adding entity recognition logic increases prompt length and model reasoning time. Guardrail: Measure end-to-end latency against a baseline expansion prompt. If the boost adds more than 200ms at P95, consider caching entity boundaries per query domain or moving entity detection to a pre-processing step.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template that expands a user query with synonyms while protecting recognized entities from inappropriate replacement.

This template is designed to be dropped directly into your application code or prompt management system. It expects a user query, an optional domain context, and a list of recognized entities that must be preserved exactly as they appear. The prompt instructs the model to generate synonym expansions for non-entity terms while leaving proper nouns, product names, and technical identifiers untouched. Use square-bracket placeholders to inject dynamic values at runtime before sending the request to the model.

text
You are a query expansion assistant for an enterprise search system. Your task is to expand a user query with synonyms and related terms to improve retrieval recall, while strictly preserving all recognized named entities, product names, and proper nouns exactly as they appear.

## Input
User Query: [USER_QUERY]
Domain Context: [DOMAIN_CONTEXT]
Recognized Entities (do NOT modify or expand these): [RECOGNIZED_ENTITIES]

## Constraints
1. Do NOT generate synonyms, alternatives, or expansions for any term listed in Recognized Entities. Preserve them verbatim.
2. For all other terms in the query, generate up to [MAX_SYNONYMS_PER_TERM] synonyms or related phrases that are relevant to the Domain Context.
3. If a term is ambiguous, prefer the sense most relevant to the Domain Context.
4. Exclude synonyms that would contradict any negation terms (e.g., "not," "excluding," "without") present in the query.
5. Do not introduce new entities, facts, or concepts not implied by the original query.
6. If no meaningful synonyms exist for a term, skip it rather than forcing low-quality expansions.

## Output Schema
Return a JSON object with this exact structure:
{
  "original_query": "string",
  "preserved_entities": ["string"],
  "expansions": [
    {
      "original_term": "string",
      "synonyms": ["string"],
      "confidence": 0.0
    }
  ],
  "expanded_query_variants": ["string"],
  "warnings": ["string"]
}

## Field Descriptions
- original_query: The user query exactly as provided.
- preserved_entities: The list of entities that were protected from expansion.
- expansions: Array of objects, one per expanded term.
  - original_term: The term from the query that was expanded.
  - synonyms: Array of synonym strings, ordered by relevance (most relevant first).
  - confidence: A score from 0.0 to 1.0 indicating confidence that each synonym is contextually appropriate.
- expanded_query_variants: Up to [MAX_VARIANTS] full query strings combining original terms with selected synonyms. Each variant should be a coherent, searchable query.
- warnings: Any concerns about entity boundary ambiguity, potential false-positive entity tagging, or terms that could not be confidently expanded.

## Examples
[FEW_SHOT_EXAMPLES]

## Risk Level
[RISK_LEVEL]

Adaptation notes: Replace [USER_QUERY] with the raw user input. [DOMAIN_CONTEXT] should describe the knowledge domain (e.g., "enterprise cloud infrastructure documentation"). [RECOGNIZED_ENTITIES] must be a pre-extracted list from your entity recognition pipeline—never rely on the model to identify entities without verification. [MAX_SYNONYMS_PER_TERM] and [MAX_VARIANTS] control output size and should be tuned against your retrieval system's query length limits. [FEW_SHOT_EXAMPLES] should include 2-3 worked examples showing correct entity preservation and domain-appropriate synonym selection. Set [RISK_LEVEL] to "low" for internal search, "medium" for customer-facing retrieval where entity errors cause confusion, or "high" for regulated domains requiring human review of expansions before retrieval execution. Always validate the output JSON against the schema before passing expanded queries to your search backend. If the warnings field is non-empty, route the output for human review or log it for offline evaluation.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Synonym Expansion with Entity Recognition Boost Prompt. Each variable must be validated before the prompt is assembled to prevent entity leakage, term collisions, and expansion drift.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw user search string to expand

Tesla Model 3 battery replacement cost

Non-empty string. Check for PII redaction. Reject if length > 2000 chars or contains only stop words.

[ENTITY_LIST]

Pre-recognized named entities to protect from synonym replacement

["Tesla Model 3", "LG Chem"]

Must be a JSON array of strings. Validate each entry against entity boundary detection. Empty array allowed if no entities detected.

[DOMAIN_CONTEXT]

Domain scope constraining synonym generation

automotive repair and electric vehicle maintenance

Non-empty string. Must match one of the allowed domain labels in the taxonomy registry. Reject if generic or ambiguous.

[EXPANSION_DEPTH]

Controls how many synonym tiers to generate (1-3)

2

Integer 1-3. Depth 1 = direct synonyms only. Depth 3 = hyponyms and hypernyms. Default to 2 if null.

[MAX_TERMS]

Hard ceiling on total expanded terms returned

15

Integer 5-50. Enforce at output validation. Exceeding this triggers truncation with a warning log.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for a term to be included in output

0.7

Float 0.0-1.0. Terms below threshold are dropped. Set to 0.0 to disable filtering. Log dropped terms for observability.

[OUTPUT_SCHEMA]

Expected JSON structure for the expansion response

{"original_query": "...", "protected_entities": [...], "expanded_terms": [{"term": "...", "confidence": 0.9, "source": "..."}]}

Must be a valid JSON Schema object. Validate against schema registry version. Reject if schema requires fields not in the prompt contract.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Synonym Expansion with Entity Recognition Boost prompt into a production retrieval pipeline with validation, retries, and entity boundary safeguards.

This prompt is designed to sit between the user's raw query and your retrieval backends. It accepts a natural language query and a list of recognized entities, then returns expanded terms while protecting those entities from inappropriate synonym replacement. The harness should treat this prompt as a pre-retrieval transformation step: the output terms feed directly into keyword search clauses, vector embedding generation, or hybrid fusion logic. Because the prompt must respect entity boundaries, the harness must provide accurate entity annotations upstream—typically from a dedicated NER model, a product catalog lookup, or a knowledge graph traversal—before calling this prompt.

Wire the prompt into your application as an async function with a strict input contract. The function signature should accept query: string and entities: Array<{name: string, type: string, start_char: number, end_char: number}>. Validate that entity spans align with the query string before calling the model; mismatched spans cause the prompt to protect the wrong tokens. On the output side, parse the model response against a JSON schema that includes expanded_terms: Array<{term: string, weight: number, source: 'synonym' | 'concept' | 'entity_alias'}> and protected_entities: Array<{name: string, type: string}>. If the model returns malformed JSON, retry once with a repair prompt that includes the raw output and the expected schema. If the second attempt fails, log the failure and fall back to the original query terms without expansion—never block the user's search on a prompt failure. For high-recall use cases where missing a synonym is costly, implement a second retry with a lower temperature to reduce output variance.

Model choice matters here. Use a model with strong instruction-following and JSON output discipline, such as GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro. Set temperature between 0.1 and 0.3 to balance creativity in synonym generation with entity boundary stability. Avoid models that frequently rephrase entity names or hallucinate entity types. Log every call with the input query, detected entities, expanded terms, model latency, and any validation errors. This trace data is essential for debugging entity boundary violations and measuring expansion recall in production. Before shipping, run the prompt against a golden set of 50–100 queries with known entities and expected expansions. Measure entity preservation rate (entities must appear verbatim in the output), term relevance precision, and recall improvement against your retrieval metrics. Set a release gate: entity preservation must exceed 98% before this prompt reaches users. If your domain includes regulated content, route any query containing flagged entity types to a human review queue before expansion terms are applied to retrieval.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when expanding queries with entity-aware synonym generation and how to guard against it.

01

Entity Leakage into Synonym Sets

What to watch: Recognized named entities, product codes, or proper nouns are incorrectly treated as common terms and expanded into inappropriate synonyms. A product name like 'Apple' might be expanded to 'fruit' or 'tech company' when the entity boundary is missed. Guardrail: Implement strict entity boundary detection before expansion. Use a pre-pass entity recognition step and lock recognized spans. Validate that no expanded term list contains entity surface forms that were marked as protected.

02

False-Positive Entity Tagging

What to watch: Common words or domain terms are incorrectly tagged as protected entities, preventing legitimate synonym expansion. A generic term like 'pipeline' might be locked as a product name, blocking useful expansions like 'workflow' or 'data flow'. Guardrail: Maintain an entity confidence threshold and a domain-specific allowlist of terms that should always be expanded. Log all blocked expansions with the entity tag that caused the block for audit and threshold tuning.

03

Entity Boundary Fragmentation

What to watch: Multi-word entities are partially recognized, causing partial expansion that breaks meaning. 'San Francisco' might have 'Francisco' expanded to 'Frank' while 'San' is left untouched, producing nonsensical query variants. Guardrail: Use span-level entity recognition with strict boundary adherence. Validate that multi-token entities are treated as atomic units. Add a post-expansion check that no expanded term set contains fragments of a recognized multi-word entity.

04

Over-Expansion Causing Precision Collapse

What to watch: Too many synonyms are generated, including low-relevance or tangentially related terms that flood the retrieval index with noise. Recall improves but precision drops sharply, burying relevant documents under irrelevant matches. Guardrail: Apply a relevance score threshold to generated synonyms and cap the total number of expanded terms per query. Use a confidence calibration eval to measure precision-recall trade-off at different expansion budgets before deployment.

05

Domain Context Drift in Expansion

What to watch: Synonyms are generated from a general language model without sufficient domain grounding, producing terms that are valid in general English but wrong for the target domain. 'Cell' in a biology context might be expanded to 'battery' or 'prison room'. Guardrail: Always provide domain context in the prompt, including a glossary or sample corpus. Validate expanded terms against a domain-specific term frequency list. Flag and reject expansions that fall outside the expected domain vocabulary.

06

Negation and Exclusion Scope Violation

What to watch: Synonyms are generated for terms inside a negation or exclusion scope, inverting the user's intent. A query like 'error codes excluding timeout' might expand 'timeout' to 'delay' or 'latency', causing the retrieval to include documents the user explicitly wanted to exclude. Guardrail: Detect negation and exclusion cues before expansion and mark the affected spans as protected from synonym generation. Add a contradiction check that verifies no expanded term set introduces terms that conflict with explicit exclusion constraints.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of synonym expansion outputs before deployment. Use this rubric to test whether the prompt preserves entities, avoids inappropriate synonyms, and produces production-ready results.

CriterionPass StandardFailure SignalTest Method

Entity Preservation

All recognized entities from [INPUT_QUERY] appear verbatim in the expanded output without synonym substitution

A product name, person, or location is replaced with a generic synonym (e.g., 'Apple' becomes 'fruit')

Exact string match of each entity in [RECOGNIZED_ENTITIES] against the expanded terms list

Entity Boundary Accuracy

Multi-word entities are treated as atomic units; no partial replacement occurs within entity spans

A synonym is inserted inside a multi-word entity (e.g., 'San Francisco' becomes 'Saint Francisco')

Span-level check: verify no expanded term modifies a substring of any entity in [RECOGNIZED_ENTITIES]

Synonym Relevance

All generated synonyms are semantically related to the non-entity terms in the original query within the [DOMAIN_CONTEXT]

A synonym is unrelated to the query intent or domain (e.g., 'bank' expanded to 'slope' in a finance context)

Human review of 50 random samples; pass if >90% of synonyms are judged relevant by a domain expert

False-Positive Entity Tagging

No common nouns or generic terms are incorrectly flagged as entities requiring protection

A generic term like 'server' or 'cloud' is locked and excluded from expansion when it should be expanded

Compare [RECOGNIZED_ENTITIES] against a curated list of known non-entity terms; flag overlap

Expansion Coverage

At least one relevant synonym is generated for each expandable non-entity content word in the query

A key concept word receives zero synonyms while stop words are correctly ignored

Count unique expandable terms in [INPUT_QUERY]; verify each has at least one synonym in the output

Output Schema Compliance

Output matches the [OUTPUT_SCHEMA] exactly: all required fields present, correct types, no extra fields

Missing 'expanded_terms' array, malformed JSON, or extra unexpected fields in the response

JSON Schema validation against [OUTPUT_SCHEMA] using a standard validator; must pass with zero errors

Confidence Score Calibration

Low-confidence synonyms (score < [CONFIDENCE_THRESHOLD]) are flagged or excluded per [CONSTRAINTS]

A synonym with obvious semantic drift receives a high confidence score, or all scores are uniformly 0.9+

Check distribution of confidence scores; flag if no scores fall below 0.5 in a diverse test set

Negation Boundary Preservation

Synonyms do not contradict or invert negation scope present in the original query

A negated term like 'not urgent' generates a synonym 'critical' that inverts the meaning

Parse query for negation markers; verify no expanded term for a negated word carries opposite polarity

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small entity dictionary. Use a single LLM call that outputs both expanded terms and entity spans. Skip strict schema enforcement initially—accept JSON or markdown lists. Test with 20–30 queries from your domain.

code
[SYSTEM]
You are a query expansion assistant. Given a user query and an entity list, expand the query with synonyms for non-entity terms only. Preserve all entities exactly as they appear.

[ENTITY_LIST]
[product_names], [company_names], [technical_terms]

[QUERY]
[user_query]

Return expanded terms as a list with a note indicating which terms were protected entities.

Watch for

  • Entity boundary errors on multi-word names like "Red Hat Enterprise Linux"
  • Over-expansion of short queries where every term looks like a candidate
  • No confidence scoring, so low-quality expansions slip through
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.