This prompt is designed for RAG system operators and AI engineers who need to reduce context window bloat by removing irrelevant retrieved passages before they reach the model. The core job is classification and pruning: given a user query and a set of retrieved passages, the prompt classifies each passage as essential, supportive, or irrelevant to the query, drops the irrelevant tier, and returns a pruned context set with brief removal justifications. This is not a summarization prompt—it preserves the original text of retained passages verbatim. Use it when your retrieval pipeline returns loosely related content alongside critical evidence, and you need to control token costs and reduce distraction without losing fidelity on what matters.
Prompt
Context Pruning Prompt for Irrelevant Evidence

When to Use This Prompt
Define the job, ideal user, required inputs, and when this prompt is the wrong tool.
The ideal user is an engineer or operator who already has a working retrieval step and wants to insert a pruning stage before the final generation call. You need three inputs: a clear user query or task description, a set of retrieved passages with source identifiers, and a defined output schema for the pruned result. The prompt works best when passages are self-contained enough to be classified independently. It is not suitable when passages are deeply interdependent, when the task requires comparing passages against each other, or when the definition of relevance depends on subtle domain knowledge the model cannot infer from the query alone. In those cases, use an evidence ranking prompt or a contradiction resolution prompt instead.
Before deploying this prompt in production, define what 'irrelevant' means for your use case and test against a golden set of passages with known relevance labels. The prompt includes a structured output schema and removal justifications, which makes it straightforward to evaluate with LLM judges or human reviewers. For high-stakes domains—legal, clinical, financial—require human approval on the pruned set before it feeds downstream generation. The biggest failure mode is over-pruning: the model drops a passage that contains critical context not obvious from the query alone. Mitigate this by running a factuality preservation check on the pruned context against the original, and by setting a minimum retention threshold when the task involves compliance or audit requirements.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if context pruning is the right tool for your pipeline before you invest in integration.
Good Fit: Noisy Retrieval Pipelines
Use when: your RAG system returns loosely related passages alongside critical evidence and you need to drop irrelevant content before packing the context window. Guardrail: run a factuality preservation check on the pruned output to confirm no essential evidence was removed.
Bad Fit: Single-Source Summarization
Avoid when: you are compressing one long document rather than filtering multiple retrieved passages. This prompt classifies and drops items, not condenses text. Guardrail: use a query-focused compression prompt instead for single-document summarization tasks.
Required Inputs
What you need: a set of retrieved passages with source identifiers, the user query or task description, and a classification schema defining essential, supportive, and irrelevant tiers. Guardrail: validate that every passage has a stable source ID before pruning so downstream citation integrity is preserved.
Operational Risk: Over-Pruning Critical Evidence
What to watch: the model may classify borderline passages as irrelevant when they contain context needed for accurate reasoning. Guardrail: implement a human review gate for high-stakes domains and run a factuality comparison between original and pruned context sets before downstream use.
Operational Risk: Citation Chain Breakage
What to watch: dropping passages can orphan citation markers that downstream answer generation expects to reference. Guardrail: run a citation integrity verification after pruning to confirm all retained citations map to surviving source passages and no dangling references remain.
Not a Replacement for Retrieval Quality
What to watch: teams may treat pruning as a fix for broken retrieval when the root cause is poor embedding, weak queries, or bad chunking. Guardrail: monitor pruning rates over time. If more than 50% of passages are consistently classified as irrelevant, investigate retrieval quality before tuning the pruning prompt.
Copy-Ready Prompt Template
A reusable prompt template that classifies retrieved passages by relevance and prunes irrelevant evidence before the main task runs.
This template is the core instruction set for the context pruning workflow. It takes a user query, a set of retrieved passages, and a task description, then classifies each passage as essential, supportive, or irrelevant to the current task. The prompt outputs a pruned context set containing only essential and supportive passages, along with removal justifications for every dropped passage. Use this template when retrieval returns loosely related or noisy results that would waste token budget, dilute model attention, or introduce contradictory signals into downstream reasoning.
textYou are a context pruning specialist. Your job is to evaluate each retrieved passage against the user's query and the stated task, then remove passages that do not contribute useful information. ## INPUT **User Query:** [USER_QUERY] **Task Description:** [TASK_DESCRIPTION] **Retrieved Passages:** [RETRIEVED_PASSAGES] ## CLASSIFICATION RULES For each passage, assign exactly one classification: - **essential**: The passage contains information that is directly required to answer the query or complete the task. Removing it would make the task impossible or significantly degrade correctness. - **supportive**: The passage provides useful context, background, or corroborating evidence that improves answer quality but is not strictly required. The task can be completed without it, though quality may suffer. - **irrelevant**: The passage does not help answer the query or complete the task. It may be about a different topic, too vague, redundant with a better passage, or contain only noise. ## CONSTRAINTS [CONSTRAINTS] ## OUTPUT FORMAT Return a JSON object with this exact structure: { "pruned_passages": [ { "passage_id": "string", "classification": "essential | supportive", "passage_text": "string" } ], "removed_passages": [ { "passage_id": "string", "classification": "irrelevant", "removal_reason": "string explaining why this passage was dropped" } ], "pruning_summary": { "total_input_passages": number, "essential_count": number, "supportive_count": number, "irrelevant_count": number, "token_savings_estimate": "string describing approximate token reduction" } } ## EXAMPLES [EXAMPLES] ## IMPORTANT - Do not modify passage text. Return passages exactly as provided. - If all passages are irrelevant, return an empty pruned_passages array and explain why in the pruning_summary. - If you are uncertain about a passage's relevance, classify it as supportive rather than dropping it. - Preserve passage_id values exactly as provided in the input.
To adapt this template, populate the square-bracket placeholders with your runtime data. [USER_QUERY] receives the original user question or instruction. [TASK_DESCRIPTION] describes what the downstream model will do with the pruned context—be specific about the output type, audience, and quality bar so the pruning classifier can make accurate relevance judgments. [RETRIEVED_PASSAGES] should be a JSON array of objects with passage_id and passage_text fields. Use [CONSTRAINTS] to inject domain-specific rules such as 'retain all passages mentioning regulatory requirements' or 'drop passages older than 2023 unless explicitly cited.' Provide 2-3 [EXAMPLES] showing correct classification decisions for your domain, including edge cases where a passage appears relevant but is actually redundant or outdated. Before deploying, validate that the output JSON parses correctly and that every input passage_id appears exactly once across the pruned and removed arrays.
Prompt Variables
Required and optional inputs for the Context Pruning Prompt. Validate these before assembly to prevent runtime failures or silent misclassification.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The current task or question that defines relevance for the evidence. | What are the side effects of Drug X in elderly patients? | Must be non-empty and under 2000 chars. Check for injection patterns before insertion. |
[EVIDENCE_LIST] | Array of retrieved passages to classify and prune. Each item must have an ID and text. | [{"id": "p1", "text": "Drug X shows efficacy..."}, {"id": "p2", "text": "Elderly patients often..."}] | Validate JSON array structure. Each object requires id (string) and text (string). Max 50 passages per call. |
[CLASSIFICATION_TIERS] | The three-tier labels used for sorting evidence: essential, supportive, irrelevant. | ["essential", "supportive", "irrelevant"] | Must be exactly three tiers. Do not change tier names without updating downstream filters. |
[TASK_DOMAIN] | Optional domain label that sharpens relevance criteria for specialized fields. | clinical_evidence_review | If null, the prompt uses general relevance heuristics. If set, validate against allowed domain list. |
[MAX_PRUNED_COUNT] | Optional ceiling on the number of passages to retain after pruning. | 5 | If set, must be a positive integer. If null, all non-irrelevant passages are retained. Warn if set below 1. |
[REMOVAL_JUSTIFICATION] | Boolean flag controlling whether the prompt outputs reasons for each dropped passage. | Must be true or false. Set to false for latency-sensitive pipelines where justification is not required. | |
[OUTPUT_SCHEMA] | JSON schema that the pruned output must conform to. | {"type": "object", "properties": {"retained": {"type": "array"}, "removed": {"type": "array"}}} | Validate as valid JSON Schema draft-07. Required fields: retained, removed. Each item in removed must include a justification field if REMOVAL_JUSTIFICATION is true. |
Implementation Harness Notes
How to wire the context pruning prompt into a production RAG pipeline with validation, retries, and observability.
The context pruning prompt is not a standalone utility; it is a pipeline stage that sits between retrieval and answer generation. The typical call pattern is: retrieve N passages, assemble them into the [CONTEXT] placeholder, invoke the pruning prompt, validate the output, and pass only the essential and supportive passages to the downstream generation prompt. This stage should be treated as a deterministic filter with a structured output contract—not an open-ended chat completion. Use a low-temperature setting (0.0–0.2) and a model that reliably produces valid JSON, such as gpt-4o or claude-3-5-sonnet, to minimize variance in classification decisions.
Validation and retry logic must be built around the expected output schema. Before the pruned context reaches the answer generator, validate that: (1) the response is parseable JSON matching the pruned_context schema; (2) every passage ID in the output exists in the input set; (3) no passage appears in more than one tier; and (4) the removal_justifications array has an entry for every irrelevant passage. If validation fails, retry once with the same prompt and a slightly higher temperature (0.3) to jitter the output. If the second attempt fails, log the failure, fall back to passing all passages to the answer generator, and flag the request for review. For high-stakes domains, add a human review gate on any batch where more than 30% of retrieved passages are classified as irrelevant, as this may indicate a retrieval quality problem rather than a pruning problem.
Observability is critical because pruning decisions directly affect downstream answer quality. Log the full input passage set, the pruning output, the token count before and after pruning, and the latency of the pruning call. Attach a trace ID that links the retrieval, pruning, and generation stages so operators can diagnose whether a bad answer originated from poor retrieval, overly aggressive pruning, or a generation failure. If your pipeline uses a feature flag or A/B testing framework, wrap the pruning stage so you can compare answer quality with and without pruning in production. Start with a conservative pruning threshold—only drop passages classified as irrelevant with high confidence—and tighten only after reviewing pruning decisions against human judgments on a labeled eval set.
Common Failure Modes
Context pruning prompts reduce token costs and improve signal-to-noise ratios, but they introduce specific failure modes that can silently degrade downstream task quality. Each card below identifies a common breakage pattern and the guardrail that prevents it.
Critical Evidence Dropped as Irrelevant
What to watch: The pruning prompt classifies a passage as irrelevant because it lacks keyword overlap with the query, even though the passage contains essential context, counter-evidence, or definitions the downstream task needs. This is the most common and most damaging failure mode. Guardrail: Require the pruning prompt to output explicit removal justifications for each dropped passage. Run a recall check that verifies key facts from the original context set still appear in the pruned set before proceeding.
Hallucinated Summaries in Removal Justifications
What to watch: When the pruning prompt is asked to justify why a passage was removed, it may fabricate a plausible-sounding reason that misrepresents the passage content. This creates a false sense of auditability. Guardrail: Include a constraint in the prompt that removal justifications must quote the specific sentence or phrase that led to the decision. If no quote can be provided, the passage must be retained. Validate justifications against source text.
Classification Drift Across Similar Passages
What to watch: The model inconsistently classifies near-identical passages, marking one as essential and its duplicate as irrelevant. This erodes trust in the pruning logic and can drop the only clean copy of a critical fact. Guardrail: Add a deduplication step before classification. Instruct the pruning prompt to treat passages with overlapping factual content as a group and apply the same classification tier to all members of the group.
Over-Pruning Under Token Budget Pressure
What to watch: When a strict token ceiling is specified, the model may drop supportive passages to meet the budget rather than flagging that the budget is insufficient. The output looks compliant but is missing necessary context. Guardrail: Instruct the pruning prompt to emit a budget adequacy flag. If the essential tier alone exceeds the token budget, the prompt must return an error state rather than silently dropping essential evidence. The application layer should escalate or expand the budget.
Loss of Source Provenance After Pruning
What to watch: The pruning prompt reorders or merges passages and drops source identifiers, making downstream citations impossible. The pruned context becomes a black box with no traceability to original documents. Guardrail: Require the pruning prompt to preserve a source ID and character offset range for every retained passage. Validate that every retained passage has a non-null source reference before the pruned context is passed downstream.
Temporal Context Stripped from Time-Sensitive Evidence
What to watch: The pruning prompt correctly identifies a passage as relevant but strips the timestamp, version marker, or effective date during compression. Downstream tasks then treat outdated information as current. Guardrail: Add a temporal preservation rule to the pruning prompt: any passage containing a date, version, or time-sensitive claim must retain that temporal marker verbatim in the pruned output. Validate temporal markers post-pruning.
Evaluation Rubric
Use this rubric to test the Context Pruning Prompt before shipping. Each criterion targets a specific failure mode observed in production pruning pipelines. Run these checks on a golden dataset of 20-30 context sets with known essential, supportive, and irrelevant passages.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Essential Passage Retention | All passages labeled essential in the golden set appear in the pruned output with their original content intact | A golden-essential passage is missing from the pruned output or its content has been altered | Exact match of passage IDs between golden essential set and pruned output; spot-check 5 random passages for content fidelity |
Irrelevant Passage Removal | All passages labeled irrelevant in the golden set are absent from the pruned output | A golden-irrelevant passage appears in the pruned output without a documented override justification | Diff of passage IDs between golden irrelevant set and pruned output; flag any overlap as failure |
Removal Justification Completeness | Every removed passage has a non-empty, specific justification that references the task or query, not a generic phrase | A removed passage has an empty justification, a generic phrase like 'not relevant', or no justification field at all | Parse the justification field for each removed passage; reject if length < 20 characters or matches a banned generic-phrase list |
Supportive Passage Classification Consistency | Passages labeled supportive in the golden set are classified as either supportive or essential in the output, never as irrelevant | A golden-supportive passage is classified as irrelevant and removed from the pruned context | Cross-reference golden supportive labels against output classification; any supportive-to-irrelevant downgrade is a failure |
Pruned Output Structural Integrity | The pruned output preserves the original passage structure with ID, text, and classification fields; no truncated or malformed entries | A passage in the pruned output has a missing ID, truncated text mid-sentence, or an unrecognized classification value | Schema validation against expected output contract; check that all passage IDs match the source set and text fields are complete sentences |
Task Alignment of Retention Decisions | Retained passages directly address the stated task or query; no passage is kept solely because it is factually true but task-irrelevant | A passage is retained in the pruned output despite having no semantic overlap with the task description when reviewed by a second LLM judge | LLM-as-judge pairwise comparison: for each retained passage, ask an independent evaluator prompt whether the passage supports the task; flag false positives |
Token Budget Compliance | The total token count of the pruned context is at or below the specified [MAX_TOKENS] constraint | The pruned context exceeds [MAX_TOKENS] by more than 5% without an explicit overflow flag in the output | Tokenize the pruned output with the target model's tokenizer; compare against [MAX_TOKENS]; fail if count > 1.05 * [MAX_TOKENS] |
No Hallucinated Passages | Every passage in the pruned output exists verbatim in the input context set; no synthesized or merged passages appear | A passage in the pruned output cannot be matched to any input passage by ID or by fuzzy text match above 90% similarity | Fuzzy string matching between each pruned passage text and all input passage texts; flag any pruned passage with < 90% max similarity to any input passage |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base classification prompt and a simple JSON output instruction. Use a small set of passages (3–5) and manually review every classification. Skip the removal-justification field initially—focus on getting the three-tier label (essential/supportive/irrelevant) correct first.
codeClassify each passage as "essential", "supportive", or "irrelevant" to the query. Query: [QUERY] Passages: [PASSAGE_LIST] Return JSON: [{"id": "...", "label": "..."}]
Watch for
- Model conflating "supportive" with "essential" when both mention the topic
- Overly strict irrelevance classification that drops context a human would keep
- No baseline accuracy measurement before iterating

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us