Inferensys

Prompt

Cost-Aware Passage Selection Prompt for Token Budgets

A practical prompt playbook for using Cost-Aware Passage Selection Prompt for Token Budgets in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for cost-aware passage selection under token budgets.

This prompt is for RAG operators and pipeline engineers who need to select the most relevant passages from a retrieval set while respecting a hard token budget. The job-to-be-done is not just ranking passages by relevance—it's making explicit trade-offs between information coverage and per-query cost. You have a fixed context window or a cost ceiling, and you need the model to justify which passages earn their tokens and which don't. The ideal user is someone running a production RAG system where token costs directly affect margins, latency, or throughput limits, and where blindly packing the top-k passages is no longer acceptable.

Use this prompt when you have already retrieved a candidate passage set and need a budget-constrained selection before answer generation. It works best when you can supply a clear token budget, a ranked or scored retrieval list, and a specific query that defines what 'relevant' means. The prompt produces a selected subset with per-passage cost-benefit justifications, making the selection logic auditable. Do not use this prompt when your retrieval set is already small enough to fit within budget, when you need binary relevance filtering without budget constraints, or when you're optimizing for recall over precision. For those cases, use the Binary Passage Relevance Filter or Passage Sufficiency Assessment prompts instead.

This prompt is not a replacement for retrieval quality. If your retriever consistently returns irrelevant passages, cost-aware selection won't fix the underlying problem—it will just produce well-justified selections of bad candidates. Pair this prompt with retrieval evaluation and relevance scoring before introducing budget constraints. The output should feed into a validation step that checks whether the selected passages still cover the query's information needs. If the budget is too tight to retain essential evidence, the prompt should surface that gap rather than silently dropping critical context. Start with a generous budget, measure relevance retention, then tighten constraints while monitoring answer quality degradation.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Cost-Aware Passage Selection Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your production RAG pipeline before integrating it.

01

Good Fit: Budget-Constrained RAG Pipelines

Use when: you have a hard token limit per query (e.g., 4K context window) and must select the most valuable passages from a larger retrieval set. Guardrail: define the budget as an explicit numeric constraint in the prompt and validate that the output respects it before generation.

02

Good Fit: Cost-Optimized Multi-Stage Retrieval

Use when: you run an expensive reranker or LLM call after initial retrieval and need to reduce the passage count to control per-query spend. Guardrail: log the cost-benefit justifications from each selection to audit whether the model is trading off relevance for budget correctly.

03

Bad Fit: Single-Passage or Trivial Retrieval Sets

Avoid when: your retrieval pipeline returns only one or two passages per query. The cost-aware selection logic adds latency and token overhead without meaningful benefit. Guardrail: bypass this prompt entirely when the input passage count is below a configurable threshold.

04

Required Input: Scored or Ranked Passage Set

Risk: the prompt cannot make budget-aware trade-offs without initial relevance signals. Passing unscored passages forces the model to guess, producing inconsistent selections. Guardrail: always provide relevance scores, ranks, or retrieval confidence metadata alongside each passage so the model can weigh cost against quality.

05

Operational Risk: Budget Miscalibration Under Load

Risk: a fixed token budget that works at low query volume may cause context starvation under peak load or when passages are longer than expected. Guardrail: implement dynamic budget calculation based on actual passage lengths and available context window, not a hardcoded number. Monitor selection density in production traces.

06

Operational Risk: Relevance Regression at Low Budgets

Risk: aggressive budget constraints may cause the model to drop passages critical for answering the query, degrading downstream answer quality. Guardrail: run eval checks that compare answer accuracy at multiple budget levels (e.g., full set vs. 50% vs. 25%) and set a minimum relevance retention threshold before deployment.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for selecting the most relevant passages under a strict token budget, with cost-benefit justifications for each inclusion and exclusion.

This prompt template is designed for production RAG operators who need to balance passage relevance against per-query token costs. It forces the model to make explicit trade-offs: selecting passages that maximize information density within a hard budget while justifying why lower-priority passages were excluded. The template expects a pre-retrieved set of passages, a token budget, and optional domain-specific constraints. Use it when your retrieval pipeline returns more context than you can afford to send to the generation model, and you need auditable selection decisions rather than opaque truncation.

text
You are a cost-aware passage selector for a retrieval-augmented generation system. Your task is to select the most relevant passages from a candidate set while respecting a strict token budget. You must maximize information density and relevance, and you must explain your trade-offs.

## INPUT

**Query:** [USER_QUERY]

**Candidate Passages:**
[PASSAGE_LIST_WITH_IDS_AND_TOKEN_COUNTS]

**Token Budget:** [MAX_TOTAL_TOKENS]

**Domain Constraints (if any):** [DOMAIN_CONSTRAINTS]

## INSTRUCTIONS

1. Review each candidate passage for relevance to the query, information density, and uniqueness relative to other passages.
2. Select passages that fit within the token budget while maximizing coverage of the query's information needs.
3. Prefer passages that provide direct evidence, specific facts, or authoritative answers over vague or tangential content.
4. If two passages contain overlapping information, select the more concise or more authoritative one.
5. If the budget forces exclusion of relevant passages, prioritize those that address the core question over those that provide supplementary context.
6. Do not exceed the token budget. Count tokens conservatively.

## OUTPUT SCHEMA

Return a JSON object with the following structure:

{
  "selected_passages": [
    {
      "passage_id": "string",
      "token_count": number,
      "relevance_score": number (0.0 to 1.0),
      "selection_rationale": "string explaining why this passage was selected"
    }
  ],
  "excluded_passages": [
    {
      "passage_id": "string",
      "token_count": number,
      "relevance_score": number (0.0 to 1.0),
      "exclusion_rationale": "string explaining why this passage was excluded despite its relevance score"
    }
  ],
  "total_tokens_used": number,
  "budget_utilization_percent": number,
  "coverage_assessment": "string describing what the selected passages cover and what information gaps remain",
  "selection_summary": "string briefly explaining the overall selection strategy"
}

## CONSTRAINTS

- Total tokens of selected passages must not exceed [MAX_TOTAL_TOKENS].
- Every passage in the candidate list must appear in either selected_passages or excluded_passages.
- Relevance scores must be justified by the passage content, not the passage position in the list.
- If no passages are sufficiently relevant, return an empty selected_passages array and explain why in coverage_assessment.
- Do not fabricate passage content. Only reference information present in the provided passages.

To adapt this template for your pipeline, replace the square-bracket placeholders with your actual data. The [PASSAGE_LIST_WITH_IDS_AND_TOKEN_COUNTS] placeholder should receive a structured list where each passage includes a unique ID, the full passage text, and a pre-computed token count. Pre-compute token counts in your application layer using your target model's tokenizer rather than relying on the model to estimate them. The [DOMAIN_CONSTRAINTS] field is optional but valuable for specialized deployments—for example, a medical RAG system might add "Prefer passages from peer-reviewed journals published within the last 5 years" or a legal system might add "Exclude passages from dissenting opinions unless the query specifically asks about dissents." If your pipeline uses a multi-stage filtering approach, you can chain this prompt after a cheaper binary relevance filter to reduce the candidate set before budget-constrained selection. Always validate the output JSON against the schema before passing selections to your generation step, and log exclusion rationales for pipeline debugging.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Cost-Aware Passage Selection Prompt. Each variable must be populated before the prompt is assembled and sent to the model. Missing or malformed variables will cause budget enforcement failures or selection errors.

PlaceholderPurposeExampleValidation Notes

[QUERY]

The user question or information need driving passage selection

What are the latency requirements for the new inference API?

Required. Must be a non-empty string. Check for vague one-word queries that produce unfocused selections.

[PASSAGES]

The retrieved passage set with metadata including source, length, and retrieval score

[{"id":"p1","text":"...","source":"docs/api-reference.md","length_tokens":245,"retrieval_score":0.89}]

Required. Must be a valid JSON array of passage objects. Each object requires id, text, and length_tokens fields. Empty array triggers immediate empty response.

[TOKEN_BUDGET]

Maximum total tokens allowed for selected passages

2048

Required. Must be a positive integer. Validate that budget is less than model context window minus prompt overhead. Budgets below 100 tokens may produce unusable selections.

[COST_PER_TOKEN]

Cost per token in USD for the target model to enable cost-benefit calculations

0.000015

Optional. If null, cost justification section is omitted. If provided, must be a positive float. Use model-specific pricing from provider documentation.

[MIN_PASSAGES]

Minimum number of passages to select regardless of token budget

2

Optional. Defaults to 1. Must be a positive integer. If MIN_PASSAGES exceeds budget capacity, prompt should return an error rather than violating budget.

[RELEVANCE_THRESHOLD]

Minimum retrieval score for a passage to be considered for selection

0.65

Optional. Defaults to 0.5. Must be a float between 0.0 and 1.0. Thresholds above 0.9 risk excluding all passages in sparse retrieval scenarios.

[OUTPUT_FORMAT]

Desired output structure for selected passages and justifications

json

Required. Must be one of json, jsonl, or markdown. JSON is recommended for downstream parsing. Markdown is acceptable for human review workflows.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the cost-aware passage selection prompt into a production RAG pipeline with validation, retries, and observability.

This prompt operates as a pre-generation filter in your RAG pipeline. After retrieval returns a candidate passage set, but before those passages are packed into the final context window for answer generation, this prompt selects the optimal subset that maximizes relevance while respecting a hard token budget. The implementation harness must enforce the budget constraint programmatically, validate the model's output against that constraint, and provide fallback behavior when the model fails to produce a valid selection. Do not rely on the model alone to count tokens accurately—always verify the selected passages' token count in your application code using the same tokenizer your target model uses.

Wiring the prompt into your application requires three layers: a pre-call layer, a post-call validation layer, and a fallback layer. In the pre-call layer, compute the token count for each candidate passage using tiktoken (for OpenAI models) or the equivalent tokenizer for your model family. Pass these counts alongside the passages in the [PASSAGES] placeholder as structured objects: {"id": "p1", "text": "...", "token_count": 145}. The [BUDGET] placeholder should receive an integer representing the maximum tokens allowed for the selected set. In the post-call layer, parse the model's JSON output, extract the selected passage IDs, sum their pre-computed token counts, and reject any selection that exceeds the budget. If validation fails, retry once with an explicit error message injected into the prompt: "Your previous selection used {actual_tokens} tokens, exceeding the budget of {budget} tokens. Select fewer or shorter passages." After two failures, fall back to a deterministic greedy selection algorithm that picks the highest-scored passages from the initial retrieval ranking until the budget is exhausted.

Logging and observability are critical because this prompt directly trades off answer quality against cost. Log the following per request: the initial retrieval set size, the budget constraint, the selected passage IDs and their individual token counts, the total tokens used, the number of retries, and whether the fallback algorithm was invoked. Over time, these logs reveal whether your budget is consistently too tight (frequent fallback invocation, degraded answer quality) or too loose (unused budget that could have included more evidence). Wire these metrics into your existing monitoring stack and set alerts for fallback rates exceeding 5% of requests. For high-stakes applications, consider an A/B evaluation harness that runs the same query through the cost-aware selection and an unbounded selection, then compares answer quality using an LLM judge to quantify the quality-cost trade-off at different budget levels.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when you ask an LLM to select passages under a token budget, and how to guard against it.

01

Budget Overrun on First Pass

What to watch: The model selects passages that collectively exceed the token budget, ignoring the constraint. This often happens when the budget is specified as a suggestion rather than a hard rule. Guardrail: Enforce the budget in application code by truncating the model's output or rejecting selections that exceed the limit. Add a post-selection token count check and retry with an explicit overrun error message.

02

Relevance Collapse Under Tight Budgets

What to watch: When the budget is very small, the model may select short but irrelevant passages that fit the token limit rather than the most relevant longer passages. Guardrail: Require the model to output a relevance score for each candidate before budget allocation. Implement a two-stage pipeline: score all passages first, then run a separate budget-constrained selection step.

03

Position Bias in Passage Ordering

What to watch: The model favors passages at the beginning or end of the input list, ignoring highly relevant passages in the middle. This recency/primacy bias distorts cost-aware selection. Guardrail: Randomize passage order before sending to the model. Run selection multiple times with different orderings and take the consensus selection. Log position of selected passages to detect systematic bias.

04

Cost-Benefit Justification Hallucination

What to watch: The model fabricates plausible-sounding justifications for why a passage was selected or excluded, even when the reasoning contradicts the passage content. Guardrail: Require the model to quote a short span from each selected passage as evidence for its inclusion. Validate that quoted spans actually exist in the source passages using string matching before accepting the selection.

05

Duplicate Content Waste Under Budget

What to watch: The model selects multiple passages that convey the same information, wasting token budget on redundancy instead of coverage. Guardrail: Add an explicit deduplication instruction in the prompt. Post-process selections with a semantic similarity check (e.g., embedding cosine similarity) and flag near-duplicate pairs for removal or merging.

06

Silent Omission of Critical Evidence

What to watch: The model drops a passage that contains information essential to answering the query correctly, with no indication that critical evidence was excluded. Guardrail: Run a separate sufficiency check after selection: ask the model whether the selected set contains enough information to answer the original query. If not, expand the budget or escalate for human review.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test whether the cost-aware passage selection prompt produces safe, budget-compliant, and relevance-preserving outputs before deploying to production.

CriterionPass StandardFailure SignalTest Method

Token budget compliance

Total tokens of selected passages plus justification text does not exceed [TOKEN_BUDGET]

Output exceeds budget by more than 5% or omits budget reporting entirely

Parse output for token count claim; verify with tokenizer on selected passage text plus justification

Relevance preservation under budget

Top-ranked passages by independent relevance score are selected at a rate >= 90% when budget allows

High-relevance passages (score >= 0.8) are excluded while lower-relevance passages are included

Run against golden query-passage set with known relevance labels; compare selected set to top-N by label

Cost-benefit justification quality

Every exclusion decision includes a specific reason referencing relevance, redundancy, or cost trade-off

Justifications are generic (e.g., 'not relevant'), missing, or hallucinate passage content

Human review or LLM-as-judge evaluation on 50 random outputs; check for passage-specific reasoning

No hallucinated passage content

All referenced passage IDs and quoted text match the provided [PASSAGES] input exactly

Output references passage IDs not in input, misquotes text, or fabricates content summaries

Exact string match on quoted spans; verify all passage IDs exist in input set

Selection diversity

Selected passages cover all distinct query aspects present in [QUERY] when budget permits

All selected passages address the same single aspect while other query facets are ignored

Label passages by query aspect; measure aspect coverage ratio in selected set

Confidence calibration

Confidence scores for selections correlate with downstream answer accuracy (Spearman rho >= 0.5)

High-confidence selections produce incorrect answers; low-confidence selections produce correct answers

Run end-to-end with answer generation; compute rank correlation between selection confidence and answer correctness

Graceful degradation under tight budget

When [TOKEN_BUDGET] is <= 20% of total passage tokens, output selects highest-relevance subset and flags insufficiency

Output either exceeds budget, selects random passages, or fails to flag that budget is too tight for adequate coverage

Test with progressively tighter budgets (50%, 30%, 15%, 5%); verify selection quality and insufficiency flagging

Output schema validity

Output parses as valid JSON matching [OUTPUT_SCHEMA] with all required fields present

Missing required fields, wrong types, or unparseable JSON

Schema validation against expected JSON Schema definition; retry count <= 1 allowed

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a simple token budget constraint and a single-pass selection. Remove the cost-benefit justification field and keep only the ranked passage list. Accept the model's native output format without strict schema enforcement.

code
Select up to [MAX_TOKENS] tokens worth of passages from [PASSAGE_LIST] that best answer [QUERY]. Return the selected passages in order of relevance.

Watch for

  • Model ignoring the token budget and returning all passages
  • No way to verify whether budget was actually respected
  • Missing justification makes debugging selection decisions impossible
  • Token counting errors when passages contain code blocks or special characters
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.