Inferensys

Prompt

Pairwise Comparison Prompt for RAG Answer Quality

A practical prompt playbook for using Pairwise Comparison Prompt for RAG Answer Quality in production AI workflows.
Elegant overhead shot of a polished wooden communal table in a sun-drenched WeWork lounge, laptops and tablets displaying AI workflow dashboards, plants and pendant lights in background.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the job-to-be-done, ideal user, required context, and when not to use this pairwise comparison prompt.

This playbook is for RAG system builders who need to compare two grounded answers against the same source material and decide which one is better. Unlike absolute scoring, pairwise comparison forces a relative judgment that is often more reliable for champion-challenger testing, model selection, and RLHF data pipelines. Use this prompt when you have two answers generated from the same retrieval context and you need a structured preference verdict based on faithfulness, citation accuracy, completeness, and source conflict handling. This prompt includes a hallucination cross-check and citation verification harness that makes it suitable for production evaluation pipelines where groundedness is the primary safety property.

The ideal user is an AI engineer or evaluation lead running a champion-challenger test between two RAG configurations, an ML engineer curating preference pairs for DPO fine-tuning, or a platform team member building an automated regression gate that compares a new prompt or model version against the current production baseline. The required context includes the original user question, the shared set of retrieved source passages, and the two answers being compared. Without this shared grounding material, the comparison reduces to stylistic preference rather than factual accuracy, which defeats the purpose of this prompt.

Do not use this prompt when the two answers are generated from different retrieval contexts, when you need an absolute quality score rather than a relative preference, or when the evaluation criteria extend beyond groundedness into dimensions like creativity, brand voice, or user engagement that lack source evidence. This prompt is also inappropriate for single-answer evaluation, multi-turn conversation assessment, or cases where the source material itself is contradictory or incomplete without explicit handling instructions. For those scenarios, use a rubric-based absolute scoring prompt, a multi-turn evaluation prompt, or a source quality pre-check respectively.

Before running this prompt at scale, calibrate its judgments against human preference labels on a representative sample of your domain data. Position bias is a known failure mode in pairwise LLM judges—always randomize the order of answers A and B, and run a subset of comparisons in both orders to measure sensitivity. The hallucination cross-check harness described in the implementation section adds a second verification pass that independently extracts claims from each answer and checks them against the source passages, providing a safety net when the primary comparison misses unsupported statements.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and what you must provide before using it in a RAG evaluation pipeline.

01

Good Fit: Champion-Challenger RAG Pipelines

Use when: comparing two RAG answer generators against the same retrieved context. Guardrail: randomize answer positions and run multiple passes to detect position bias before trusting preference labels.

02

Good Fit: RLHF Preference Data Generation

Use when: building preference pairs for DPO or reward model training. Guardrail: require structured justifications with each preference and filter pairs where the judge cannot articulate a clear reason for its choice.

03

Bad Fit: Single-Answer Absolute Scoring

Avoid when: you need a numeric score for one answer rather than a relative preference. Guardrail: use a rubric-based scoring prompt instead. Pairwise comparison forces a choice even when both answers are excellent or both are poor.

04

Bad Fit: No Source Material Available

Avoid when: the judge cannot inspect the retrieved passages that grounded each answer. Guardrail: always include the shared source material in the prompt. Without it, the judge cannot verify faithfulness or detect hallucinations.

05

Required Input: Shared Retrieved Context

Risk: comparing answers without the source passages they cite produces preference based on style, not groundedness. Guardrail: include the full retrieved context block and require the judge to cross-check claims against it before declaring a preference.

06

Operational Risk: Position Bias

Risk: LLM judges systematically prefer the first or second answer regardless of quality. Guardrail: run each comparison twice with swapped positions and discard pairs where the preference flips. Flag position-sensitive pairs for human review.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for comparing two RAG-generated answers against shared source material to produce a structured preference verdict.

This prompt template is designed to be dropped into an evaluation harness that supplies two candidate answers and the source context from which they were generated. It forces a structured, evidence-backed preference based on faithfulness, citation accuracy, completeness, and source conflict handling. The placeholders are intentionally granular so you can control the comparison dimensions, output schema, and risk tolerance without rewriting the core instruction.

text
You are an evaluation judge comparing two answers generated by a Retrieval-Augmented Generation (RAG) system. Both answers were produced from the same set of source documents. Your job is to determine which answer is better and explain why.

## SOURCE MATERIAL
[SOURCE_CONTEXT]

## ANSWER A
[ANSWER_A]

## ANSWER B
[ANSWER_B]

## COMPARISON DIMENSIONS
Evaluate both answers on the following dimensions. For each dimension, state which answer performs better and provide a brief evidence-backed justification.

1. **Faithfulness**: Does the answer contain only claims supported by the source material? Flag any unsupported claims or hallucinations.
2. **Citation Accuracy**: Are citations present, correctly placed, and do they point to the right source passages? Flag miscitations or missing citations where a claim requires support.
3. **Completeness**: Does the answer address all parts of the user's question without omitting key information present in the sources?
4. **Source Conflict Handling**: If sources contradict each other, does the answer acknowledge the conflict rather than silently picking one side or blending contradictory claims?

## OUTPUT FORMAT
Return a JSON object with the following structure:

{
  "preferred_answer": "A" | "B" | "TIE",
  "confidence": 0.0-1.0,
  "dimension_verdicts": {
    "faithfulness": {"winner": "A" | "B" | "TIE", "justification": "string"},
    "citation_accuracy": {"winner": "A" | "B" | "TIE", "justification": "string"},
    "completeness": {"winner": "A" | "B" | "TIE", "justification": "string"},
    "source_conflict_handling": {"winner": "A" | "B" | "TIE", "justification": "string"}
  },
  "overall_justification": "string summarizing the key reasons for the preference",
  "hallucination_flags": [
    {"answer": "A" | "B", "claim": "string", "severity": "CRITICAL" | "MAJOR" | "MINOR"}
  ],
  "citation_errors": [
    {"answer": "A" | "B", "claim": "string", "cited_source": "string", "error_type": "MISCITATION" | "MISSING_CITATION" | "IRRELEVANT_CITATION"}
  ]
}

## CONSTRAINTS
- Base your judgment ONLY on the source material provided. Do not use external knowledge.
- If both answers are equally good or equally flawed, use "TIE" and explain why neither is clearly better.
- Flag every unsupported claim in the hallucination_flags array, even if the answer is otherwise preferred.
- If a dimension is not applicable (e.g., no citations exist in either answer), mark it as "TIE" and explain.
- Confidence should reflect how certain you are in the preference, not the quality of the preferred answer.
- [ADDITIONAL_CONSTRAINTS]

## EXAMPLES
[FEW_SHOT_EXAMPLES]

Adapt this template by adjusting the comparison dimensions to match your RAG system's quality priorities. If citation accuracy is irrelevant because your system doesn't produce citations, remove that dimension and update the output schema. Add few-shot examples that demonstrate your expected preference behavior, especially for edge cases like partially correct answers, conflicting sources, or answers that are faithful but incomplete. The [ADDITIONAL_CONSTRAINTS] placeholder lets you inject domain-specific rules—for example, preferring shorter answers when quality is equal, or deprioritizing answers that use speculative language. Always validate the JSON output against the schema before accepting the verdict, and log dimension-level scores for drift monitoring over time.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Pairwise Comparison Prompt for RAG Answer Quality. Each variable must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of invalid verdicts.

PlaceholderPurposeExampleValidation Notes

[QUESTION]

The user question both answers attempt to address

What is the refund policy for annual subscriptions?

Must be non-empty string. Truncate if >500 chars. Log original for trace.

[SOURCE_MATERIAL]

Shared ground-truth context both answers should be grounded in

Section 4.2: Annual subscriptions may be refunded within 30 days of purchase...

Must be non-empty string. Strip PII before insertion. Verify source hash matches retrieval record.

[ANSWER_A]

First candidate answer to evaluate

You can get a full refund within 30 days of your annual subscription purchase.

Must be non-empty string. Label consistently to avoid position bias. Randomize order before injection.

[ANSWER_B]

Second candidate answer to evaluate

Refunds are available for annual plans if requested within the first month.

Must be non-empty string. Must differ from [ANSWER_A] by at least 5 characters to avoid identity comparison.

[EVALUATION_DIMENSIONS]

Ordered list of dimensions to judge, with definitions

  1. Faithfulness: Does the answer only make claims supported by the source? 2. Citation Accuracy: Are claims linked to correct source passages? 3. Completeness: Does the answer address all parts of the question?

Must be a valid JSON array of strings. Minimum 1 dimension. Max 5. Each dimension must have a one-sentence definition.

[TIE_BREAKING_PRIORITY]

Which dimension wins if answers are equal on all others

Faithfulness

Must match exactly one value from [EVALUATION_DIMENSIONS]. Reject if not found in dimension list.

[OUTPUT_FORMAT]

Expected JSON schema for the verdict

{"preference": "A" | "B" | "TIE", "justification": "...", "dimension_scores": {...}, "hallucination_flags": [...]}

Must be a valid JSON Schema object. Validate with ajv or similar before prompt assembly. Reject if schema is not parseable.

[CONFIDENCE_THRESHOLD]

Minimum confidence required to return a preference instead of TIE

0.7

Must be a float between 0.0 and 1.0. If model confidence is below threshold, force TIE verdict. Log threshold for audit.

PRACTICAL GUARDRAILS

Common Failure Modes

Pairwise comparison prompts for RAG answer quality break in predictable ways. These are the most common failure modes, why they happen, and how to guard against them before they corrupt your evaluation pipeline.

01

Position Bias Skews Preference

What to watch: The judge consistently prefers the first answer (or the second) regardless of quality. This is the most common failure in pairwise evaluation and silently invalidates preference data. Guardrail: Randomize answer order per comparison and log the original position. Run a position-bias check by comparing identical answers in swapped positions—any preference indicates bias. Use calibration pairs with known human labels to detect drift.

02

Judge Prefers Longer Answers Over Accurate Ones

What to watch: The judge conflates verbosity with quality, selecting the longer answer even when it contains hallucinations or irrelevant detail. This is especially dangerous in RAG evaluation where grounded brevity should win. Guardrail: Include a conciseness dimension in the rubric that penalizes unnecessary length. Add an explicit instruction: 'Do not prefer an answer because it is longer. A shorter, fully-grounded answer should win over a longer, partially-grounded one.' Test with a pair where the shorter answer is clearly better.

03

Hallucination Cross-Check Misses Fabricated Citations

What to watch: The judge accepts plausible-sounding citations that don't exist in the source material. The model invents document sections, page numbers, or quote fragments that sound authoritative but are entirely fabricated. Guardrail: Require the judge to verify every citation against the provided source material explicitly. Add a step: 'For each citation, confirm the exact text appears in the source. If a citation cannot be verified, flag it as unsupported and penalize the answer.' Use a separate hallucination detection pass before the pairwise comparison.

04

Source Conflict Resolution Produces False Balance

What to watch: When sources contradict each other, the judge rewards answers that split the difference or present both sides equally, even when one source is clearly more authoritative or recent. This produces preference for false balance over accurate resolution. Guardrail: Add a source conflict handling criterion: 'When sources conflict, prefer the answer that correctly identifies the conflict, explains the contradiction, and prioritizes the more authoritative or recent source with explicit reasoning.' Include test pairs with known source conflicts and expected resolution behavior.

05

Judge Ignores Abstention When It's Correct

What to watch: When neither answer can be fully grounded in the source material, the judge still picks a winner instead of recognizing that both should abstain. This produces preference labels for answers that should have been rejected entirely. Guardrail: Add an explicit abstention evaluation step: 'If neither answer is adequately grounded in the provided sources, both should be rejected. Do not force a preference when both answers contain unsupported claims. Flag the pair as a tie with a note that neither answer meets the grounding threshold.' Include a 'reject both' option in the output schema.

06

Citation Accuracy Is Confused With Citation Density

What to watch: The judge rewards answers with many citations regardless of whether those citations actually support the claims they're attached to. High citation count masks low citation accuracy. Guardrail: Separate citation count from citation accuracy in the rubric. Add a verification step: 'For each citation, check whether the cited source actually supports the specific claim it's attached to. Penalize citations that reference irrelevant passages or contradict the claim. Prefer the answer with fewer but more accurate citations over the answer with many inaccurate ones.'

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the Pairwise Comparison Prompt's output quality before integrating it into a RAG evaluation pipeline. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Output Schema Validity

Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed.

JSON parse error, missing required field like preferred_answer_id, or field type mismatch (e.g., confidence is a string).

Automated schema validation check on 100 test runs. Use a JSON Schema validator against the defined [OUTPUT_SCHEMA].

Preference Verdict Consistency

The preferred_answer_id is either A or B and is consistent with the justification text.

Verdict is A but justification describes B as better, or verdict is null without a valid tie-breaker reason.

LLM-as-judge consistency check: feed the justification and verdict to a separate validator prompt to confirm alignment. Manual review on a 20% sample.

Citation Accuracy

Every citation in the justification references a real passage in [SOURCE_MATERIAL] and supports the claim made.

A citation points to a non-existent passage ID, or the cited text does not support the justification's claim.

Automated citation grounding check: extract all citation IDs from the output and verify they exist in [SOURCE_MATERIAL]. For a 10% sample, manually verify the cited text supports the claim.

Hallucination Cross-Check

The justification contains no factual claims not directly attributable to [SOURCE_MATERIAL].

The justification introduces new facts, entities, or events not present in the source material.

LLM-as-judge faithfulness check: prompt a separate model to verify each sentence in the justification against [SOURCE_MATERIAL]. Flag any unsupported sentences for human review.

Confidence Score Calibration

The confidence score (0.0-1.0) correlates with the ambiguity of the comparison. Clear wins have high confidence; near-ties have low confidence.

A high confidence score (e.g., 0.95) is assigned to a comparison where the justification describes a near-tie, or vice-versa.

Run 50 comparisons with known human preference labels. Calculate Expected Calibration Error (ECE) between the model's confidence and human agreement rates. Flag if ECE > 0.1.

Position Bias Mitigation

The preference verdict is not statistically biased toward position A or B across a balanced test set.

In a set of 100 comparisons where the order of A and B is randomized, the model selects position A more than 60% of the time.

Run a balanced test set of 100 comparisons with randomized positions. Perform a binomial test on the preference distribution. Fail if p < 0.05 for bias toward one position.

Tie-Breaking Logic

When both answers are equally faithful and complete, the output correctly identifies a tie and uses [TIE_BREAKING_CRITERIA] to force a choice or declare a true tie.

The model declares a tie without analyzing [TIE_BREAKING_CRITERIA], or forces a choice based on an irrelevant or hallucinated differentiator.

Test on a curated set of 10 known tie cases. Verify the justification explicitly references the configured [TIE_BREAKING_CRITERIA] and the final verdict is logically consistent with it.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the pairwise comparison prompt into a production RAG evaluation pipeline with validation, position bias mitigation, and result logging.

This prompt is designed to operate as a stateless evaluation function within a larger RAG quality pipeline. It expects two complete answer objects and a shared set of source documents as input, and it returns a structured preference verdict. The implementation harness must handle input assembly, position randomization, output validation, and result storage. Do not use this prompt directly on raw model outputs without first attaching the source documents that grounded each answer. The prompt assumes answers are already generated and that the comparison is the only task.

Position bias mitigation is mandatory. Before calling the prompt, randomly swap the order of [ANSWER_A] and [ANSWER_B] and record the swap state in a metadata field. After receiving the preference verdict, remap the result back to the original answer identities. Without this, the model may systematically prefer the first or second position regardless of quality. Implement this as a pre-processing step in your harness, not as a prompt instruction. Log the swap state alongside every comparison result for later audit and bias analysis.

Output validation must be strict. Parse the model response as JSON and validate that the preference field contains exactly one of the allowed values: ANSWER_A, ANSWER_B, or TIE. Reject any response that does not conform to the output schema. If the model returns a preference for an answer that does not exist in the input, log the mismatch and retry with a clarified prompt. For high-stakes evaluation pipelines, implement a retry budget of 2-3 attempts with exponential backoff before escalating to human review. Store raw model responses alongside parsed results for debugging judge drift over time.

Citation verification requires a post-processing step. The prompt asks the judge to flag unsupported claims, but the harness should independently cross-check any hallucination flags against the provided source documents using a separate grounding check. Do not treat the judge's hallucination detection as authoritative without verification. For production systems, maintain a disagreement log where the judge's hallucination flags are compared against a secondary fact-checking prompt or human audit sample. This dual-layer approach catches judge errors before they corrupt your evaluation metrics.

Model choice matters for judge reliability. This prompt works best with frontier models that have strong instruction-following and structured output capabilities. Avoid using smaller or older models as judges for RAG quality comparison, as they are more likely to produce inconsistent verdicts or hallucinate citations. If cost constraints require a smaller judge model, increase the retry budget and lower the confidence threshold for automatic acceptance. Always run a calibration set of 50-100 human-labeled comparison pairs through the judge before trusting its output in production. Track judge-human agreement rates over time and trigger a recalibration review if agreement drops below your defined threshold.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base pairwise comparison prompt and a small set of 20-30 RAG answer pairs. Use a single model as both generator and judge. Skip position bias mitigation initially—just run each pair once. Store results in a CSV with columns: pair_id, source_doc, answer_a, answer_b, preference, rationale. Focus on whether the judge's reasoning makes sense, not on statistical rigor.

Watch for

  • Position bias: the judge may consistently prefer Answer A over Answer B regardless of quality. Spot-check by manually swapping positions on 5 pairs.
  • Overly verbose rationales that sound plausible but miss factual errors. Cross-check 3-5 rationales against the source material yourself.
  • The judge avoiding hard calls by marking everything as a tie. Add a tie-breaking instruction early: "If both answers are nearly identical in quality, you may declare a tie, but you must explain why neither answer is clearly better."
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.