Inferensys

Prompt

Synonym Expansion with Token Budget Constraint Prompt

A practical prompt playbook for using Synonym Expansion with Token Budget Constraint 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

Define the job, reader, and constraints for the Synonym Expansion with Token Budget Constraint prompt.

This prompt is for production retrieval pipelines where query length directly impacts latency, cost, or downstream model context windows. The job-to-be-done is generating a ranked list of synonyms and related terms from a user query while strictly adhering to a token or term count ceiling. The ideal user is a search engineer, RAG developer, or infrastructure operator who has already established that synonym expansion improves recall but now needs to control the expansion budget to meet a service-level objective (SLO). You need a source query, a target token or term limit, and optionally a domain context or controlled vocabulary to ground the expansion.

Do not use this prompt when recall maximization is the only goal and budget is unconstrained—a simpler, unbounded expansion prompt will suffice. It is also inappropriate when the downstream retriever has no practical length limit, such as in offline batch processing. This prompt assumes you have already validated that synonym expansion provides a measurable recall lift for your corpus and that you are now tuning the cost-recall trade-off. If you have not yet established baseline expansion value, start with a standard synonym expansion eval prompt first.

The prompt is designed to be wired into a pre-retrieval stage of a RAG or search pipeline. It expects you to handle validation of the output budget adherence in application code, not just in the prompt instructions. The model will produce a ranked list with marginal recall gain estimates, but you must verify the actual token count and truncate or reject outputs that exceed the budget. For high-stakes domains like legal or healthcare retrieval, always log the expansion output and the final query sent to the retriever for auditability.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Synonym Expansion with Token Budget Constraint prompt works, where it fails, and the operational conditions required for production use.

01

Good Fit: Budget-Constrained Retrieval Pipelines

Use when: your retrieval backend enforces a hard token or term limit per query, and naive expansion would exceed it. Guardrail: The prompt ranks synonyms by marginal recall gain so the most valuable terms survive the cut, preventing wasted token spend on low-impact expansions.

02

Bad Fit: Unbounded Exploratory Search

Avoid when: the goal is open-ended discovery with no strict latency or cost ceiling. The budget constraint forces truncation that may drop serendipitous matches. Guardrail: Use an unbounded expansion prompt variant and apply downstream re-ranking or filtering instead of pre-expansion truncation.

03

Required Inputs

What you must provide: the original user query, the target token or term budget ceiling, and domain context (e.g., industry, corpus type). Guardrail: Without domain context, the model cannot assess which synonyms carry the highest marginal recall gain, leading to generic or misweighted expansions.

04

Operational Risk: Budget Exhaustion by Low-Value Terms

What to watch: the model fills the budget with obvious synonyms before reaching high-value conceptual alternatives. Guardrail: Require the output to include per-term marginal recall gain estimates and validate that high-gain terms appear before low-gain fillers. Implement a minimum gain threshold to reject filler terms.

05

Operational Risk: Budget Miscalculation

What to watch: the model miscounts tokens or terms, producing an output that exceeds the specified ceiling. Guardrail: Implement a post-generation token-count validator that truncates or rejects over-budget outputs. Log budget violations as a production metric to detect prompt drift or model behavior changes.

06

Operational Risk: Domain Mismatch Drift

What to watch: the model generates synonyms from a general corpus when the retrieval index is domain-specific, causing irrelevant expansions that waste budget. Guardrail: Provide explicit domain constraints in the prompt and validate expanded terms against a domain term list or embedding similarity check before retrieval execution.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for generating a ranked, token-budget-aware synonym list from a user query.

This prompt template is the core instruction set for the Synonym Expansion with Token Budget Constraint workflow. It is designed to be copied directly into your application code, test suite, or orchestration layer. The template forces the model to act as a retrieval engineer, prioritizing synonym selection based on marginal recall gain and strictly adhering to a provided token or term count ceiling. All dynamic inputs are represented as square-bracket placeholders, which your application must resolve before sending the request to the model.

text
You are a search relevance engineer. Your task is to expand a user's query with synonyms and related terms to improve document recall, while strictly adhering to a token budget.

INPUT QUERY:
[USER_QUERY]

DOMAIN CONTEXT:
[DOMAIN_DESCRIPTION]

TOKEN BUDGET:
[MAX_TOKENS]

OUTPUT SCHEMA:
[OUTPUT_SCHEMA]

CONSTRAINTS:
[CONSTRAINTS]

INSTRUCTIONS:
1. Analyze the INPUT QUERY and identify the core concepts that are most critical for retrieval.
2. Generate a list of synonymous terms, phrases, and conceptual alternatives for each core concept, informed by the DOMAIN CONTEXT.
3. For each generated term, estimate its marginal recall gain on a scale of 0.0 to 1.0, where 1.0 represents a term that is highly likely to retrieve uniquely relevant documents.
4. Rank all generated terms by their estimated marginal recall gain in descending order.
5. Assemble the final list of terms, starting from the highest-ranked, until adding the next term would exceed the TOKEN BUDGET. Count tokens using the same tokenizer as the target model.
6. Output the final list of terms, their marginal recall gain scores, and the total token count of the list in the exact format specified by the OUTPUT SCHEMA.
7. If no terms can be generated within the budget, return an empty list and a total token count of 0.

To adapt this template, replace the placeholders with concrete values from your application context. For [USER_QUERY], inject the raw search string. [DOMAIN_DESCRIPTION] should be a concise text field describing the knowledge base's subject matter (e.g., 'internal documentation for a cloud data warehouse product'). The [MAX_TOKENS] placeholder must be an integer representing the ceiling for the expanded terms list, not the entire prompt. Crucially, [OUTPUT_SCHEMA] should be replaced with a strict JSON schema definition to enforce a machine-readable contract, and [CONSTRAINTS] should be replaced with a list of hard rules, such as 'Do not expand proper nouns' or 'Preserve negation terms.' After implementing, validate the output against your schema and test with a golden query set to ensure budget adherence and term relevance.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Synonym Expansion with Token Budget Constraint prompt. Each placeholder must be populated before the prompt is assembled and sent. Validation notes describe how to programmatically verify the input before execution.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw user query to expand with synonyms and related terms

How do I configure SSO for enterprise accounts?

Non-empty string; max 500 characters; reject if only stopwords or punctuation

[TOKEN_BUDGET]

Maximum number of tokens or terms allowed in the expanded output

15

Integer >= 3; reject if budget exceeds model context window minus system prompt tokens

[DOMAIN_CONTEXT]

Domain or product area that constrains synonym relevance

Enterprise SaaS, identity and access management

Non-empty string; max 200 characters; null allowed if domain-agnostic expansion is acceptable

[RETRIEVAL_BACKEND]

Target retrieval system type that influences term selection strategy

sparse_keyword

Must be one of: sparse_keyword, dense_vector, hybrid; reject unrecognized values

[CONTROLLED_VOCABULARY]

Optional list of canonical terms or taxonomy entries to align expansions with

["SSO", "single sign-on", "identity provider", "SAML", "OIDC"]

JSON array of strings or null; max 50 terms; validate each term is non-empty string

[NEGATION_SCOPE]

Flag indicating whether the query contains negation that must be preserved

Boolean; if true, prompt must include negation boundary preservation instructions

[PRIOR_QUERY_CONTEXT]

Previous query turns for session-aware expansion disambiguation

null

Array of strings or null; max 5 prior turns; reject if any turn exceeds 300 characters

[OUTPUT_SCHEMA]

Expected JSON schema for the expansion output including terms, weights, and budget adherence

{"terms": [{"term": "...", "weight": 0.0, "source": "..."}], "budget_used": 0, "budget_total": 0}

Valid JSON schema object; must include terms array, budget_used, and budget_total fields

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the token-budgeted synonym expansion prompt into a production retrieval pipeline with validation, retries, and observability.

The synonym expansion prompt with a token budget constraint is designed to sit directly between the user's original query and the retrieval backend. In a typical RAG or search pipeline, you will call this prompt after query intake and before the expanded query is dispatched to your vector store, keyword index, or hybrid retriever. The prompt expects a raw user query, a target token budget, and an optional domain context string. The output is a ranked list of expansion terms with per-term marginal recall gain estimates and a total token count that must not exceed the budget. Because this prompt enforces a hard constraint, your harness must validate the output before forwarding it to retrieval.

The implementation harness should wrap the LLM call in a function that accepts user_query, token_budget, and domain_context as arguments. After receiving the model response, parse the JSON output and run three validation checks before proceeding: (1) verify that the total token count of the expanded terms does not exceed the requested budget, (2) confirm that each term has a non-negative marginal recall gain estimate, and (3) ensure the original query terms are preserved unless explicitly flagged for replacement. If validation fails, retry the prompt once with the validation error appended as a [CONSTRAINT] note. If the second attempt also fails, fall back to the original query without expansion and log the failure for later analysis. This retry-and-fallback pattern prevents a broken expansion from blocking retrieval entirely.

For model selection, use a model with strong instruction-following and structured output capabilities. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all handle the budget constraint reliably when the output schema is enforced. If you are running in a cost-sensitive or high-throughput environment, consider using a smaller model like GPT-4o-mini or Claude 3 Haiku with a stricter JSON schema and a post-processing step that truncates the term list to the budget if the model overshoots. Always log the raw model output, the validated output, the token count, and whether the fallback was triggered. These logs are essential for tuning the budget parameter and detecting prompt drift over time.

When integrating with a hybrid retrieval pipeline, pass the expanded terms as a weighted query string to your keyword index and as a concatenated phrase to your dense embedding model. The marginal recall gain estimates from the prompt can be used to weight term importance in BM25 or similar sparse retrieval algorithms. For dense retrieval, you may choose to embed only terms above a configurable gain threshold to avoid diluting the query vector with low-value synonyms. Store the expansion provenance—which terms were added, their gain estimates, and the budget consumed—alongside the retrieval trace so that downstream re-rankers and evaluators can distinguish original query matches from expansion-driven matches.

Avoid wiring this prompt into a synchronous user-facing path without a timeout and a circuit breaker. The expansion call adds latency, and a slow model response can degrade the end-to-end search experience. Set a reasonable timeout (e.g., 2–3 seconds) and fall back to the original query if the expansion call exceeds it. For high-risk domains such as legal or medical search, route expanded queries through a human review step before retrieval if the expansion introduces terms that materially change the query's meaning. The marginal gain estimates can serve as a signal for when review is warranted: if any single term has a gain estimate above a threshold you define, flag the expansion for approval.

IMPLEMENTATION TABLE

Expected Output Contract

Machine-readable contract for the synonym expansion output. Use this schema to validate responses before they enter your retrieval pipeline. Every field must pass the listed validation rule or trigger a repair or retry.

Field or ElementType or FormatRequiredValidation Rule

expanded_terms

Array of objects

Array length must be >= 1 and <= [MAX_TERMS]. Reject if empty or exceeds budget.

expanded_terms[].term

String

Non-empty string. Must not duplicate another term in the array (case-insensitive check). Must not be a substring of the original query unless it is a known multi-word concept.

expanded_terms[].weight

Number (float)

Value between 0.0 and 1.0 inclusive. Sum of all weights must be <= 1.0. Reject if any weight is negative or exceeds 1.0.

expanded_terms[].source_rationale

String or null

If provided, must be a non-empty string explaining why the term was selected. Null allowed when source attribution is not required.

total_token_estimate

Integer

Must be >= 0. Must equal the sum of token counts for all expanded_terms[].term values using the specified tokenizer. Reject if estimate exceeds [TOKEN_BUDGET].

budget_utilization_pct

Number (float)

Calculated as (total_token_estimate / [TOKEN_BUDGET]) * 100. Must be between 0.0 and 100.0. Flag for review if > 95 to prevent budget overruns from downstream concatenation.

rejected_terms

Array of strings or null

If provided, each entry must be a non-empty string. Must not overlap with expanded_terms[].term. Used to audit terms considered but excluded due to budget or relevance.

original_query_preserved

Boolean

Must be true if the original query terms are included in the expanded set; false otherwise. Flag for review if false and the retrieval strategy requires original term preservation.

PRACTICAL GUARDRAILS

Common Failure Modes

When synonym expansion hits token limits, these failures surface first. Each card identifies a specific breakdown and the operational guardrail to prevent it.

01

Budget Exhaustion on Low-Value Terms

What to watch: The model fills the token budget with common, low-discrimination synonyms (e.g., 'good' → 'great, nice, fine') before reaching rare, high-value domain terms. The budget is consumed but recall gain is negligible. Guardrail: Require the prompt to rank terms by marginal recall gain and truncate at the budget ceiling. Validate that rare terms appear before common synonyms in the output ordering.

02

Budget Overrun from Uncontrolled Generation

What to watch: The model ignores the explicit token or term count ceiling and produces an expanded list that exceeds the retrieval system's query length limit. This causes downstream truncation by the application layer, often dropping the most valuable terms last. Guardrail: Implement a post-generation validator that counts tokens or terms and rejects outputs exceeding the budget. Use a retry prompt that includes the exact overflow count and demands strict adherence.

03

Entity Corruption During Expansion

What to watch: Named entities, product codes, or proper nouns are treated as expandable terms and replaced with inappropriate synonyms (e.g., 'Project Falcon' → 'Project Hawk, Project Eagle'). This destroys retrieval precision for entity-specific queries. Guardrail: Include an entity protection list in the prompt and add a post-expansion check that verifies protected entities appear verbatim in the output. Flag any entity substitution as a hard failure.

04

Negation Scope Collapse

What to watch: A query containing negation like 'laptops without soldered RAM' gets expanded to include synonyms for 'soldered RAM' that inadvertently match documents about soldered memory, inverting the exclusion intent. Guardrail: Add a negation detection step before expansion. The prompt must preserve negation boundaries and mark excluded terms as non-expandable. Validate that expanded queries do not introduce terms that contradict the original exclusion.

05

Domain Drift Under Budget Pressure

What to watch: When the token budget is tight, the model selects synonyms from a broader or adjacent domain to fill the allocation, introducing terms that match irrelevant documents and degrade precision. Guardrail: Anchor the prompt with a domain constraint and a provided controlled vocabulary or taxonomy. Add a domain-relevance check that scores each expanded term against the source domain and rejects outputs where drift exceeds a threshold.

06

Marginal Gain Estimation Failure

What to watch: The model cannot accurately estimate which terms will actually improve recall against the target corpus, leading to budget allocation based on linguistic similarity rather than retrieval impact. Guardrail: When available, provide corpus statistics or term frequency data in the prompt context. If unavailable, add an eval step that measures actual recall gain on a golden query set and feeds discrepancies back into prompt refinement.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of synonym expansion outputs before integrating them into a production retrieval pipeline. Each criterion targets a specific failure mode of budget-constrained expansion.

CriterionPass StandardFailure SignalTest Method

Token Budget Adherence

Total token count of the output list is less than or equal to [MAX_TOKENS].

Output token count exceeds [MAX_TOKENS] by any amount.

Parse the output string with the target model's tokenizer. Assert token_count <= [MAX_TOKENS].

Term Relevance

All expanded terms are valid synonyms or conceptual equivalents for the [INPUT_QUERY] within the [DOMAIN_CONTEXT].

An expanded term is a homonym, antonym, or belongs to a completely unrelated domain.

For each term, perform a cosine similarity check against a domain-specific embedding of [INPUT_QUERY]. Assert similarity > [RELEVANCE_THRESHOLD].

Ranking Rationality

Terms are ranked in descending order of estimated marginal recall gain, with the highest-value terms appearing first.

A low-value or generic term is ranked higher than a specific, high-value synonym.

Using a held-out relevance dataset, simulate retrieval with the top N terms vs. the bottom N terms. Assert recall@k(top_terms) >= recall@k(bottom_terms).

Noise Exclusion

The output excludes terms that would introduce significant noise, such as overly broad hypernyms or common stop words.

The output includes a term that, when added to a query, reduces precision@k by more than [NOISE_DELTA].

Execute a retrieval eval with and without the candidate term. Assert precision@k(with_term) > precision@k(baseline) - [NOISE_DELTA].

Entity Preservation

Named entities from [INPUT_QUERY] are not replaced with generic synonyms. For example, 'Project Titan' is not expanded to 'Project Large Person'.

A recognized named entity is replaced or augmented with an inappropriate common noun synonym.

Run a Named Entity Recognition (NER) model on [INPUT_QUERY]. Assert that no token from an entity span is used as a seed for a generic synonym.

Negation Scope Integrity

If [INPUT_QUERY] contains a negation, no expanded term contradicts the negated intent.

A query for 'laptops without overheating issues' is expanded with 'hot', 'thermal throttling'.

Detect negation cues in [INPUT_QUERY]. For each expanded term, check if it is an antonym of a negated term. Assert contradiction_count == 0.

Marginal Gain Estimation

The output provides a plausible, non-zero marginal recall gain estimate for each term.

All terms have an identical gain score, a score of 0, or the score is missing from the output schema.

Validate the output schema field marginal_gain is present, is a float, and 0.0 < value <= 1.0 for each term.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a simple token counter and a hard cutoff. Skip confidence scoring and marginal gain estimation. Accept a flat list of synonyms ranked by relevance. Validate only that the output stays under the token budget.

code
[SYNONYM_EXPANSION_PROMPT]

Return a JSON array of synonym objects:
{"synonyms": [{"term": string, "relevance": "high"|"medium"|"low"}]}

Stop adding terms when the total token count reaches [MAX_TOKENS].

Watch for

  • Budget overshoot when the model miscounts tokens
  • Relevance inflation where every term is marked "high"
  • Missing domain terms because no glossary is provided
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.