Inferensys

Prompt

Contradiction Detection Harness Prompt for RAG Pipelines

A practical prompt playbook for using Contradiction Detection Harness Prompt for RAG Pipelines 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

Identify the exact integration point in a RAG pipeline where a structured contradiction check prevents conflicting answers from reaching the user.

This prompt is designed for RAG system builders who need to add a post-retrieval contradiction check before generating an answer. When a user query triggers retrieval of multiple passages, those passages may contain conflicting facts, figures, or interpretations. This prompt acts as a harness: it takes a set of retrieved passages with their citation metadata and produces a structured contradiction signal. The signal can then be used to suppress an answer, qualify it with a warning, or route the query for human review. Use this when you need a machine-readable contradiction verdict integrated directly into your RAG pipeline, not a human-readable explanation. It assumes you already have a retrieval step producing passages with source identifiers.

Do not use this prompt for open-ended document comparison, single-document proofreading, or claim extraction without retrieval context. It is not a general fact-checking tool—it expects a specific input shape: a user query paired with multiple retrieved passages, each carrying a unique source ID. The output is a structured JSON verdict, not prose. If your goal is to explain contradictions to an end user, pair this prompt with a downstream summarization step. If your latency budget is under 200ms, consider batching smaller passage sets or using a lighter classification model for the contradiction check before invoking this more thorough analysis.

Before deploying, validate that your retrieval step returns passages with stable, unique identifiers. The prompt's utility depends entirely on traceable provenance—without source IDs, you cannot act on the contradiction signal. Start by wiring this prompt after retrieval and before answer generation, then add an eval suite that measures both contradiction detection recall and false-positive rates on known-consistent passage sets. Avoid using this prompt on single-source retrievals; the contradiction check is meaningless without at least two distinct sources to compare.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Contradiction Detection Harness fits into a RAG pipeline and where it introduces more risk than it resolves.

01

Good Fit: Post-Retrieval Quality Gate

Use when: you have multiple retrieved passages and need to suppress or qualify an answer when sources directly conflict. Guardrail: run the harness after retrieval but before answer generation so the contradiction signal can block or modify the final prompt.

02

Bad Fit: Single-Source Summarization

Avoid when: only one source document is available. Pairwise contradiction detection requires at least two evidence passages. Guardrail: route single-source requests to a standard RAG answer prompt and skip the harness to avoid false-positive 'conflicts' from paraphrasing.

03

Required Inputs

What you need: at least two retrieved passages with citation metadata, a claim or proposed answer to verify, and a latency budget. Guardrail: if citation metadata is missing, the harness cannot produce traceable contradiction signals. Validate inputs before invoking.

04

Operational Risk: Latency Amplification

What to watch: pairwise comparison across many passages multiplies inference calls and can blow latency budgets. Guardrail: set a maximum passage-pair limit, batch comparisons where possible, and use a fast classifier model for the harness if the primary model is large.

05

Operational Risk: False Positives from Paraphrasing

What to watch: semantically equivalent statements phrased differently can be flagged as contradictions. Guardrail: include a paraphrasing check step in the harness and calibrate the contradiction threshold using a labeled dev set before production deployment.

06

Escalation Path: Unresolvable Conflicts

What to watch: some contradictions cannot be resolved automatically and should not be silently dropped. Guardrail: define an escalation threshold where high-severity, unresolvable conflicts trigger human review or answer suppression with an explicit 'sources disagree' message.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for detecting contradictions across retrieved passages, designed to be inserted into your RAG pipeline after retrieval and before answer generation.

This prompt template is the core instruction set for a post-retrieval contradiction detection harness. It is designed to be invoked after your retrieval system has returned a set of candidate passages for a user query. The prompt forces the model to perform pairwise comparison of the provided passages, identify direct contradictions, and output a structured signal that your application can use to suppress, qualify, or flag the final generated answer. The primary job is not to answer the user query, but to audit the evidence for internal consistency. Use this when the cost of presenting conflicting information to a user is high, such as in financial analysis, medical summarization, or legal research.

text
You are an evidence auditor. Your task is to analyze a set of retrieved text passages for direct factual contradictions. Do not answer the user's original question. Focus only on whether the provided passages conflict with each other on specific, verifiable facts.

## INPUT
User Query: [USER_QUERY]
Retrieved Passages:
[RETRIEVED_PASSAGES]

## TASK
For every pair of passages, determine if they contain a direct contradiction. A direct contradiction exists only if two passages assert mutually exclusive facts about the same specific entity, event, number, date, or claim. Do not flag differences in phrasing, scope, or opinion as contradictions.

## CONSTRAINTS
- Ignore contradictions that are irrelevant to the user query.
- If a contradiction is found, you must cite the exact text from both passages that creates the conflict.
- If no contradictions are found, explicitly state "NO_CONTRADICTIONS_DETECTED".
- Do not hallucinate conflicts. If you are unsure, classify as "NO_CONTRADICTIONS_DETECTED".

## OUTPUT_SCHEMA
Respond with a valid JSON object conforming to this schema:
{
  "contradictions": [
    {
      "passage_ids": ["id_1", "id_2"],
      "conflict_type": "direct_contradiction",
      "conflicting_claim_1": "Exact excerpt from passage 1",
      "conflicting_claim_2": "Exact excerpt from passage 2",
      "explanation": "Brief explanation of why these are mutually exclusive."
    }
  ],
  "status": "CONTRADICTIONS_FOUND" | "NO_CONTRADICTIONS_DETECTED"
}

To adapt this template, you must format your retrieved passages into the [RETRIEVED_PASSAGES] placeholder as a string that clearly separates each passage with a unique identifier. A robust pattern is to prepend each passage with [ID: chunk_01] before injecting it. The [USER_QUERY] placeholder should contain the original user question to provide relevance context, preventing the model from flagging trivial or off-topic disagreements. For high-stakes domains, add a [RISK_LEVEL] placeholder and adjust the instructions to require higher confidence thresholds or to route CONTRADICTIONS_FOUND outputs directly to a human review queue. The output schema is intentionally flat to make parsing reliable; your application harness should validate that the JSON is well-formed and that the status field is present before proceeding to answer generation.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Contradiction Detection Harness Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to programmatically check the input before execution.

PlaceholderPurposeExampleValidation Notes

[CLAIM_A]

The primary claim to verify, extracted from the generated RAG answer.

The Acme 3000 processor was released in Q3 2024.

Must be a non-empty string. Check that the claim is atomic and contains a single verifiable assertion. Reject if length > 2000 characters.

[CLAIM_B]

The secondary claim to compare against, extracted from a different source or passage.

Acme Corp's flagship chip launched in September 2024.

Must be a non-empty string. Ensure [CLAIM_A] and [CLAIM_B] are not identical strings. Reject if both originate from the same source document ID.

[SOURCE_A_CITATION]

The citation metadata for the passage supporting or containing [CLAIM_A].

doc_id: 'acme_2024_10k.pdf', page: 42, chunk: 3

Must be a valid JSON object with at least a 'doc_id' field. Validate JSON parseability. The doc_id must match a record in the retrieval log.

[SOURCE_B_CITATION]

The citation metadata for the passage supporting or containing [CLAIM_B].

doc_id: 'techreport_q3.pdf', page: 15, chunk: 1

Must be a valid JSON object with at least a 'doc_id' field. Validate JSON parseability. The doc_id must differ from [SOURCE_A_CITATION].

[EVIDENCE_SNIPPET_A]

The verbatim text from the source that grounds [CLAIM_A].

The Acme 3000 processor began shipping to partners in late September 2024.

Must be a non-empty string. Check that [EVIDENCE_SNIPPET_A] is a substring of the retrieved passage for [SOURCE_A_CITATION] to prevent hallucinated evidence.

[EVIDENCE_SNIPPET_B]

The verbatim text from the source that grounds [CLAIM_B].

Acme Corp announced the 3000 processor availability for Q4 2024.

Must be a non-empty string. Check that [EVIDENCE_SNIPPET_B] is a substring of the retrieved passage for [SOURCE_B_CITATION] to prevent hallucinated evidence.

[CONTRADICTION_THRESHOLD]

A float between 0.0 and 1.0 that sets the minimum confidence score for flagging a contradiction.

0.75

Must be a float. Validate range: 0.0 <= value <= 1.0. If null, default to 0.7. Values below 0.5 generate a warning for high false-positive risk.

[OUTPUT_SCHEMA]

The strict JSON schema the model must use for its contradiction verdict.

{ 'verdict': 'contradiction' | 'no_contradiction', 'confidence': float, 'explanation': string }

Must be a valid JSON Schema object. Validate with a schema validator before prompt assembly. Reject if the schema is missing the required 'verdict' field.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the contradiction detection prompt into a RAG pipeline with validation, retries, and latency-aware batching.

Integrating the contradiction detection prompt into a production RAG pipeline requires treating it as a post-retrieval verification step, not a standalone classifier. The prompt should receive a batch of retrieved passage pairs—each pair consisting of a claim-bearing passage and a potentially conflicting passage—along with their citation metadata. The application layer is responsible for constructing these pairs before calling the model, typically by grouping retrieved chunks by the claim they are meant to support or refute. The model returns structured contradiction verdicts, which the harness then validates against an expected output schema before the results influence downstream answer generation, suppression, or qualification logic.

The implementation harness must enforce a strict output contract. Define a JSON schema that includes fields for claim_id, conflicting_passage_id, contradiction_type (e.g., direct_contradiction, partial_mismatch, temporal_inconsistency, numerical_disagreement, compatible), confidence_score (0.0–1.0), explanation, and evidence_excerpts from both passages. After each model call, validate the response against this schema. If validation fails, implement a retry loop with a maximum of two additional attempts, appending the validation error message to the prompt context. Log every validation failure and retry for observability. For high-stakes domains such as healthcare or legal review, route any contradiction with a confidence score between 0.4 and 0.7 to a human review queue, and suppress or flag the affected answer segment rather than presenting it as resolved.

Latency and cost are critical when adding contradiction checks to a RAG pipeline. Batch multiple passage pairs into a single prompt call where possible, but cap the batch size based on your latency budget—start with 5–10 pairs per call and measure end-to-end latency. Use a faster model (e.g., GPT-4o-mini, Claude Haiku) for initial contradiction screening, and escalate ambiguous pairs to a more capable model only when the confidence score falls in the uncertain range. Cache contradiction verdicts for identical passage pairs to avoid redundant computation. Finally, instrument the harness with metrics: contradiction detection rate, validation failure rate, retry count, human escalation rate, and p95 latency per batch. These metrics will tell you whether the contradiction check is adding value or just adding noise to your pipeline.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON output for the contradiction detection harness. Use this contract to validate model responses before passing signals to downstream RAG suppression or qualification logic.

Field or ElementType or FormatRequiredValidation Rule

contradiction_detected

boolean

Must be true if any conflict pair exists; false only if all passages are consistent.

conflict_pairs

array of objects

Must be present and non-empty if contradiction_detected is true; otherwise empty array.

conflict_pairs[].claim_a

string

Exact excerpt from passage_a; must be a substring matchable in the source.

conflict_pairs[].claim_b

string

Exact excerpt from passage_b; must be a substring matchable in the source.

conflict_pairs[].conflict_type

enum: direct_contradiction | partial_mismatch | temporal_inconsistency | numerical_disagreement

Must match one of the allowed enum values; no free-text types.

conflict_pairs[].confidence

number (0.0-1.0)

Must be a float between 0 and 1; values below [CONFIDENCE_THRESHOLD] should be filtered post-response.

conflict_pairs[].explanation

string

Must contain a concise rationale grounded in the provided passages; null or empty string triggers a retry.

conflict_pairs[].citation_a

object

Must include source_id and passage_index for passage_a; source_id must match a provided source identifier.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when running contradiction detection in RAG pipelines and how to guard against it.

01

Paraphrase Flagged as Contradiction

What to watch: The model classifies semantically equivalent statements as contradictory because they use different words, sentence structures, or levels of specificity. This is the most common false positive in production. Guardrail: Add a pre-check instruction requiring the model to first restate both claims in a canonical form before comparing. Include few-shot examples of paraphrases that should be labeled 'compatible'.

02

Scope Mismatch Misclassified as Conflict

What to watch: One passage makes a broad claim while another makes a narrow claim about a subset. The model treats the unqualified broad statement as contradicting the qualified narrow one. Guardrail: Instruct the model to extract explicit quantifiers, time windows, and population scopes before comparison. Add a 'partial mismatch' label for scope differences and require scope alignment justification in the output.

03

Temporal Context Ignored

What to watch: Two passages describe the same entity at different points in time, and the model flags the change as a contradiction rather than a legitimate update or evolution. Guardrail: Require the model to extract and compare timestamps, effective dates, or version metadata before rendering a contradiction verdict. Add a 'temporal sequence valid' escape clause when dates explain the difference.

04

Citation Drift Under Load

What to watch: When processing many claim pairs in batch, the model mixes up which evidence belongs to which claim, producing contradiction signals with wrong source attributions. Guardrail: Keep claim-evidence pairs in a single structured prompt turn rather than spreading across conversation history. Validate that every output citation ID matches an input source ID. Add a post-processing schema check that rejects outputs with orphan citations.

05

Over-Confident Contradiction on Low-Information Passages

What to watch: The model issues a high-confidence contradiction verdict when one or both passages lack sufficient detail to determine whether a real conflict exists. Guardrail: Add an explicit 'insufficient information' output option and require the model to state what missing information would resolve the ambiguity. Set a minimum information threshold: if either passage is under N tokens or lacks a verifiable predicate, route to human review.

06

Latency Budget Exceeded in Batch Mode

What to watch: Pairwise comparison of many passages causes end-to-end latency to exceed the RAG pipeline budget, especially when contradiction checks run synchronously before answer generation. Guardrail: Implement a two-stage architecture: fast heuristic pre-filter (keyword overlap, entity match) to select candidate pairs, then run the full prompt only on high-risk pairs. Set a hard timeout with a 'defer to human' fallback rather than skipping the check silently.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the contradiction detection harness output before integrating it into a production RAG pipeline. Each criterion targets a specific failure mode common in post-retrieval contradiction checks.

CriterionPass StandardFailure SignalTest Method

Contradiction Signal Accuracy

All flagged contradictions are genuine factual conflicts, not paraphrases or differences in scope.

False positive rate exceeds 10% on a golden set of 50 known-clean passage pairs.

Run the harness on a labeled dataset containing both contradictory and non-contradictory passage pairs. Calculate precision and compare against the threshold.

Citation Provenance Integrity

Every contradiction signal includes a valid [CITATION] that maps directly to the conflicting text spans in the source passages.

A citation is missing, hallucinated (points to a non-existent section), or does not contain the conflicting claim.

Parse the output JSON. For each contradiction, verify the cited text exists verbatim in the specified source passage using an automated string match or substring check.

Latency Budget Compliance

The end-to-end contradiction check completes within the defined [LATENCY_BUDGET_MS] for the batch size.

Processing time exceeds the budget by more than 20% in three consecutive test runs.

Instrument the harness call with a timer. Run with a representative batch of [MAX_PASSAGES] and measure the 95th percentile latency over 20 trials.

Output Schema Validity

The output is valid JSON that strictly conforms to the [OUTPUT_SCHEMA], with all required fields present and correctly typed.

JSON parsing fails, a required field like contradiction_detected is missing, or a field has an incorrect type (e.g., string instead of boolean).

Validate the raw string output against the [OUTPUT_SCHEMA] using a JSON schema validator. The check must pass with zero errors.

Conflict Severity Calibration

The severity score in the output correctly reflects the material impact of the contradiction, matching a predefined rubric.

A trivial wording difference is scored as 'critical', or a direct factual negation is scored as 'minor'.

Use an LLM-as-a-Judge with the severity rubric to evaluate a sample of 20 outputs. Measure the correlation (e.g., Cohen's Kappa) between the harness's score and the judge's score; it must be above 0.7.

Abstention on Ambiguity

The harness returns contradiction_detected: false with a low confidence score when the relationship between passages is genuinely unclear.

The harness confidently flags a contradiction or confidently reports no contradiction for a pair of passages that are semantically ambiguous.

Include 10 ambiguous passage pairs in the test set where human annotators could not reach a consensus. The harness must not return a high-confidence verdict for these cases.

Batch Processing Completeness

The output contains a contradiction analysis for every passage pair in the input batch, with no skipped or dropped comparisons.

The number of results in the output array is less than the number of input pairs, or an error object is returned for a valid input.

Send a batch of exactly [BATCH_SIZE] passage pairs. Assert that the output array length equals [BATCH_SIZE] and that every entry has a valid pair_id matching the input.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single model call and minimal output validation. Focus on getting contradiction signals flowing before adding infrastructure. Replace [LATENCY_BUDGET_MS] with a generous timeout (e.g., 10000) and [BATCH_SIZE] with 1. Skip the batching loop and process one passage pair at a time. Log raw outputs to a JSONL file for later eval.

Prompt snippet

code
You are a contradiction detector. Compare the two passages below and return a JSON object with fields: contradiction_detected (boolean), conflict_type (string: direct|partial|temporal|numerical|none), explanation (string), confidence (float 0-1).

Passage A: [PASSAGE_A]
Passage B: [PASSAGE_B]

Watch for

  • Missing schema checks causing downstream parse failures
  • Overly broad instructions producing verbose explanations instead of structured signals
  • No latency tracking, making it hard to know if the prompt fits your RAG budget
  • False positives from paraphrasing treated as contradictions
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.