Inferensys

Prompt

Synonym Expansion with Source Attribution Prompt

A practical prompt playbook for using Synonym Expansion with Source Attribution Prompt in production AI workflows.
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

Defines the job-to-be-done, ideal user, required context, and explicit boundaries for the auditable synonym expansion prompt.

This prompt is for search engineers and RAG developers operating in regulated domains where query transformations must be auditable. The core job-to-be-done is expanding a user query with synonyms and related terms to improve retrieval recall, while producing a verifiable chain of provenance for every added term. The ideal user is someone who already has a controlled vocabulary source—a thesaurus, ontology, or internal knowledge base—and needs to prove to an auditor or downstream reviewer why a specific term was added to a retrieval query. Without this prompt, teams either skip expansion in high-stakes domains (hurting recall) or perform un-attributed expansion that fails compliance review.

You should use this prompt when the cost of an incorrect or unexplained expansion is high. Typical scenarios include legal document retrieval, clinical literature search, financial audit evidence gathering, and regulatory filing review. In these contexts, a reviewer must be able to trace every synonym back to an approved source entry. The prompt requires a [SOURCE_VOCABULARY] input—a structured thesaurus, ontology fragment, or term-to-synonym mapping—and will refuse to generate terms that cannot be grounded in that source. It also emits explicit missing_source alerts when the input query contains concepts absent from the provided vocabulary, preventing silent gaps in coverage.

Do not use this prompt for low-latency, high-throughput search where source attribution overhead is unnecessary. If your retrieval pipeline processes thousands of queries per second and every millisecond counts, the attribution generation and validation steps will add unacceptable latency. Similarly, do not use this prompt when no controlled vocabulary source exists; the prompt is designed to refuse ungrounded expansion, so it will produce empty or near-empty results without a source. For general-purpose synonym expansion without audit requirements, use the standard Synonym Expansion Prompt Template for Keyword Search instead. Before implementing, confirm that you have a machine-readable vocabulary source and that your latency budget can absorb the attribution generation step—typically an additional 200-500ms depending on source size and model choice.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Synonym Expansion with Source Attribution is designed for regulated domains requiring auditable query transformations. It excels when every expanded term must be traceable to an approved source, but it is the wrong tool for open-ended creative expansion or low-latency, high-throughput pipelines where source lookup adds unacceptable overhead.

01

Good Fit: Regulated or Auditable Domains

Use when: the retrieval system operates in legal, financial, medical, or compliance contexts where every query transformation must be explainable to an auditor. Guardrail: ensure the provided thesaurus, ontology, or knowledge base is version-locked and approved before use.

02

Bad Fit: Open-Ended Creative Search

Avoid when: the goal is brainstorming, exploratory research, or marketing copy retrieval where rigid source constraints would suppress useful but unlisted synonyms. Guardrail: use a standard synonym expansion prompt without source attribution for open-ended recall tasks.

03

Required Input: Authoritative Source Material

Risk: the prompt produces empty or incomplete expansions if no thesaurus, ontology, or controlled vocabulary is provided. Guardrail: always supply a structured source document with canonical terms and approved synonyms; validate that the source covers the query domain before invoking expansion.

04

Operational Risk: Latency from Source Lookup

Risk: real-time search pipelines may time out if the model must parse large ontologies or knowledge graphs per query. Guardrail: pre-index approved synonym mappings for low-latency retrieval, and use this prompt for offline expansion cache population or audit-trail generation rather than per-request expansion.

05

Operational Risk: Missing-Source Alerts Without Action

Risk: the prompt correctly flags terms that lack source provenance, but downstream systems ignore the alert and use ungrounded expansions anyway. Guardrail: implement a hard reject or human-review step when missing-source alerts are present; never silently pass ungrounded terms to retrieval.

06

Bad Fit: High-Volume, Low-Stakes Search

Avoid when: the retrieval system serves consumer product search, FAQ lookup, or internal wikis where audit trails add cost without value. Guardrail: reserve source-attributed expansion for queries where incorrect or ungrounded expansions carry regulatory, financial, or safety consequences.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A production-ready prompt for generating auditable synonym expansions with explicit source attribution and missing-source alerts.

This template is designed for regulated domains where every expanded term must be traceable to an approved source. Replace the square-bracket placeholders with your specific thesaurus, ontology, or knowledge base entries before use. The prompt instructs the model to output only expansions that can be attributed to the provided sources, to flag any terms that cannot be sourced, and to include a completeness check. This is not a general-purpose synonym generator; it is a controlled vocabulary expansion tool for audit-ready retrieval pipelines.

text
You are a controlled vocabulary expansion engine for a regulated domain. Your task is to expand the user's query with synonyms and related terms that improve search recall, using ONLY the provided authoritative sources. You must attribute every expansion to a specific source entry and flag any query terms you cannot source.

## INPUT
Query: [QUERY]

## AUTHORITATIVE SOURCES
[SOURCES]

## CONSTRAINTS
- Output ONLY expansions that can be directly attributed to the provided sources.
- For each expansion, cite the exact source entry (e.g., source name, entry ID, or line number).
- If a query term has no match in the sources, list it under "missing_sources" with a note.
- Do not invent synonyms, use general knowledge, or infer related terms.
- Preserve the original query's logical operators, negation, and entity boundaries.
- If the query contains negated terms (e.g., "without X"), do not expand them.

## OUTPUT SCHEMA
Return a JSON object with the following structure:
{
  "original_query": "string",
  "expansions": [
    {
      "original_term": "string",
      "expanded_terms": ["string"],
      "source_attribution": [
        {
          "source_name": "string",
          "entry_id": "string",
          "relationship": "exact_synonym | broader_term | narrower_term | related_term"
        }
      ]
    }
  ],
  "missing_sources": [
    {
      "term": "string",
      "reason": "not_found_in_sources"
    }
  ],
  "completeness_check": {
    "total_query_terms": "number",
    "terms_with_expansions": "number",
    "terms_without_expansions": "number",
    "all_terms_sourced": "boolean"
  }
}

## EXAMPLES
Query: "cardiac event"
Sources: [{"source": "MedThesaurus v3", "entry": "CARD-001", "term": "cardiac event", "synonyms": ["myocardial infarction", "heart attack", "acute coronary syndrome"]}]
Output: {"original_query": "cardiac event", "expansions": [{"original_term": "cardiac event", "expanded_terms": ["myocardial infarction", "heart attack", "acute coronary syndrome"], "source_attribution": [{"source_name": "MedThesaurus v3", "entry_id": "CARD-001", "relationship": "exact_synonym"}]}], "missing_sources": [], "completeness_check": {"total_query_terms": 1, "terms_with_expansions": 1, "terms_without_expansions": 0, "all_terms_sourced": true}}

## RISK LEVEL
[RISK_LEVEL]

To adapt this template, replace [QUERY] with the user's raw input, [SOURCES] with your structured thesaurus or ontology entries (as a JSON array of objects with source name, entry ID, term, and synonyms), and [RISK_LEVEL] with a note about the domain's tolerance for missing expansions (e.g., "High: missing sources must block retrieval" or "Medium: flag and proceed"). The output schema is strict JSON to enable programmatic validation before the expanded terms are injected into a retrieval pipeline. If your sources are large, consider pre-filtering them to relevant entries before passing them into the prompt to stay within context limits. Always validate the output against the schema before use, and log any missing_sources entries for audit review.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Synonym Expansion with Source Attribution Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The original user search string to expand with synonyms and related terms

treatment protocol for myocardial infarction

Non-empty string; max 500 characters; check for injection patterns before passing to model

[SOURCE_THESAURUS]

A structured thesaurus, ontology, or controlled vocabulary containing canonical terms and relationships

{"myocardial infarction": {"synonyms": ["heart attack", "MI", "acute coronary syndrome"], "source": "MeSH 2024"}}

Valid JSON object; must contain at least one term entry with a synonyms array; schema check required before prompt assembly

[DOMAIN_CONTEXT]

A short description of the domain to constrain expansion relevance and prevent cross-domain term collision

clinical cardiology and emergency medicine

Non-empty string; max 200 characters; should match the domain scope of [SOURCE_THESAURUS]

[EXPANSION_DEPTH]

Controls how many levels of synonym and related-term traversal are permitted from the source thesaurus

2

Integer between 1 and 4; values above 2 increase risk of semantic drift; validate range before prompt execution

[MIN_CONFIDENCE_THRESHOLD]

The minimum confidence score a term must meet to be included in the output; terms below this threshold are rejected

0.7

Float between 0.0 and 1.0; 0.0 disables filtering; typical production range is 0.6-0.85

[OUTPUT_SCHEMA]

The expected JSON schema for the expansion output, including term, source, confidence, and attribution fields

{"expanded_terms": [{"term": "string", "source_term": "string", "source_document": "string", "confidence": "float"}]}

Valid JSON Schema draft; must include expanded_terms array with required fields; schema validation before prompt injection

[MAX_TERMS]

The maximum number of expanded terms to return, preventing unbounded output in production pipelines

15

Integer between 5 and 50; budget-aware systems should set lower limits; validate against retrieval query length constraints

[MISSING_SOURCE_BEHAVIOR]

Instruction for how the model should handle query terms not found in the source thesaurus

flag_and_continue

Must be one of: 'flag_and_continue', 'skip_term', 'fallback_to_embedding', or 'halt_and_alert'; enum check required

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Synonym Expansion with Source Attribution prompt into a production retrieval pipeline with validation, logging, and human review gates.

This prompt is designed for regulated domains where every term expansion must be traceable to an authoritative source. The implementation harness must enforce that traceability at runtime, not just hope the model complies. The core integration pattern is a pre-retrieval expansion step: the user's query enters the pipeline, the prompt expands it using the provided thesaurus or ontology, and only terms with valid source attribution are forwarded to the retrieval backend. The harness must validate the output schema before any expanded terms touch the search index.

Start by wrapping the prompt call in a strict validation layer. The expected output is a JSON array of objects, each containing term, source, confidence, and relationship_type fields. Before forwarding terms to retrieval, validate that every object has a non-null source field that matches an entry in your provided knowledge base. Reject or quarantine any term where source is null, "unknown", or missing. Log these rejections as missing_source_alert events for audit review. For high-recall use cases, you may allow terms with confidence above a configurable threshold (e.g., 0.9) even with missing sources, but this must be explicitly flagged and reviewed. Implement a circuit breaker: if more than 20% of terms in a batch fail source validation, halt expansion for that query and fall back to the original user query with a logged warning.

Model choice matters here. Use a model with strong instruction-following and structured output capabilities, such as gpt-4o or claude-3-5-sonnet, and set response_format to json_object with the schema enforced. Temperature should be low (0.0–0.2) to minimize hallucinated sources. Implement retries with exponential backoff for schema validation failures, but cap retries at 3 attempts. On the third failure, log the raw output, alert the on-call channel, and fall back to the original query. For auditability, store every expansion request and response in an append-only log with the query, the provided knowledge base version, the expanded terms, and the validation results. This log becomes your evidence trail for compliance reviews.

Human review should be gated on specific triggers: any query where the missing_source_alert count exceeds zero, any batch where the circuit breaker tripped, or any term flagged with relationship_type equal to "contradiction" or "antonym". Route these to a review queue where a domain expert can approve, correct, or reject the expansions before they enter retrieval. Do not silently drop these cases—silent failures in regulated domains become audit findings. Finally, monitor the ratio of expanded queries to original queries over time. A sudden drop in expansion rate may indicate knowledge base drift or prompt degradation, while a spike in missing-source alerts signals that your thesaurus needs updating.

IMPLEMENTATION TABLE

Expected Output Contract

Machine-readable contract for synonym expansion outputs with source attribution. Each field enforces a specific validation rule so downstream systems can parse, log, and audit expansions without ambiguity.

Field or ElementType or FormatRequiredValidation Rule

expanded_terms

Array of objects

Must contain at least 1 object. Empty array triggers a retry or fallback to original query.

expanded_terms[].term

String

Non-empty string. Must not duplicate the original query token exactly unless it is a canonical form from the provided source.

expanded_terms[].source_id

String or null

Must match an entry in the provided thesaurus, ontology, or knowledge base. Null allowed only when source_attribution is 'inferred' and a missing-source alert is generated.

expanded_terms[].source_attribution

Enum: 'exact_match', 'broader_match', 'narrower_match', 'inferred'

Must be one of the four enum values. 'inferred' requires a corresponding entry in the missing_source_alerts array.

expanded_terms[].confidence

Number (0.0-1.0)

Float between 0.0 and 1.0 inclusive. Values below the configured reject_threshold must be excluded from the array.

missing_source_alerts

Array of objects

Required when any expanded_term has source_attribution 'inferred'. Each object must contain term, reason, and suggested_review fields.

missing_source_alerts[].term

String

The inferred term that lacks a source match. Must correspond to an entry in expanded_terms with source_attribution 'inferred'.

missing_source_alerts[].reason

String

Non-empty explanation of why no source was found. Must not be a generic placeholder.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when expanding queries with source-attributed synonyms and how to guard against it.

01

Over-Expansion and Term Dilution

What to watch: The prompt adds too many low-relevance synonyms, diluting the original query intent and causing retrieval to return noisy, off-topic results. Guardrail: Set a maximum term limit per query and require a minimum confidence or relevance score for each expanded term. Implement a post-expansion deduplication and salience check before retrieval.

02

Missing or Fabricated Source Attribution

What to watch: The model generates plausible-sounding synonyms but fails to link them to the provided thesaurus, ontology, or knowledge base, or worse, invents source references. Guardrail: Validate that every returned term maps to an entry in the provided source material. Flag and discard terms with missing or unverifiable provenance before they reach retrieval.

03

Entity and Proper Noun Corruption

What to watch: The expansion process replaces named entities, product codes, or proper nouns with inappropriate synonyms, breaking exact-match requirements for key terms. Guardrail: Pre-process the query to detect and lock recognized entities before expansion. Use a protected-term list and validate that original entities appear unchanged in the final expanded query set.

04

Negation and Scope Inversion

What to watch: Expanding a negated term like 'not urgent' with a synonym like 'critical' inverts the semantic intent, causing retrieval of exactly the wrong documents. Guardrail: Detect negation cues in the original query and mark the scope of negation. Exclude negated terms from expansion or apply strict antonym filtering within the negated scope.

05

Domain Mismatch and Cross-Context Drift

What to watch: A term valid in one domain maps to an irrelevant concept in another, such as 'cell' expanding to 'battery' in a biology query. Guardrail: Condition expansion on an explicit domain context parameter. Validate expanded terms against a domain-specific stop list and flag cross-domain collisions for human review in regulated workflows.

06

Silent Source Exhaustion and Incomplete Attribution

What to watch: The provided thesaurus or ontology lacks coverage for a query term, but the model fills the gap with unattributed guesses instead of raising a missing-source alert. Guardrail: Require the prompt to output an explicit missing_sources array for any query term not found in the provided knowledge base. Monitor this array in production to identify coverage gaps.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of synonym expansion outputs with source attribution before deploying to production. Use this rubric to build automated eval checks and manual review gates.

CriterionPass StandardFailure SignalTest Method

Source Attribution Completeness

Every expanded term includes a non-null source reference from the provided [SOURCE_ONTOLOGY]

Missing source field, null source, or source value not present in [SOURCE_ONTOLOGY]

Schema validation: assert all terms have a source field; assert source value exists in the provided ontology set

Term Relevance to [INPUT_QUERY]

All expanded terms are semantically relevant to the core concepts in [INPUT_QUERY] with no off-topic drift

Expanded term belongs to a different domain, introduces unrelated concepts, or contradicts query intent

LLM-as-judge pairwise comparison against a golden relevance threshold; human spot-check for domain boundary violations

No Entity Corruption

Named entities, product names, and proper nouns from [INPUT_QUERY] are preserved without inappropriate synonym replacement

A recognized entity from [ENTITY_LIST] is replaced with a generic synonym or altered

Entity boundary detection: extract entities from output; assert intersection with [ENTITY_LIST] matches input entities exactly

Confidence Score Calibration

Per-term confidence scores in [CONFIDENCE_SCORE] field are between 0.0 and 1.0 and correlate with source authority

Confidence score of 1.0 for a term from a weak or indirect source; score below 0.5 for a direct ontology match

Statistical check: assert all scores are floats in [0.0, 1.0]; validate that direct ontology matches have scores >= 0.8

Missing-Source Alert Accuracy

The [MISSING_SOURCE_ALERT] flag is true when any query concept lacks a matching entry in [SOURCE_ONTOLOGY]

Alert flag is false when a query concept has no ontology match; alert flag is true when all concepts are covered

Ground truth comparison: pre-label queries with known ontology coverage gaps; assert alert flag matches expected value

Output Schema Compliance

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

Missing required field, extra undeclared field, string where array expected, or malformed JSON

JSON Schema validation against [OUTPUT_SCHEMA]; parse check with strict mode enabled

Negation Scope Preservation

Expanded terms do not introduce synonyms that would contradict or invert negation in [INPUT_QUERY]

A negated term like 'without' gets expanded with a synonym that implies inclusion

Negation boundary detection: identify negated spans in input; assert no expanded term maps to a negated concept

Token Budget Adherence

Total expanded term count does not exceed [MAX_TERMS] and total output tokens are within [MAX_TOKENS]

Output contains more terms than [MAX_TERMS] or token count exceeds budget

Programmatic count: count terms in output array; assert length <= [MAX_TERMS]; tokenize and assert token count <= [MAX_TOKENS]

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a small provided thesaurus or ontology snippet inline. Skip strict schema enforcement and focus on getting reasonable expansions with source references. Accept free-text or loosely structured JSON output.

code
[SYSTEM]
You are a query expansion assistant. Given a user query and a provided thesaurus, expand the query with synonyms and related terms. For each term you add, cite the source entry from the thesaurus.

[THESAURUS]
[PASTE_SMALL_THESAURUS_HERE]

[QUERY]
[USER_QUERY]

Watch for

  • Hallucinated sources when the thesaurus lacks coverage
  • Missing attribution on terms the model considers obvious
  • Over-expansion that adds noise before retrieval is tested
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.