Inferensys

Prompt

Ground-Truth Answer Comparison Prompt for RAG

A practical prompt playbook for using Ground-Truth Answer Comparison Prompt for RAG in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, and boundaries for the Ground-Truth Answer Comparison Prompt for RAG.

This prompt is for RAG system builders who need to validate retrieval-augmented outputs against a known-correct answer. It acts as an automated judge, producing a structured comparison report that covers answer correctness, citation accuracy, and source faithfulness. Use this when you have a golden dataset of question-reference answer pairs and need to measure how well your RAG pipeline performs before shipping a new retriever, prompt, or model. It also detects abstention, distinguishing between a model that correctly refuses to answer and one that produces a wrong answer. This is not a prompt for generating answers. It is a prompt for evaluating them.

The ideal user is an AI engineer or evaluation lead running a regression suite before a RAG pipeline change. You should have a validated golden dataset where each record contains a user question, a known-correct reference answer, and the retrieved context chunks that were provided to the generation model. The prompt expects the model's generated answer alongside this ground truth. It is designed for pre-release gates, not real-time production monitoring. If you need to evaluate outputs without a reference answer, use a rubric-based judge instead. If you need to evaluate multi-turn conversations, this single-turn comparison prompt will miss context-switching failures.

Do not use this prompt when the reference answer is itself uncertain, when multiple valid answers exist with no clear ground truth, or when the evaluation requires domain expertise beyond what the judge model can reliably assess. For high-stakes domains like healthcare or legal review, always route flagged disagreements to a human reviewer rather than treating the judge's output as final. Wire the prompt into a test harness that logs every comparison, tracks score distributions over time, and alerts on sudden regressions. The next section provides the copy-ready template you can adapt to your schema and tolerance thresholds.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Ground-Truth Answer Comparison Prompt for RAG delivers reliable evaluation and where it introduces risk. Use these cards to decide if this prompt fits your pipeline before you integrate it.

01

Good Fit: Regression Gates with Golden Datasets

Use when: you have a curated set of question-reference answer pairs and need to catch regressions before deploying a new retriever or prompt. Guardrail: run this prompt as a blocking gate in CI; a drop in answer correctness or citation accuracy halts the release.

02

Good Fit: RAG System Tuning

Use when: you are iterating on chunk size, embedding model, or top-k and need a signal on whether end-to-end answer quality is improving. Guardrail: pair this prompt with retrieval-specific metrics; a good answer from stale sources is still a failure.

03

Bad Fit: Open-Ended Creative Tasks

Avoid when: the task has no single correct answer, such as summarization style or brainstorming. Guardrail: use a rubric-based judge instead; forcing a ground-truth comparison on subjective output produces misleading scores.

04

Bad Fit: Live User Traffic Without References

Avoid when: you lack a pre-written reference answer for every query. Guardrail: this prompt requires a known-correct answer; for live traffic, use a groundedness or faithfulness evaluator that checks against retrieved context only.

05

Required Inputs

Risk: incomplete inputs produce unreliable scores. Guardrail: ensure every evaluation sample includes the user question, the model's full answer, the retrieved context list, and the ground-truth reference answer. Missing any field should abort the evaluation run.

06

Operational Risk: Reference Drift

Risk: reference answers become stale as your knowledge base updates, causing false positives. Guardrail: version your golden dataset alongside your document store and re-validate references when source documents change; schedule a quarterly audit of reference freshness.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for comparing a RAG system's output against a known-correct ground-truth answer, producing a structured comparison report.

This prompt template is the core of the Ground-Truth Answer Comparison playbook. It instructs the model to act as an evaluator, comparing a generated answer against a reference answer and the provided source context. The template uses square-bracket placeholders for all dynamic inputs, making it straightforward to integrate into an evaluation harness. The goal is a structured report that assesses answer correctness, citation accuracy, and source faithfulness, while also detecting when the RAG system abstained from answering.

text
You are an expert evaluation judge for a Retrieval-Augmented Generation (RAG) system. Your task is to compare a generated answer against a known-correct ground-truth answer and the provided source context. Produce a structured comparison report.

## INPUTS
**User Question:** [USER_QUESTION]

**Generated Answer:** [GENERATED_ANSWER]

**Ground-Truth Answer:** [GROUND_TRUTH_ANSWER]

**Source Context (provided to the RAG system):** [SOURCE_CONTEXT]

## EVALUATION CRITERIA
1.  **Answer Correctness:** Does the generated answer contain the same core information as the ground-truth answer? Is it factually accurate based on the ground truth?
2.  **Citation Accuracy:** Are the claims in the generated answer supported by the provided source context? Check for hallucinations.
3.  **Source Faithfulness:** Does the generated answer faithfully represent the information in the source context, or does it misinterpret it?
4.  **Abstention Detection:** Did the RAG system correctly abstain from answering (e.g., "I don't know") if the source context lacked the necessary information? If the ground-truth answer indicates the question is unanswerable, the generated answer should abstain.

## OUTPUT FORMAT
Respond with a single JSON object conforming to this schema:
{
  "overall_score": "PASS" | "FAIL",
  "answer_correctness": {
    "score": "PASS" | "FAIL" | "PARTIAL",
    "explanation": "A concise explanation comparing the generated and ground-truth answers."
  },
  "citation_accuracy": {
    "score": "PASS" | "FAIL" | "NO_CITATIONS",
    "unsupported_claims": ["List of claims in the generated answer not found in the source context."],
    "explanation": "A concise explanation of the citation audit."
  },
  "source_faithfulness": {
    "score": "PASS" | "FAIL",
    "explanation": "A concise explanation of whether the generated answer misinterprets the source context."
  },
  "abstention_detection": {
    "score": "CORRECT_ABSTENTION" | "INCORRECT_ABSTENTION" | "CORRECT_ANSWER" | "INCORRECT_ANSWER" | "NOT_APPLICABLE",
    "explanation": "A concise explanation of the abstention analysis."
  }
}

## CONSTRAINTS
- Base your evaluation strictly on the provided inputs.
- Do not use outside knowledge.
- If the generated answer is empty or contains only an abstention phrase, evaluate it as an abstention.

To adapt this template, start by customizing the OUTPUT FORMAT schema to match your specific evaluation needs. You might add a severity field to unsupported_claims or a partial_credit_details object. The EVALUATION CRITERIA section can also be expanded with domain-specific rules, such as numerical tolerance checks for financial data. For high-stakes evaluations, always pair this prompt with a human review step, especially for FAIL or PARTIAL scores, to validate the model's judgment before it is used in a regression test suite or performance report.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Ground-Truth Answer Comparison Prompt for RAG. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before evaluation begins.

PlaceholderPurposeExampleValidation Notes

[MODEL_OUTPUT]

The RAG-generated answer to evaluate against the ground truth

The capital of France is Paris. SOURCE: doc_12

Must be non-empty string. Check for null or whitespace before sending. If output contains an abstention marker, route to abstention detection path first.

[GROUND_TRUTH_ANSWER]

The known-correct reference answer for comparison

Paris is the capital and largest city of France.

Must be non-empty string. Verify source provenance: is this a human-verified golden answer or an unvalidated reference? Flag if ground truth is stale or unconfirmed.

[RETRIEVED_SOURCES]

The source passages the RAG system used to generate its output

["doc_12: Paris has been the capital of France since...", "doc_7: France is a country in Western Europe..."]

Must be a JSON array of strings or structured objects with source IDs. Validate array is non-empty. Check that source IDs match the citation format used in [MODEL_OUTPUT].

[EVALUATION_DIMENSIONS]

The specific dimensions to score: correctness, citation_accuracy, faithfulness, completeness, abstention

["correctness", "citation_accuracy", "faithfulness"]

Must be a JSON array of strings drawn from the allowed set. Reject unknown dimension names. Default to all five if omitted. At least one dimension required.

[SCORING_THRESHOLD]

The minimum score required for a passing evaluation per dimension

0.8

Must be a float between 0.0 and 1.0. Validate range. If threshold is below 0.5, log a warning that the bar may be too low for production use. Use same threshold across dimensions or specify per-dimension map.

[ABSTENTION_PATTERNS]

Known phrases the RAG system uses to indicate it cannot answer

["I don't have enough information", "Unable to determine from sources"]

Must be a JSON array of strings. Case-insensitive matching recommended. If empty, abstention detection is skipped. Validate that patterns don't accidentally match legitimate answers.

[SOURCE_GROUNDING_REQUIRED]

Whether every claim in the model output must be traceable to a specific source passage

Must be boolean. When true, the evaluator will flag unsupported claims even if factually correct. Set false for evaluations where external knowledge is acceptable. Default true for RAG evaluation.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Ground-Truth Answer Comparison Prompt into a RAG evaluation pipeline with validation, retries, and human review gates.

This prompt is designed to operate as a programmatic evaluation step within a RAG system's CI/CD or regression testing pipeline, not as a one-off manual check. The implementation harness should treat the LLM call as a deterministic function: it receives a structured input containing the user question, the RAG-generated answer, and the ground-truth reference, and it must return a machine-readable comparison report. The primary integration point is immediately after a RAG pipeline produces an answer, where this prompt acts as an automated judge before the answer reaches an end user or a dataset curator. The harness must enforce a strict JSON output schema, as the comparison report's fields—such as answer_correctness, citation_accuracy, source_faithfulness, and abstention_detected—are consumed by downstream metric aggregators and release gates.

To wire this into an application, wrap the prompt call in a function that constructs the [USER_QUESTION], [RAG_ANSWER], and [GROUND_TRUTH_REFERENCE] placeholders from your test dataset. The model should be instructed to return a JSON object conforming to a predefined [OUTPUT_SCHEMA], which your harness must validate immediately. Implement a validation layer using a tool like Pydantic or JSON Schema that checks for the presence and correct types of all required fields. If validation fails, implement a retry strategy with a maximum of 2 additional attempts, feeding the validation error message back into the prompt's [CONSTRAINTS] or as a follow-up correction request. Log every raw response, validation result, and retry attempt to your observability platform (e.g., a comparison_eval log stream) for trace analysis. For high-stakes domains like healthcare or finance, route any comparison where answer_correctness is false or citation_accuracy falls below a configurable threshold (e.g., 0.9) to a human review queue, attaching the full comparison report and source artifacts.

Model choice matters for this harness. Use a model with strong instruction-following and JSON mode capabilities, such as GPT-4o, Claude 3.5 Sonnet, or a fine-tuned evaluator model. Set a low temperature (0.0–0.2) to maximize deterministic scoring. The harness should also implement a circuit breaker: if the retry loop exhausts all attempts or the model returns a refusal, mark the evaluation as indeterminate and escalate for manual review rather than silently passing or failing the RAG output. Finally, avoid the anti-pattern of using this prompt to evaluate every single production query in real-time; it is best suited for offline batch evaluation, regression test suites, and periodic sampling. For real-time guardrails, pair it with a lighter-weight, higher-recall groundedness check and reserve this detailed comparison for deep-dive analysis and release validation.

IMPLEMENTATION TABLE

Expected Output Contract

Define the exact fields, types, and validation rules your application should expect from the Ground-Truth Answer Comparison Prompt. Use this contract to build a parser and trigger retries or human review on failure.

Field or ElementType or FormatRequiredValidation Rule

overall_score

number (0.0 to 1.0)

Must be a float between 0.0 and 1.0 inclusive. Parse check: JSON number. If null or out of range, retry or fail.

answer_correctness

object

Must contain 'score' (number 0.0-1.0) and 'verdict' (enum: 'correct', 'partially_correct', 'incorrect'). Schema check: required keys present.

citation_accuracy

object

Must contain 'score' (number 0.0-1.0) and 'audit' (array of objects). Each audit object requires 'citation_id', 'verdict' (enum: 'supported', 'unsupported', 'contradicted'), and 'evidence_span' (string).

source_faithfulness

object

Must contain 'score' (number 0.0-1.0) and 'hallucinated_claims' (array of strings). If score is 1.0, hallucinated_claims must be an empty array.

abstention_detected

boolean

Must be true if the model output indicates it cannot answer. If true, overall_score must be null and a 'reason' string field must be present. Type check: boolean.

comparison_summary

string

A non-empty string explaining the key differences between the model output and the ground-truth reference. Null or empty string is a validation failure.

error_flags

array of strings

If present, must be an array of strings from a controlled vocabulary: ['missing_citation', 'contradicts_reference', 'extra_information', 'incomplete_answer', 'parse_error']. Unknown flags should trigger a warning log.

PRACTICAL GUARDRAILS

Common Failure Modes

When comparing RAG outputs against ground-truth answers, these failures surface first. Each card identifies a specific breakage pattern and the guardrail that catches it before it reaches production.

01

Surface-Level String Matching Misses Semantic Equivalence

What to watch: The judge rejects a correct answer because it uses different phrasing than the reference. Paraphrased answers, synonym substitutions, and reordered clauses get scored as incorrect even when semantically identical. Guardrail: Add a semantic similarity pre-check that distinguishes meaning-preserving rewrites from factual deviations. Use embedding-based similarity as a tiebreaker before running the full comparison prompt.

02

Citation Grounding Drift Under Retrieval Noise

What to watch: The model cites a source that exists in the retrieved context but doesn't actually support the claim. The comparison prompt flags the citation as valid because the source ID matches, missing that the evidence span is irrelevant or contradictory. Guardrail: Require span-level grounding verification. The prompt must extract the exact evidence span from the cited source and compare it to the claim, not just check that the source was retrieved.

03

Partial Credit Collapse on Multi-Fact Answers

What to watch: An answer containing three correct facts and one hallucinated fact receives a binary fail score. The evaluation loses signal on partially correct outputs, making it impossible to track incremental improvement. Guardrail: Decompose the reference answer into discrete checkable facts before comparison. Score each fact independently and report a coverage ratio rather than a single pass/fail judgment.

04

Abstention Misclassification as Wrong Answer

What to watch: The model correctly abstains when retrieved context lacks sufficient evidence, but the comparison prompt treats abstention as a failure because the reference answer exists. Safe behavior gets penalized, incentivizing hallucination. Guardrail: Add an abstention detection gate before the comparison step. When the model abstains, check whether the retrieved context actually contains the answer. Score correct abstention as a pass, not a failure.

05

Numerical Tolerance Blindness

What to watch: The model outputs 47.3% when the reference says 47%. The comparison prompt flags this as incorrect because it performs exact string matching on numbers, ignoring acceptable tolerance ranges. Guardrail: Define numerical tolerance thresholds per domain before evaluation. Extract numeric values, normalize units, and apply tolerance-aware comparison. Flag only deviations that exceed the pre-defined acceptable range.

06

Reference Contamination from Overlapping Retrieval

What to watch: The reference answer was derived from the same knowledge base used for retrieval. The comparison prompt confirms the model output matches the reference, but both may share the same source error. The evaluation passes while factual accuracy fails. Guardrail: Maintain a contamination audit trail. Tag each reference answer with its source provenance and check whether the model's retrieved context overlaps with the reference's source material. Flag high-overlap cases for human spot-checking.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Ground-Truth Answer Comparison Prompt before shipping. Each criterion defines a pass standard, a failure signal, and a concrete test method. Run these checks against a curated golden dataset of at least 20 RAG query–retrieved-context–reference-answer triples.

CriterionPass StandardFailure SignalTest Method

Answer Correctness Classification

Correct/Partially Correct/Incorrect label matches human judgment in ≥90% of cases

Model labels a factually wrong answer as Correct or a fully correct answer as Incorrect

Run prompt on 50 labeled pairs; compute agreement with human labels; flag cases where label differs

Citation Accuracy Audit

≥95% of citations marked Supported are verifiable in the source; 0 false Supported marks

Citation marked Supported but source text contradicts or does not contain the claim

Spot-check 30 citations across 10 outputs; verify each Supported citation against the original source span

Source Faithfulness Flag

Faithfulness flag matches groundedness ground truth in ≥90% of cases

Output marked Faithful but contains unsupported claims; or Unfaithful flag on fully grounded output

Compare faithfulness flag to manual groundedness annotation on 20 outputs; compute false-positive and false-negative rates

Abstention Detection

Abstention correctly detected in ≥95% of cases where model output is 'I don't know' or equivalent

Model output is an abstention but prompt classifies it as a substantive answer; or vice versa

Include 10 abstention examples in test set; verify abstention flag triggers; check no false abstention flags on real answers

Comparison Report Structure

Output contains all required fields: correctness_label, citation_audit[], faithfulness_flag, abstention_flag, summary

Missing one or more top-level fields; or fields present but with wrong types

Validate output against JSON schema; reject any response missing required keys or with type mismatches

Summary Justification Quality

Summary provides a specific, evidence-backed reason for the correctness label in ≥85% of cases

Summary is generic ('answer looks correct'), circular, or contradicts the correctness label

Review 20 summaries; check for specific reference to source evidence and logical alignment with the assigned label

Edge Case: Conflicting Sources

Prompt correctly flags conflict and does not mark answer as Incorrect solely due to source disagreement

Prompt marks answer Incorrect when one source supports it and another contradicts it, without noting the conflict

Include 5 cases with conflicting retrieved passages; verify conflict is noted and correctness label accounts for ambiguity

Latency and Token Budget

Prompt completes within 2x the latency of the underlying RAG answer generation; no runaway token usage

Prompt exceeds 3x generation latency or produces >500 tokens for a simple correct/incorrect case

Measure end-to-end latency on 20 calls; set a timeout; flag any response exceeding 1000 output tokens for a single evaluation

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base comparison prompt and a small golden dataset (10-20 QA pairs). Remove strict schema requirements initially—accept a paragraph summary of correctness, citation accuracy, and faithfulness instead of structured JSON. Use a single model call per comparison. Focus on whether the output directionally matches the ground truth before investing in field-level validation.

Watch for

  • The model producing vague agreement without citing specific deviations
  • Missing abstention detection when the RAG output says "I don't know"
  • Overly generous scoring that masks real failures
  • No baseline to compare against—run a few manual comparisons first to calibrate expectations
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.