Inferensys

Prompt

Synonym Expansion with Recall-Oriented Evaluation Prompt

A practical prompt playbook for search quality engineers who need to measure whether synonym expansion actually improves retrieval recall. This prompt produces a before-and-after comparison using your document corpus and relevance judgments, with per-query recall deltas and statistical significance notes.
Developer reviewing semantic search engine results on laptop, relevance scores visible, technical search demo.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and limitations for the recall-oriented evaluation prompt.

This prompt is for search quality engineers and RAG operators who have already deployed a synonym expansion step and need to measure its impact on retrieval recall. It takes a set of test queries, a document corpus, relevance judgments, and the expansion outputs, then produces a structured before-and-after comparison. Use this when you need evidence that your expansion strategy helps rather than hurts, and when you need per-query diagnostics to identify which queries benefit and which degrade.

Do not use this prompt for generating expansions themselves; use the Synonym Expansion Prompt Template for Keyword Search or the Concept Expansion Prompt for Vector Retrieval for that. This prompt assumes you already have expansion outputs and need evaluation, not generation. The ideal user has access to a labeled relevance dataset (qrels), a fixed document corpus, and the output of a synonym expansion pipeline. Without these three inputs, the prompt cannot produce a meaningful comparison. The evaluation is recall-oriented, meaning it measures how many relevant documents were retrieved that would have been missed without expansion. It does not measure precision, ranking quality, or end-to-end answer accuracy—pair it with a separate precision or NDCG evaluation for a complete picture.

Before running this prompt, ensure your relevance judgments are current and representative of real user needs. Stale or sparse judgments will produce misleading recall numbers. Also verify that your expansion outputs are deterministic enough to evaluate; if your expansion prompt introduces high variance, run multiple trials and report confidence intervals. The prompt includes statistical significance notes, but these are approximations—for production gate decisions, supplement with proper statistical tests. Finally, treat per-query recall deltas as diagnostic signals, not final verdicts. A query that degrades after expansion may indicate a domain mismatch, an over-expansion problem, or a judgment gap rather than a broken expansion strategy. Use the output to prioritize manual review of the worst-affected queries before rolling back or tuning your expansion step.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Synonym Expansion with Recall-Oriented Evaluation Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your current retrieval pipeline and evaluation maturity.

01

Good Fit: Pre-Release Retrieval QA

Use when: you are about to ship a synonym expansion change and need a structured, quantitative before-and-after recall comparison against a curated relevance judgment set. Guardrail: freeze the document corpus and judgment set before running the eval to ensure a stable baseline.

02

Bad Fit: Real-Time Query Guard

Avoid when: you need a low-latency, inline expansion validator for production traffic. This prompt is designed for offline evaluation, not per-query gating. Guardrail: use a lightweight, rule-based confidence threshold or a cached expansion lookup for online checks instead.

03

Required Inputs: Judgments and Corpus

Risk: running this prompt without a representative set of relevance judgments and a fixed document corpus produces ungrounded, misleading recall numbers. Guardrail: validate that your judgment set covers tail queries, not just head queries, and that the corpus matches your production index.

04

Operational Risk: Statistical Overconfidence

Risk: treating small per-query recall deltas as significant when the judgment set is small or unrepresentative. The prompt reports deltas but cannot replace a proper power analysis. Guardrail: pair the prompt output with a human-reviewed significance threshold and a minimum query count before accepting a regression flag.

05

Operational Risk: Corpus Drift

Risk: reusing an old evaluation corpus that no longer matches the production index. Recall improvements measured on stale documents may not hold in production. Guardrail: version your evaluation corpus alongside your index and re-sample whenever the production document distribution shifts meaningfully.

06

Bad Fit: No Baseline Expansion

Avoid when: you have no existing expansion strategy to compare against. The prompt measures recall delta, not absolute recall quality. Guardrail: establish a baseline expansion (even a simple synonym dictionary) before running this comparative evaluation.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that generates synonym expansions and a structured recall evaluation report from a document corpus and relevance judgments.

This prompt is the core of the Synonym Expansion with Recall-Oriented Evaluation playbook. It instructs the model to act as a search quality engineer, taking a user query, a set of relevance judgments, and a document corpus to produce a before-and-after recall comparison. The output is a structured report, not just a list of synonyms, making it directly usable in a CI/CD pipeline for search quality regression testing.

text
You are a search quality engineer evaluating the impact of query expansion on retrieval recall.

Your task is to expand a user query with synonyms and related terms, then measure the change in recall against a provided document corpus and relevance judgments.

## INPUT
- User Query: [USER_QUERY]
- Domain Context: [DOMAIN_CONTEXT]
- Document Corpus (ID, Title, Snippet): [DOCUMENT_CORPUS]
- Relevance Judgments (Query ID, Document ID, Relevance Score): [RELEVANCE_JUDGMENTS]
- Expansion Constraints: [EXPANSION_CONSTRAINTS]

## PROCEDURE
1. Generate a list of synonym and related term expansions for the user query, respecting the provided constraints.
2. For each expansion, assign a confidence score (0.0 to 1.0) and a brief rationale.
3. Simulate retrieval using the original query against the document corpus. Record which documents are retrieved.
4. Simulate retrieval using the expanded query (original terms + expansions) against the document corpus. Record which documents are retrieved.
5. Calculate recall@[K] for both the original and expanded queries using the provided relevance judgments.
6. Compute the per-query recall delta.

## OUTPUT_SCHEMA
Return a single JSON object with this exact structure:
{
  "query_id": "string",
  "original_query": "string",
  "expansions": [
    {
      "term": "string",
      "confidence": number,
      "rationale": "string"
    }
  ],
  "original_recall": {
    "recall_at_k": number,
    "retrieved_relevant_docs": ["doc_id"],
    "total_relevant_docs": number
  },
  "expanded_recall": {
    "recall_at_k": number,
    "retrieved_relevant_docs": ["doc_id"],
    "total_relevant_docs": number
  },
  "recall_delta": number,
  "statistical_note": "string describing if the delta is meaningful given the corpus size",
  "failure_flags": ["string describing any issues like zero recall, over-expansion, or missing judgments"]
}

## CONSTRAINTS
- Do not expand named entities, product codes, or proper nouns unless they have known aliases in the domain context.
- Preserve the original query's negation scope. Do not add synonyms that contradict exclusionary terms.
- If no relevance judgments are provided for a document, treat it as non-relevant.
- If the original query retrieves zero relevant documents, flag this in failure_flags.
- Limit expansions to a maximum of [MAX_EXPANSIONS] terms.

To adapt this template, replace each square-bracket placeholder with your application's data. The [DOCUMENT_CORPUS] should be a serialized list of document objects with at least an ID and a snippet for the model to reason over. The [RELEVANCE_JUDGMENTS] are your ground truth, typically a CSV or JSON structure mapping query-document pairs to relevance scores. For high-stakes search systems, always run this evaluation against a held-out golden query set before deploying a new expansion prompt. The failure_flags field is your primary signal for manual review; automate alerts on any non-empty flag array.

IMPLEMENTATION TABLE

Prompt Variables

Replace each placeholder before sending the prompt. Validation notes describe how to confirm the input is well-formed before it reaches the model.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The original user question to expand with synonyms

How do I configure SSO for the admin dashboard?

Non-empty string; max 500 chars; must contain at least one searchable term

[CORPUS_DOCUMENTS]

The document set against which recall will be measured

["doc_001": "Single sign-on setup guide...", "doc_002": "Dashboard admin..."]

Array of objects with id and text fields; min 10 documents for statistical significance; no duplicate ids

[RELEVANCE_JUDGMENTS]

Ground-truth mapping of which documents are relevant to the query

{"doc_001": "highly_relevant", "doc_002": "not_relevant"}

JSON object with doc_id keys and relevance labels; must cover all documents in corpus; labels must use controlled vocabulary

[EXPANSION_STRATEGY]

The synonym generation approach to evaluate

keyword_synonym_expansion_v2

Must match a registered strategy name in the evaluation harness; null allowed for baseline no-expansion run

[CONFIDENCE_THRESHOLD]

Minimum confidence score for a synonym to be included in the expanded query

0.7

Float between 0.0 and 1.0; lower values increase recall but risk term drift; validate against golden set before production use

[MAX_EXPANDED_TERMS]

Upper bound on the number of synonym terms added to the original query

5

Integer between 1 and 20; budget check enforced in harness before model call; exceeding limit triggers truncation with warning

[DOMAIN_CONTEXT]

Optional domain or taxonomy scope to constrain synonym generation

enterprise_identity_and_access_management

String matching a registered domain key; null allowed; when provided, expansion must not generate terms outside domain boundaries

[STATISTICAL_SIGNIFICANCE_LEVEL]

Alpha threshold for reporting whether recall differences are significant

0.05

Float between 0.01 and 0.10; used in paired statistical test; harness logs warning if sample size is insufficient for chosen level

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Synonym Expansion with Recall-Oriented Evaluation Prompt into an automated CI pipeline for regression testing and release gating.

This prompt is designed to be the final evaluation gate in a synonym expansion pipeline. It is not a user-facing prompt but a developer-facing evaluation tool. The harness should be invoked automatically after any change to the upstream expansion prompt, the domain glossary, or the retrieval index configuration. The primary job of this harness is to take a batch of queries, their expanded forms from the candidate system, a golden set of relevance judgments, and a document corpus, and produce a structured report comparing recall metrics before and after expansion. The output is a JSON report that downstream CI systems can parse to pass or fail a release.

To integrate this prompt, construct a test runner that iterates over a curated golden query set. For each query, execute the candidate expansion prompt to generate the expanded query, then run both the original and expanded queries against your retrieval system. Collect the top-K document IDs for each. Pass the full matrix—original query, expanded query, original results, expanded results, and the golden relevance labels for each query—into this evaluation prompt as [INPUT]. The prompt expects a structured [INPUT] object containing query_id, original_query, expanded_query, original_results (list of doc IDs), expanded_results (list of doc IDs), and relevance_judgments (a map of doc ID to relevance score). The [OUTPUT_SCHEMA] should be enforced as a strict JSON object with per-query recall deltas, a pass/fail summary, and statistical significance notes. Use a JSON validator in your harness to retry the call if the output does not conform to the schema, and log schema violations for prompt debugging.

For production CI integration, store the golden query set and relevance judgments in version control alongside the prompt templates. The evaluation harness should be triggered on pull requests that modify any file in the prompts/synonym-expansion/ directory. Set a minimum recall improvement threshold (e.g., 5% relative recall gain with p < 0.05) as a release gate. If the evaluation prompt reports a pass status of false or flags significant regressions, block the merge. Log the full evaluation report as a CI artifact for auditability. Avoid running this evaluation on every commit to unrelated code paths; scope the trigger to prompt and retrieval configuration changes to manage compute costs. For high-stakes deployments, add a manual review step that requires a search quality engineer to sign off on the evaluation report before the prompt change reaches production.

IMPLEMENTATION TABLE

Expected Output Contract

Machine-readable contract for the recall comparison report. Use this schema to validate the model response before ingesting it into your evaluation dashboard or CI pipeline.

Field or ElementType or FormatRequiredValidation Rule

report_id

string (UUID v4)

Must match regex ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

corpus_id

string

Must equal the provided [CORPUS_ID] input parameter

baseline_recall

number (0.0-1.0)

Must be between 0 and 1 inclusive; parse as float and clamp if out of range

expanded_recall

number (0.0-1.0)

Must be between 0 and 1 inclusive; parse as float and clamp if out of range

recall_delta

number (-1.0 to 1.0)

Must equal expanded_recall minus baseline_recall within 0.001 tolerance

statistical_significance

object

Must contain p_value (number) and test_method (string enum: mcnemar, bootstrap, ttest); p_value must be between 0 and 1

per_query_deltas

array of objects

Each element must have query_id (string), baseline_hits (integer >= 0), expanded_hits (integer >= 0), delta (integer), and relevant_docs_found (integer >= 0)

failure_queries

array of strings

If present, each string must match a query_id from per_query_deltas where delta is negative; null allowed if no regressions

PRACTICAL GUARDRAILS

Common Failure Modes

Synonym expansion prompts fail in predictable ways that degrade recall, introduce noise, or break downstream retrieval. Here are the most common failure modes and how to guard against them before they reach production.

01

Over-Expansion and Query Drift

What to watch: The prompt generates too many synonyms or overly broad terms, causing the expanded query to retrieve irrelevant documents that dilute result quality. This often happens when the model prioritizes coverage over precision or lacks domain boundaries. Guardrail: Set a hard token or term-count budget in the prompt, require per-term relevance scores, and implement a post-expansion filter that drops terms below a minimum relevance threshold before retrieval executes.

02

Term Collision Across Domains

What to watch: A query term has different meanings in different contexts (e.g., 'cell' in biology vs. telecommunications), and the expansion prompt generates synonyms for the wrong domain. This produces misleading expansions that actively harm recall. Guardrail: Always provide a domain context string or glossary in the prompt input. Add a disambiguation step that asks the model to identify the domain before expanding, and validate expanded terms against a domain-specific controlled vocabulary when available.

03

Negation Scope Violation

What to watch: The expansion prompt adds synonyms for terms inside a negation scope (e.g., expanding 'error' in 'not an error' to 'mistake, fault, bug'), inverting the user's exclusionary intent and retrieving documents the user explicitly wanted to avoid. Guardrail: Include explicit negation-handling instructions in the prompt template. Require the model to identify and preserve negation boundaries, and add an eval check that verifies expanded terms do not contradict negated clauses in the original query.

04

Entity Corruption During Expansion

What to watch: Named entities, product codes, or proper nouns get replaced with generic synonyms (e.g., 'iPhone 15' becomes 'smartphone, mobile device'), losing the specificity required for precise retrieval. Guardrail: Add an entity-preservation rule to the prompt that instructs the model to recognize and protect named entities, product identifiers, and proper nouns. Implement a pre-expansion entity detection step and validate that recognized entities appear unchanged in the expanded output.

05

Confidence Miscalibration

What to watch: The model assigns high confidence scores to low-quality or irrelevant synonyms, causing downstream systems to trust and use bad expansions. Conversely, good synonyms receive low scores and get filtered out. Guardrail: Require the prompt to produce confidence scores with explicit rationale for each term. Calibrate these scores against a golden evaluation set during prompt QA, and set a minimum confidence threshold validated by recall-impact measurement before deployment.

06

Context Blindness in Conversational Settings

What to watch: In multi-turn conversations, the expansion prompt treats each query in isolation, generating synonyms that ignore prior turns, resolved entities, or established context. This produces expansions that contradict or duplicate earlier clarifications. Guardrail: Include the conversation history or a session context summary as a required input to the expansion prompt. Add a context-consistency eval that checks whether expanded terms align with previously established entities and intent from the session.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of your synonym expansion prompt before shipping it to your CI pipeline. Each criterion includes a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Recall Improvement

Mean recall@k increases by >=5% on the golden query set when using expanded queries versus the original query.

Mean recall delta is negative or <5%, indicating expansion adds noise or misses relevant terms.

Run retrieval with and without expansion on the golden query set. Compute per-query recall@k delta and aggregate the mean.

Precision Preservation

Mean precision@k does not drop by more than 3% relative to the baseline original query.

Mean precision drops >3%, indicating over-expansion or irrelevant term injection.

Compute precision@k for both runs. Compare the mean difference. Flag any query where precision drops >10%.

Term Relevance

=90% of expanded terms are judged relevant by the LLM judge or human reviewer.

Relevance rate drops below 90%, indicating the prompt is generating unrelated synonyms.

Sample 50 expanded queries. For each, have an LLM judge or human label each term as relevant or irrelevant. Compute the percentage.

Schema Compliance

100% of outputs parse successfully against the [OUTPUT_SCHEMA] without field-level errors.

Any output fails to parse, has missing required fields, or contains values of the wrong type.

Validate every output in the test run against the JSON schema. Use a strict validator that rejects extra fields.

Confidence Calibration

Terms with a confidence score below the [CONFIDENCE_THRESHOLD] are excluded from the final query in >=95% of cases.

Low-confidence terms frequently appear in the final query, or high-confidence terms are incorrectly dropped.

Check the harness logic. For 100 test outputs, verify that no term with confidence < [CONFIDENCE_THRESHOLD] is passed to the retriever.

Negation Handling

No expanded term contradicts a negated constraint in the original query (e.g., 'wireless' for 'not wireless').

A contradiction is detected by the eval harness, indicating semantic inversion.

Create a small adversarial test set of 10 queries with explicit negations. Assert that no expanded term is an antonym of a negated entity.

Entity Preservation

Recognized named entities from [ENTITY_LIST] are never replaced by a synonym in the expanded output.

A proper noun, product name, or known entity is replaced, causing a retrieval miss.

Run the prompt on 20 queries containing known entities. Assert that the original entity string appears verbatim in the final expanded query.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a small, hand-labeled relevance judgment set. Skip strict schema enforcement and focus on whether expanded terms surface documents that the original query missed. Run the prompt against 10-20 queries and manually inspect the before-and-after recall deltas.

  • Remove the [OUTPUT_SCHEMA] constraint and accept free-text expansion lists.
  • Replace the statistical significance section with a simple note: "Report whether recall improved, stayed flat, or degraded per query."
  • Use a flat JSON array of expanded terms instead of the full evaluation payload.

Watch for

  • Over-expansion that floods results with irrelevant documents and masks real recall gains.
  • Missing per-query delta reporting, which makes it impossible to spot regressions on specific query types.
  • Confirmation bias when hand-labeling relevance judgments after seeing expansion output.
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.