Inferensys

Prompt

Evidence Ranking Error Counterexample Prompt

A practical prompt playbook for using Evidence Ranking Error Counterexample Prompt 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 the Evidence Ranking Error Counterexample Prompt.

This prompt is for RAG system builders who need to teach a model to distinguish strong evidence from weak or irrelevant sources by showing it what incorrect prioritization looks like. The primary job-to-be-done is reducing retrieval noise and improving answer grounding by injecting negative examples that demonstrate flawed ranking decisions—favoring a document that matches keywords but contradicts the query's intent, selecting a source with low authority, or ignoring a directly relevant passage in favor of a tangentially related one. The ideal user is an AI engineer or search quality engineer who already has a working retrieval pipeline and needs to fine-tune the model's evidence selection behavior through few-shot counterexamples rather than rewriting the entire system prompt.

Use this prompt when you observe systematic ranking errors in production: the model consistently picks the first retrieved chunk regardless of relevance, gets distracted by high-term-overlap but semantically irrelevant documents, or fails to prefer authoritative sources when they are available. It is most effective when you have a labeled set of query-evidence pairs where the correct ranking is known, and you can extract specific failure cases to use as negative demonstrations. The prompt template expects you to provide [INPUT_QUERY], a [RETRIEVED_EVIDENCE_SET] with multiple candidate passages, and one or more [INCORRECT_RANKING_EXAMPLES] that show the model what not to do. Do not use this prompt when your retrieval system itself is broken—if the correct evidence is never retrieved, no amount of ranking instruction will fix the problem. This prompt addresses ranking quality, not retrieval recall.

Avoid deploying this prompt without a validation harness that measures ranking quality metrics like NDCG, MRR, or precision@k against a held-out test set. Counterexamples can over-correct: a model shown only ranking failures may become overly conservative, refusing to rank any evidence confidently or requiring excessive source verification. Pair this prompt with positive examples that show correct ranking behavior, and run regression tests to ensure the counterexamples improve ranking accuracy without introducing new failure modes. If the ranking task involves regulated content—medical, legal, or financial evidence—always include a human review step before the ranked results are surfaced to end users.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Evidence Ranking Error Counterexample Prompt works and where it introduces risk. Use these cards to decide if this prompt fits your retrieval pipeline before investing in integration.

01

Strong Fit: RAG Systems with Measurable Ranking Quality

Use when: you have an existing retrieval pipeline and can measure NDCG, MRR, or precision@k. Why: the prompt teaches the model to avoid weak-evidence prioritization through negative examples, which directly improves ranking metrics. Guardrail: run A/B tests comparing retrieval quality with and without the counterexample prompt to confirm lift before full deployment.

02

Weak Fit: Black-Box Retrieval Without Ranking Access

Avoid when: you cannot modify or observe the ranking layer between retrieval and generation. Risk: the prompt teaches ranking discipline, but if your system hides ranking decisions from the model, the negative examples have no effect. Guardrail: verify that your architecture exposes ranked passages to the model before adopting this prompt.

03

Required Input: Labeled Ranking Mistakes

Prerequisite: you need concrete examples of incorrect rankings—where irrelevant or weak passages were scored above relevant ones. Why: the prompt relies on negative demonstrations of real failure patterns. Guardrail: curate at least 5-10 real ranking errors from production logs or manual review before generating the prompt. Synthetic counterexamples alone may miss domain-specific failure modes.

04

Operational Risk: Stale Counterexamples After Index Refresh

What to watch: counterexamples become stale when your document index changes significantly. Risk: negative examples referencing removed or updated documents teach the model to avoid patterns that no longer exist, wasting tokens and potentially confusing ranking behavior. Guardrail: schedule counterexample review after major index updates and monitor NDCG drift weekly.

05

Token Budget Risk: Counterexample Overhead

What to watch: each negative example consumes tokens that could be used for positive demonstrations or additional context. Risk: overloading the prompt with counterexamples reduces the space available for actual evidence, degrading answer quality. Guardrail: cap counterexamples at 20-30% of your total example budget and measure answer faithfulness alongside ranking metrics.

06

Evaluation Requirement: NDCG and Ranking Quality Metrics

What to watch: without evaluation, you cannot confirm the prompt is improving ranking behavior. Risk: the prompt may appear to work anecdotally while silently introducing new ranking biases. Guardrail: implement automated NDCG measurement against a held-out query set before and after prompt deployment. Require statistically significant improvement before production release.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that teaches a model to avoid incorrect evidence ranking by providing negative examples of favoring irrelevant or weak sources.

This prompt template is designed for RAG system builders who need to fine-tune a model's ability to prioritize evidence. It works by presenting a query and a set of retrieved passages, then demonstrating an incorrect ranking as a negative example. The model learns to avoid common pitfalls like prioritizing a source based on keyword density, source recency, or authority bias when the content is irrelevant to the specific query. The core mechanism is a few-shot counterexample that pairs a flawed ranking with an explicit critique, teaching the model why the ranking is wrong before it attempts the real task.

code
You are an evidence ranking assistant. Your task is to rank the provided text passages by their relevance to the user's query. The most relevant passage should be ranked first.

A good ranking directly addresses the query's core intent with specific facts. A bad ranking is distracted by superficial keyword matches, high-level topic similarity, or the perceived authority of the source when the content does not answer the question.

---
NEGATIVE EXAMPLE:

User Query: [EXAMPLE_QUERY]

Retrieved Passages:
[PASSAGE_A]: [TEXT_OF_IRRELEVANT_PASSAGE_A]
[PASSAGE_B]: [TEXT_OF_HIGHLY_RELEVANT_PASSAGE_B]
[PASSAGE_C]: [TEXT_OF_IRRELEVANT_PASSAGE_C]

Incorrect Ranking and Critique:
1. [PASSAGE_A] - INCORRECT. This passage is ranked first because it contains the keyword "[KEYWORD]" many times, but it discusses a completely different context and does not answer the query.
2. [PASSAGE_C] - INCORRECT. This passage is from a highly authoritative source, but its content is only tangentially related to the query's specific question.
3. [PASSAGE_B] - CORRECT RANK. This passage directly answers the query with specific evidence, but it was incorrectly deprioritized.

---
TASK:

Now, rank the following passages for the new user query. Provide your output as a JSON object with a "ranking" key containing an ordered list of passage IDs, and a "critique" key explaining why the top-ranked passage is the most relevant.

User Query: [INPUT_QUERY]

Retrieved Passages:
[PASSAGE_1]: [TEXT_OF_PASSAGE_1]
[PASSAGE_2]: [TEXT_OF_PASSAGE_2]
[PASSAGE_3]: [TEXT_OF_PASSAGE_3]

Output Schema:
{
  "ranking": ["PASSAGE_ID"],
  "critique": "string"
}

To adapt this template, replace the bracketed placeholders in the NEGATIVE EXAMPLE section with a realistic failure case from your own retrieval pipeline. The example must clearly show a non-relevant passage winning due to a specific, named bias (e.g., keyword density, source authority). For the TASK section, inject your live query and candidate passages. The Output Schema enforces a structured response that is easy to validate. Before deploying, run this prompt against a golden dataset where the correct ranking is known and measure the Normalized Discounted Cumulative Gain (NDCG) to ensure the counterexample is steering the model toward better precision, not just memorizing the negative case.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Evidence Ranking Error Counterexample Prompt. Each variable must be populated before the prompt is assembled and sent to the model.

PlaceholderPurposeExampleValidation Notes

[QUERY]

The user question or search string for which evidence is being ranked.

What are the side effects of drug X?

Required. Must be a non-empty string. Check for minimum length of 10 characters to ensure meaningful retrieval context.

[RETRIEVED_PASSAGES]

A list of candidate passages returned by the retrieval system, including both relevant and irrelevant results.

[{"id": "p1", "text": "Drug X is generally well-tolerated..."}, {"id": "p2", "text": "Clinical trials for Drug Y showed..."}]

Required. Must be a valid JSON array of objects with id and text fields. Minimum 3 passages required to demonstrate ranking errors. Validate JSON parse succeeds.

[CORRECT_RANKING]

The ground-truth ranking of passage IDs ordered by relevance to the query, serving as the positive example.

["p1", "p3", "p2"]

Required. Must be a JSON array of strings matching passage IDs from [RETRIEVED_PASSAGES]. All IDs must exist in the passage set. Order must reflect true relevance.

[INCORRECT_RANKING]

A deliberately flawed ranking that prioritizes irrelevant or weak passages, serving as the negative example.

["p2", "p1", "p3"]

Required. Must be a JSON array of the same length and IDs as [CORRECT_RANKING] but in a different order. At least one high-relevance passage must be ranked last to demonstrate clear error.

[ERROR_EXPLANATION]

A concise explanation of why the incorrect ranking is wrong, highlighting specific evidence-quality failures.

Passage p2 discusses Drug Y, which is irrelevant to the query about Drug X. It should not be ranked first.

Required. Must be a non-empty string directly referencing passage IDs and explaining the ranking error. Validate that explanation mentions at least one passage ID from [INCORRECT_RANKING].

[DOMAIN]

The knowledge domain or corpus description to contextualize evidence quality expectations.

Biomedical research papers and clinical trial summaries

Optional but recommended. If provided, must be a non-empty string. If null, the prompt uses a generic evidence-quality frame. Validate that domain is not a single generic word like 'general'.

[RANKING_CRITERIA]

Explicit criteria for what makes evidence strong or weak in this context.

Relevance to query, source authority, recency, directness of evidence, absence of speculation

Optional. If provided, must be a non-empty string or list. If null, the prompt defaults to general relevance and source quality. Validate that criteria are actionable and not circular.

[OUTPUT_FORMAT]

The expected structure for the model's final ranking output after learning from the counterexample.

JSON array of passage IDs in ranked order with a confidence score per passage

Required. Must describe a parseable output schema. Validate that the format specification includes field names and types. Schema check: output must be valid JSON matching this spec.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Evidence Ranking Error Counterexample Prompt into a RAG evaluation pipeline with validation, metrics, and retry logic.

This prompt is not a one-shot generation task; it is a synthetic data generator for evaluation. The primary implementation pattern is to call this prompt programmatically to produce a labeled dataset of (query, evidence_list, incorrect_ranking) tuples. These tuples are then used to test your production ranker's ability to avoid the demonstrated mistakes. The harness must therefore treat the LLM call as a data factory, not a runtime component. Each generated counterexample should be validated for structural correctness before being admitted to the evaluation set.

Wiring the call: Construct the request by injecting a real [QUERY] and a set of [RETRIEVED_PASSAGES] from your retrieval system. The [INCORRECT_RANKING_PATTERN] variable should specify the type of error you want to test (e.g., 'favoring shorter passages over more relevant longer ones' or 'ranking by entity match count instead of semantic fit'). The model will return a JSON object containing the incorrect ranking order and a justification. Validation step: Before using this output, validate that the returned ranked_passage_ids array contains exactly the same IDs as the input passages, with no additions or omissions. Reject any output that fails this check and retry with a lower temperature. Log the rejection reason for quality monitoring.

Metrics integration: The primary use of this prompt's output is to compute Normalized Discounted Cumulative Gain (NDCG) and Mean Reciprocal Rank (MRR) for your production ranker against the deliberately flawed baseline. Store each generated counterexample with a unique example_id and the error_type label. Run your production ranker on the same query and passage set, then compare its NDCG against the counterexample's NDCG. A production ranker that scores lower than the counterexample on a specific error type indicates a vulnerability that needs addressing. Human review gate: For high-stakes domains (medical, legal, financial), a domain expert should review a sample of generated counterexamples to confirm that the 'incorrect' ranking is genuinely flawed and not a plausible alternative interpretation. This prevents the evaluation set from teaching the wrong lesson.

Retry and fallback: If the model fails to produce valid JSON after two retries, or if the generated ranking is identical to the ideal ranking (indicating the model failed to produce a true counterexample), discard the attempt and log the query for manual curation. Do not silently include degenerate examples in your evaluation set. Model choice: This task benefits from models with strong instruction-following and JSON output capabilities. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are suitable. Avoid smaller models that may conflate the instruction to produce an incorrect ranking with a general tendency to hallucinate rankings that don't match the input passages. Next step: After accumulating a validated counterexample dataset, use it as a regression suite—run it before every ranker update to detect ranking quality regressions on known failure patterns.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the evidence ranking error counterexample output. Use this contract to validate model responses before accepting them in your RAG pipeline.

Field or ElementType or FormatRequiredValidation Rule

error_examples

Array of objects

Array length >= 1. Each element must be an object with all required sub-fields present.

error_examples[].query

String

Non-empty string. Must match the user's original information need, not a rewritten variant.

error_examples[].incorrect_ranking

Array of objects

Array length >= 2. Must contain at least one strong and one weak evidence item to demonstrate ranking inversion.

error_examples[].incorrect_ranking[].passage_id

String

Non-empty string matching a passage_id from the provided [RETRIEVED_PASSAGES] input. No fabricated IDs allowed.

error_examples[].incorrect_ranking[].relevance_label

String (enum)

Must be one of: 'highly_relevant', 'partially_relevant', 'irrelevant'. At least one item must be 'irrelevant' and ranked above a 'highly_relevant' item.

error_examples[].error_explanation

String

Concise explanation of why the ranking is incorrect. Must reference specific passage content or metadata, not generic statements. Max 200 characters.

error_examples[].correct_ranking

Array of strings (passage_ids)

Ordered list of passage_ids representing the correct relevance ranking. Must be a permutation of the IDs in incorrect_ranking. No additions or omissions.

metadata

Object

If present, must include 'generated_at' as ISO 8601 timestamp and 'model_id' as string. No other fields required.

PRACTICAL GUARDRAILS

Common Failure Modes

Evidence ranking prompts fail in predictable ways. These cards cover the most common failure modes when using counterexamples to teach correct evidence prioritization, along with concrete mitigations.

01

Near-Miss Confusion

What to watch: The model learns to reject obviously irrelevant evidence but still favors superficially related sources that don't actually support the claim. Counterexamples that are too easy create a false sense of robustness. Guardrail: Include near-miss negative examples where the evidence shares keywords or entities with the query but lacks logical support. Validate with adversarial test pairs that mix relevant and near-miss passages.

02

Overcorrection to Recency Bias

What to watch: Negative examples showing outdated evidence being incorrectly favored can cause the model to over-prioritize recency at the expense of authoritative older sources. The model starts treating publication date as a stronger signal than relevance. Guardrail: Include counterexamples that show both recency-over-relevance errors and authority-over-recency errors. Monitor NDCG across temporal distributions to detect drift toward recency bias.

03

Counterexample Contamination

What to watch: Negative examples that are too similar to valid positive cases cause the model to reject legitimate evidence. The model over-generalizes the rejection pattern and starts flagging correct rankings as errors. Guardrail: Test counterexample sets against a golden dataset of known-good rankings before deployment. Measure false rejection rate on positive cases and remove counterexamples that cause collateral damage to correct behavior.

04

Surface-Level Pattern Matching

What to watch: The model learns to reject evidence based on superficial formatting cues in the counterexamples—like missing metadata fields or shorter passage length—rather than actual relevance failures. Ranking quality degrades when evidence format changes. Guardrail: Vary the formatting, length, and metadata presence in both positive and negative examples. Test ranking consistency when the same evidence is presented with different formatting wrappers.

05

Ranking Collapse Under Evidence Volume

What to watch: Counterexamples designed for small evidence sets fail when retrieval returns many passages. The model's ranking discrimination degrades as the candidate pool grows, and mid-tier evidence gets scored randomly. Guardrail: Include negative examples with varying evidence set sizes, including high-volume scenarios. Test NDCG@k stability as k increases from 5 to 50. Consider two-stage ranking with coarse filtering before fine-grained prioritization.

06

Silent Hallucination in Ranking Justifications

What to watch: The model correctly ranks evidence but fabricates supporting reasoning that misrepresents what the source actually says. The ranking is right but the explanation is wrong—undermining trust and auditability. Guardrail: Add counterexamples where correct rankings are paired with fabricated justifications. Evaluate ranking explanations separately from ranking accuracy using citation faithfulness checks. Flag outputs where the justification contradicts the source text.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing whether the evidence ranking error counterexample prompt teaches the model to avoid favoring irrelevant or weak sources. Use this rubric before shipping the prompt into a RAG pipeline.

CriterionPass StandardFailure SignalTest Method

NDCG@5 improvement

NDCG@5 increases by ≥0.05 over baseline on held-out queries

NDCG@5 flat or decreases; weak sources still ranked above relevant ones

Run 50+ annotated queries through retrieval + ranking; compute NDCG@5 before and after prompt injection

Relevant source prioritization

≥90% of top-3 ranked passages are annotated as highly relevant

Top-3 contains ≥2 irrelevant or tangentially related passages in >20% of test queries

Spot-check 30 random outputs; label top-3 passages against ground-truth relevance judgments

Weak source demotion

Passages annotated as 'weak' or 'noisy' appear in top-5 for <10% of queries

Weak passages consistently outrank moderate-relevance passages in top-5

Track weak-source position distribution across test set; flag if median rank < 6

Counterexample pattern recognition

Model correctly identifies and avoids the demonstrated error pattern in ≥95% of test cases

Model repeats the exact ranking mistake shown in negative examples on similar inputs

Construct 10 probe queries structurally similar to counterexamples; verify error pattern is absent

Citation faithfulness

100% of ranked passages exist in the provided context; no hallucinated source IDs

Output references a passage ID or quote not present in the input context

Parse all output citations; cross-reference against input passage IDs; flag any mismatch

Abstention on insufficient evidence

Model returns empty or low-confidence ranking when no passage meets relevance threshold

Model confidently ranks irrelevant passages instead of indicating insufficient evidence

Feed 5 queries with only distractor passages; verify output indicates no strong evidence found

Ranking explanation quality

≥80% of ranking justifications cite specific passage content, not generic statements

Justifications use vague language like 'this seems relevant' without quoting or referencing passage details

Sample 20 ranking explanations; check for presence of direct quotes, section references, or specific entity mentions

Consistency across similar inputs

Identical or near-identical queries produce rankings with ≤1 position swap in top-3

Same query re-run produces completely different top-3 ordering with no input change

Run 10 queries 3 times each at temperature=0; measure top-3 overlap; flag if Jaccard similarity < 0.7

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small hand-curated set of 3-5 negative examples showing incorrect evidence ranking (e.g., favoring recency over relevance, selecting shorter passages over authoritative ones). Use a lightweight eval script that checks NDCG@5 against a golden ranking. Skip schema enforcement initially.

Watch for

  • Negative examples that are too obvious (model already avoids them)
  • Overfitting to your 5 examples without generalizing to new query types
  • No baseline NDCG measurement before adding counterexamples
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.