Inferensys

Prompt

Retrieved Context vs Generated Output Diff Prompt

A practical prompt playbook for using Retrieved Context vs Generated Output Diff Prompt 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

Understand the job-to-be-done, the ideal user, and the boundaries of the Retrieved Context vs Generated Output Diff Prompt.

This prompt is designed for quality engineers and RAG developers who need to move beyond a binary 'hallucination' flag and into a detailed, actionable audit of answer faithfulness. The core job-to-be-done is to produce a structured, segment-level diff between a generated answer and the exact retrieved context that was provided to the model. You should use this when you have a production trace containing both the retrieved_context and the generated_output and you need a reviewable alignment report before shipping a model update, tuning a retrieval pipeline, or responding to a user-reported factual error. The output is not a pass/fail score; it is a forensic artifact that identifies added, omitted, distorted, and contradicted information, enabling precise root-cause analysis.

The ideal user is someone who already has access to a production trace and can extract the relevant text blocks. This prompt assumes the retrieved context is pre-extracted and formatted as a single input block. It does not perform retrieval itself, nor does it evaluate the quality of the retrieval pipeline. It is a targeted diagnostic tool for the generation step. For example, if a user reports that an answer misrepresented a contract clause, you would pull the trace, isolate the clause from the retrieved_context and the claim from the generated_output, and run this prompt to get a structured breakdown of exactly how the output diverged from the source material.

Do not use this prompt as a replacement for a full RAG pipeline evaluation or as a real-time guardrail. It is an offline analysis tool. It is not designed to catch every subtle form of bias or to judge the overall quality of the prose. Its strength is in creating a rigorous, evidence-based map of factual alignment and misalignment. After running this prompt, the next step is to use the structured diff to inform a specific action: fixing a prompt instruction, tuning a retrieval hyperparameter, adding a source to the knowledge base, or documenting a known model behavior. Avoid using the output to simply 'score' a model without acting on the specific segments it flags.

PRACTICAL GUARDRAILS

Use Case Fit

This prompt is a diagnostic tool for quality engineers, not a real-time guardrail. Understand where it adds value and where it introduces risk before wiring it into a production pipeline.

01

Good Fit: Offline Trace Forensics

Use when: debugging a specific production trace where a hallucination or faithfulness failure has already been flagged. Guardrail: Run this prompt in a debugging notebook or review queue, not in the hot path of user requests.

02

Good Fit: Pre-Release RAG Regression Testing

Use when: comparing a new retrieval pipeline, embedding model, or prompt version against a golden dataset of traces. Guardrail: Batch-process traces and aggregate faithfulness scores; never ship based on a single diff result.

03

Bad Fit: Real-Time Hallucination Blocking

Avoid when: you need to block a hallucinated response before it reaches the user. This prompt requires both the retrieved context and the generated output, so it can only run post-generation. Guardrail: Use lightweight claim extraction and NLI models for real-time checks; reserve this diff prompt for root-cause analysis.

04

Required Inputs: Complete Trace Context

What to watch: running this prompt without the full retrieved context, including dropped or truncated passages, produces misleading faithfulness scores. Guardrail: Ensure the trace includes all retrieved documents, their ranking scores, and any truncation metadata before invoking the diff.

05

Operational Risk: Large Context Window Costs

What to watch: long retrieved contexts plus long generated outputs can push token usage into expensive territory, especially when batching. Guardrail: Set a maximum combined token budget per trace; if exceeded, summarize or chunk the context before diffing, and log a warning that the diff may be incomplete.

06

Operational Risk: Model-Graded Faithfulness Drift

What to watch: the model grading faithfulness may share biases with the model that generated the output, causing self-consistency blind spots. Guardrail: Cross-validate a sample of diffs with a different model family or a human reviewer, and track inter-rater agreement over time.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A structured prompt that diffs retrieved context against a generated answer to identify added, omitted, distorted, or contradicted information.

This prompt template is designed to be pasted directly into your trace analysis harness. It instructs the model to perform a structured comparison between the retrieved context and the generated output from a single production trace, producing a faithful diff. The goal is to isolate where the model's answer deviated from the provided evidence, which is the core diagnostic signal for debugging hallucination and grounding failures in RAG systems.

text
You are a trace analysis auditor. Your task is to compare the RETRIEVED CONTEXT against the GENERATED OUTPUT from a single production trace and produce a structured diff.

## INPUTS

RETRIEVED CONTEXT:
[RETRIEVED_CONTEXT]

GENERATED OUTPUT:
[GENERATED_OUTPUT]

## OUTPUT SCHEMA

Return a valid JSON object with the following structure:
{
  "faithfulness_score": <float between 0.0 and 1.0, where 1.0 means the output is fully supported by the context>,
  "summary": "<one-sentence summary of the overall faithfulness>",
  "segments": [
    {
      "segment_id": "<unique identifier for this segment>",
      "generated_text": "<the exact text from the generated output being evaluated>",
      "alignment_status": "<FULLY_SUPPORTED | PARTIALLY_SUPPORTED | UNSUPPORTED | CONTRADICTED>",
      "supporting_context": "<the exact text from the retrieved context that supports or contradicts this segment, or null if none>",
      "issue_type": "<ADDED | OMITTED | DISTORTED | CONTRADICTED | NONE>",
      "explanation": "<brief explanation of the alignment or misalignment>"
    }
  ]
}

## CONSTRAINTS

- Compare the generated output against ONLY the provided retrieved context. Do not use external knowledge.
- If the generated output contains information not present in the context, mark it as ADDED.
- If the context contains important information missing from the output, add a segment with generated_text set to null and issue_type set to OMITTED.
- If the output distorts or misrepresents information from the context, mark it as DISTORTED.
- If the output directly contradicts the context, mark it as CONTRADICTED.
- Segment the generated output into atomic claims or sentences for granular analysis.
- The faithfulness_score should reflect the proportion of fully supported segments relative to total segments.

To adapt this template, replace [RETRIEVED_CONTEXT] with the raw text of the documents, passages, or chunks retrieved during the trace. Replace [GENERATED_OUTPUT] with the final answer the model produced. For high-risk domains such as healthcare or finance, always route the output of this prompt to a human reviewer before taking any action. You can also extend the output schema to include trace event IDs or document pointers if your observability platform captures them, enabling direct navigation from the diff back to the source trace.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Retrieved Context vs Generated Output Diff Prompt. Each variable must be populated from production trace data before the prompt is executed.

PlaceholderPurposeExampleValidation Notes

[GENERATED_OUTPUT]

The final answer produced by the model in the trace

The capital of France is Paris. It has a population of 2.1 million.

Must be a non-empty string. Validate that the output is the exact text from the trace, not a sanitized version.

[RETRIEVED_CONTEXT]

The full set of retrieved passages or documents provided to the model

[{"doc_id": "d1", "text": "Paris is the capital of France."}, {"doc_id": "d2", "text": "The population of Paris is 2.16 million."}]

Must be a valid JSON array of objects with at least doc_id and text fields. Null or empty array triggers an abstention path.

[TRACE_ID]

Unique identifier for the production trace being analyzed

trace_2025-03-15_14-22-07_a1b2c3

Must match the trace ID format used in your observability platform. Used for anchoring results to source data.

[USER_QUERY]

The original user question or prompt that triggered the generation

What is the capital of France and its population?

Must be a non-empty string. Used to assess whether omissions are justified by query scope.

[OUTPUT_SCHEMA]

The expected JSON structure for the diff output

{"faithfulness_score": float, "segments": [{"claim": str, "status": str, "evidence": str|null, "note": str}]}

Must be a valid JSON Schema or example object. Validate that downstream parsers can consume this exact shape.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for auto-accepting a faithfulness classification

0.85

Must be a float between 0.0 and 1.0. Claims below this threshold should be flagged for human review. Default 0.85 if not specified.

[MAX_SEGMENTS]

Upper limit on the number of claim segments to extract and compare

20

Must be a positive integer. Prevents runaway token consumption on long outputs. If the generated output contains more claims, truncate with a note.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Retrieved Context vs Generated Output Diff Prompt into a production observability pipeline with validation, retries, and trace integration.

This prompt is designed to run as a post-hoc analysis step within an observability or evaluation pipeline, not as a real-time user-facing feature. It expects a fully hydrated trace record containing both the retrieved context and the generated output, typically sourced from a tracing platform like LangSmith, Arize, or a custom trace store. The primary integration point is a batch or streaming job that pulls traces flagged for hallucination review—either by automated evals, user reports, or sampling rules—and enriches them with a structured diff and faithfulness score before routing to a human review queue or a dashboard.

Wire the prompt into an application by first constructing a trace retrieval function that fetches the required fields: [RETRIEVED_CONTEXT] (the full list of retrieved documents or passages with metadata), [GENERATED_OUTPUT] (the final model response), and optionally [USER_QUERY] for additional context. Validate these inputs before calling the model—reject traces where the retrieved context is empty, the generated output is truncated, or the trace event IDs are missing. On model response, parse the JSON output and validate that the faithfulness_score is a float between 0 and 1, that each segment in the diff has a non-empty type field matching the allowed enum (added, omitted, distorted, contradicted, faithful), and that trace_event_references contain valid span IDs from the original trace. If validation fails, retry once with the error message appended to the prompt as a [PREVIOUS_ERROR] constraint. For high-stakes domains like healthcare or finance, route all diffs with a faithfulness score below 0.9 or any contradicted segment to a human review queue before the finding is considered confirmed.

Model choice matters here: use a model with strong instruction-following and structured output capabilities, such as GPT-4o, Claude 3.5 Sonnet, or Gemini 2.0 Flash, and set temperature=0 to minimize variance in the faithfulness score. Log every diff output alongside the original trace ID, model version, and prompt version to enable longitudinal tracking of hallucination rates. Avoid running this prompt on traces where the retrieved context exceeds the model's context window—chunk the context or use a summarization pre-processing step instead. The diff output should be treated as a diagnostic signal, not a final verdict; always correlate it with user feedback and downstream eval results before triggering automated rollbacks or model switches.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured diff output fields, their types, and validation rules for the Retrieved Context vs Generated Output Diff Prompt. Use this contract to parse, validate, and store the model's response before surfacing it in a debugging dashboard or alerting system.

Field or ElementType or FormatRequiredValidation Rule

faithfulness_score

number (0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive. Reject if non-numeric or out of range.

overall_assessment

string

Must be one of: 'faithful', 'mostly_faithful', 'mixed', 'mostly_unfaithful', 'unfaithful'. Reject if not in enum.

diff_segments

array of objects

Must be a non-empty array. Each object must conform to the diff_segment schema. Reject if empty or not an array.

diff_segments[].segment_id

string

Must be a unique string within the diff_segments array. Reject on duplicate or missing values.

diff_segments[].generated_text

string

The exact text span from the generated output being evaluated. Must not be empty.

diff_segments[].retrieved_context_match

string or null

Must be a string containing the matching source text, or null if no match exists. Reject if missing key.

diff_segments[].alignment_status

string

Must be one of: 'supported', 'contradicted', 'omitted', 'added', 'distorted'. Reject if not in enum.

diff_segments[].confidence

number (0.0-1.0)

Must be a float between 0.0 and 1.0. If below 0.5, flag for human review.

PRACTICAL GUARDRAILS

Common Failure Modes

When comparing retrieved context against generated output, these failure modes surface first. Each card identifies a specific breakage pattern and the guardrail that catches it before it reaches users.

01

Silent Fabrication Without Source Anchors

What to watch: The model generates plausible-sounding claims that have no corresponding passage in the retrieved context. These fabrications often appear in confident, fluent prose and pass casual review. Guardrail: Require the diff prompt to output a per-claim source_span_id or null. Any claim with a null anchor must be flagged for human review or automatically stripped before the answer reaches the user.

02

Distortion Through Paraphrase Drift

What to watch: The output rephrases retrieved content but shifts meaning—changing a 'may reduce risk' to 'eliminates risk' or a correlation into causation. The diff looks like a match but the semantics diverge. Guardrail: Add a semantic_alignment field to the diff schema that scores each segment on a 1-5 scale. Segments scoring below 3 require explicit reviewer attention, even if a source passage is cited.

03

Context Window Truncation Masking Gaps

What to watch: Retrieved documents were truncated to fit the context window, and the missing sections contained critical evidence. The diff shows 'no contradiction' because the evidence was never seen. Guardrail: Include truncation_warnings in the trace metadata and instruct the diff prompt to note when a claim's topic area falls within a truncated region. Flag these outputs for retrieval pipeline review, not just generation review.

04

Source Conflict Smoothing

What to watch: Two retrieved sources disagree, but the generated output presents a single, harmonized answer that hides the conflict. The diff prompt may mark both as 'used' without noting the contradiction. Guardrail: Add a source_conflict_detected boolean and a conflict_summary field to the diff output. When true, the system should surface the disagreement to the user rather than silently resolving it.

05

Omission of High-Stakes Details

What to watch: The output faithfully includes most retrieved information but drops a critical qualifier—a dosage limit, a legal exception, a version constraint. The diff shows high coverage but misses the one detail that matters most. Guardrail: Weight omission severity by domain. For regulated or safety-critical domains, require a critical_omission_check pass that compares output against a pre-defined list of required fact types extracted from the retrieved context.

06

Diff Prompt Itself Hallucinating Alignment

What to watch: The diff prompt confidently reports that a claim is supported when the cited passage says something different. The evaluation tool becomes the source of error. Guardrail: Run a periodic calibration check where human-annotated diff examples are compared against the diff prompt's output. Track precision and recall of the diff prompt's own grounding judgments and trigger a review if calibration drifts beyond threshold.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the structured diff output before integrating it into an automated pipeline or review workflow. Each criterion targets a specific failure mode of the Retrieved Context vs Generated Output Diff Prompt.

CriterionPass StandardFailure SignalTest Method

Faithfulness Score Calibration

Score is an integer 1-5 and correlates with the number and severity of alignment notes

Score is 5 but notes describe contradictions; score is 1 but notes are empty

Parse score field; assert score is integer between 1 and 5; manually spot-check 10 traces for score-to-note correlation

Segment Alignment Completeness

Every generated segment is classified as aligned, omitted, added, distorted, or contradicted

A generated sentence appears in the output but has no corresponding segment entry in the diff

Split generated output into sentences; assert each sentence text appears in exactly one segment label

Source Evidence Anchoring

Every aligned, distorted, or contradicted segment references a specific [RETRIEVED_CONTEXT] span or chunk ID

Segment is marked aligned but source_span is null or contains a fabricated quote not in [RETRIEVED_CONTEXT]

For each segment with label aligned, distorted, or contradicted, assert source_span text is a substring of [RETRIEVED_CONTEXT]

Omission Detection Recall

All information in [RETRIEVED_CONTEXT] that is relevant to [USER_QUERY] but missing from [GENERATED_OUTPUT] is listed as omitted

A key fact from the retrieved context is absent from the generated output but not flagged in the omitted list

Manually annotate 5 traces for expected omissions; assert recall >= 0.90 against human annotations

Contradiction Flagging Precision

Contradicted segments are true logical contradictions, not stylistic differences or inferred implications

Segment is flagged as contradicted but the source and generated text are semantically equivalent

For each contradicted segment, assert semantic entailment check fails; manually review flagged contradictions for false positives

Added Information Classification

Added segments are genuinely absent from [RETRIEVED_CONTEXT], not paraphrases of retrieved content

Segment is flagged as added but contains a close paraphrase of a retrieved passage

Compute cosine similarity between added segment and all [RETRIEVED_CONTEXT] chunks; assert similarity < 0.85 threshold; manually review borderline cases

Output Schema Validity

Diff output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present

Output is missing the segments array; faithfulness_score is a float instead of integer; extra untyped fields appear

Validate output against [OUTPUT_SCHEMA] using JSON Schema validator; assert no schema violations

Abstention Appropriateness

When [RETRIEVED_CONTEXT] is empty or irrelevant, output indicates insufficient context rather than hallucinating a diff

Empty or irrelevant context produces a diff with fabricated aligned segments and a high faithfulness score

Inject 5 traces with empty [RETRIEVED_CONTEXT]; assert faithfulness_score <= 2 and segments array is empty or contains only added entries

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single [RETRIEVED_CONTEXT] and [GENERATED_OUTPUT] pair. Drop the per-segment alignment notes and faithfulness score to start. Focus on getting a clean diff of additions, omissions, and contradictions.

code
Compare the retrieved context and generated output below. List:
- Information in the output NOT in the context (ADDED)
- Information in the context NOT in the output (OMITTED)
- Information where the output contradicts the context (DISTORTED)

Context: [RETRIEVED_CONTEXT]
Output: [GENERATED_OUTPUT]

Watch for

  • The model treating stylistic rephrasing as distortion
  • Over-flagging minor omissions that don't affect correctness
  • No severity weighting on flagged items
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.