This prompt is a post-generation guardrail designed for operators and QA engineers who need to detect semantic drift in Retrieval-Augmented Generation (RAG) pipelines. Unlike simple keyword-overlap checks, this prompt compares the generated answer to its source documents to catch subtle hallucinations—fabricated statistics, invented causal relationships, unauthorized tone shifts, or concepts entirely absent from the evidence. The primary job-to-be-done is automated quality monitoring: you run this prompt on a sample of production answers to detect when your system is 'making things up' in ways that evade string-matching heuristics. The ideal user is an MLOps engineer, a QA lead, or a product engineer responsible for maintaining factual accuracy before answers reach end users.
Prompt
Source-Answer Divergence Detection Prompt

When to Use This Prompt
Identifies the operational context, ideal user, and failure modes where source-answer divergence detection is the correct guardrail, and when it is not.
Use this prompt when you need a high-recall detector for semantic divergence. It excels at catching cases where the model introduces plausible-sounding but unsupported details—for example, claiming a product has a '30-day money-back guarantee' when the source only mentions a 'return policy,' or attributing a causal relationship ('the outage was caused by a database failure') when the evidence only notes a temporal correlation. The prompt is also effective for detecting unauthorized tone shifts, such as a marketing-style superlative ('best-in-class') injected into an answer sourced from neutral technical documentation. Do not use this prompt as a replacement for answer-grounding prompts during generation; it is a detection tool, not a prevention mechanism. It is also not suitable for real-time blocking of every response due to latency and cost—reserve it for offline batch auditing, pre-release gating, or sampling-based production monitoring.
Before implementing this prompt, ensure you have a reliable mechanism for passing both the generated answer and the full set of source documents as context. The prompt's effectiveness depends on the completeness of the evidence provided. If your retrieval pipeline already drops relevant documents, the divergence detector will flag legitimate synthesis as hallucination. Pair this prompt with an evidence sufficiency gate to verify that the context is adequate before running divergence detection. For high-stakes deployments, route flagged outputs to a human review queue rather than auto-blocking, as the model may occasionally mark faithful paraphrasing as divergence. The next section provides the copy-ready prompt template you can adapt to your specific divergence taxonomy and severity thresholds.
Use Case Fit
Where the Source-Answer Divergence Detection Prompt works, where it fails, and what you must provide before deploying it as a production guardrail.
Strong Fit: Semantic Drift Monitoring
Use when: You need to catch subtle hallucinations where the answer sounds plausible but introduces concepts, tone, or details absent from the source. Guardrail: Deploy this prompt as a post-generation check in your RAG pipeline, comparing the final answer against the retrieved chunks before the user sees it.
Strong Fit: Pre-Release Quality Gate
Use when: You are building a release gate that blocks answers until they pass a divergence check. Guardrail: Combine this prompt with a structured output schema (pass/fail + divergence summary) so your application code can programmatically block or flag the response.
Bad Fit: Keyword-Only Verification
Avoid when: Your existing checks already catch exact-match fabrications. This prompt targets semantic divergence, not simple keyword mismatches. Guardrail: Use cheaper, deterministic methods (e.g., string matching, N-gram overlap) for surface-level checks and reserve this LLM-based prompt for deep semantic drift.
Bad Fit: Real-Time Streaming Answers
Avoid when: You need to check answers token-by-token as they stream to the user. This prompt requires the complete answer and source context. Guardrail: Buffer the full response, run the divergence check server-side, and only then release the verified answer or a fallback message.
Required Inputs: Answer + Source Pairs
What to watch: Running divergence detection without providing the exact source passages used for generation. Guardrail: Always pass the specific retrieved chunks (not just document IDs or summaries) alongside the generated answer. The prompt needs the precise evidence to compare against.
Operational Risk: Second-Model Latency
What to watch: Adding an LLM-based divergence check doubles your inference latency and cost per user query. Guardrail: Gate this prompt behind a confidence threshold. Only invoke divergence detection when the primary generation model's own confidence score is below a defined level, or sample a percentage of traffic for drift monitoring.
Copy-Ready Prompt Template
A copy-ready prompt for detecting semantic divergence between a generated answer and its source documents.
This prompt template is designed to be pasted directly into your evaluation harness or LLM orchestration layer. It instructs the model to act as a divergence auditor, comparing a generated answer against its source documents to identify concepts, tone, or details present in the answer but absent from the evidence. The output is a structured JSON report suitable for automated gating, logging, or triggering a human review queue. Replace every square-bracket placeholder with your actual data before execution.
textYou are a semantic divergence auditor for a RAG system. Your task is to compare a generated answer against its source documents and detect any divergence where the answer introduces concepts, tone, details, or implications absent from the provided evidence. ## INPUTS **Generated Answer:** [ANSWER] **Source Documents (with IDs):** [SOURCES] ## TASK 1. Decompose the generated answer into discrete claims. 2. For each claim, search the source documents for supporting evidence. 3. Flag any claim that introduces information not present in the sources. 4. Assess overall semantic divergence, including tone shifts, unsupported inferences, and fabricated details. ## OUTPUT SCHEMA Return a JSON object with this exact structure: { "divergence_detected": boolean, "divergence_severity": "none" | "minor" | "moderate" | "critical", "divergent_claims": [ { "claim_text": string, "claim_span": [start_char_index, end_char_index], "divergence_type": "unsupported_concept" | "fabricated_detail" | "tone_shift" | "unsupported_inference", "explanation": string, "nearest_source_id": string | null } ], "overall_assessment": string } ## CONSTRAINTS - Only flag divergence where the answer clearly goes beyond the sources. - Legitimate paraphrasing is NOT divergence. - If the answer stays faithful to the sources, divergence_detected must be false and divergent_claims must be an empty array. - Base every divergence flag on specific evidence gaps, not vague impressions.
After pasting this template, replace [ANSWER] with the full text of the generated answer and [SOURCES] with a structured list of source documents, each including a unique ID and the full passage text. For high-stakes deployments, route any output with divergence_severity of "moderate" or "critical" to a human review queue before the answer reaches end users. Log every divergence report alongside the prompt version, model, and timestamp to support drift analysis over time.
Prompt Variables
Required inputs for the Source-Answer Divergence Detection Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to confirm the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[GENERATED_ANSWER] | The full text of the answer produced by the RAG system that needs to be checked for divergence from its sources. | The new policy reduces latency by 40% and improves customer satisfaction scores. | Non-empty string. Must be the complete answer, not a truncated snippet. Null or empty input should abort the check. |
[SOURCE_DOCUMENTS] | The retrieved context passages that were provided to the generation step. These are the ground truth against which divergence is measured. | DOC-1: The policy update reduces average response time from 200ms to 120ms. DOC-2: Early user feedback indicates positive reception. | Array of strings or concatenated text with document IDs. Each source must have a unique identifier. Empty array should trigger an evidence-sufficiency gate before divergence detection. |
[DIVERGENCE_CATEGORIES] | The specific types of semantic divergence to detect, such as unsupported claims, tone shift, concept introduction, or detail fabrication. | ["unsupported_claim", "tone_shift", "concept_introduction", "detail_fabrication"] | Must be a defined list from a controlled vocabulary. Unknown categories should be rejected before prompt assembly. At least one category required. |
[OUTPUT_SCHEMA] | The structured format the model must use to report divergence findings, including fields for the divergent span, source evidence, category, and severity. | {"divergences": [{"span": "...", "category": "...", "source_evidence": "...", "severity": "..."}]} | Valid JSON Schema or TypeScript interface. Must include required fields: span, category, severity. Schema should be validated against model output in post-processing. |
[SEVERITY_THRESHOLD] | The minimum severity level at which a divergence should be flagged for human review or automated blocking. | medium | Must be one of a predefined set: low, medium, high, critical. Values outside this set should default to medium with a warning log entry. |
[DOCUMENT_METADATA] | Optional metadata for each source document, such as publication date, author, or credibility score, used to weight divergence severity. | {"DOC-1": {"date": "2025-01-15", "credibility": 0.92}} | If provided, must be a valid JSON object keyed by document ID. Missing metadata for a cited source should not break execution but should be logged. Null allowed if metadata weighting is disabled. |
[MAX_DIVERGENCES] | The maximum number of divergence findings to return before truncation, preventing unbounded output on long answers. | 5 | Positive integer. Values above 20 should be capped with a warning. A value of 0 should be treated as a configuration error and rejected. |
Implementation Harness Notes
How to wire the Source-Answer Divergence Detection Prompt into a production RAG monitoring pipeline with validation, retries, and logging.
This prompt is designed to operate as a post-generation guardrail, sitting between the answer synthesis step and the user delivery step. It is not a real-time user-facing prompt; it is an internal evaluation step that compares the final generated answer against the retrieved source documents. The harness should call this prompt for every answer generated, or on a sampled subset for cost control, and use the structured output to decide whether to block, flag, or release the answer. The primary integration points are your RAG orchestrator (e.g., LangChain, LlamaIndex, a custom Python service) and your observability stack.
The harness should pass three inputs to the prompt: the full generated answer, the concatenated source passages used for generation, and a structured output schema. Use a model with strong instruction-following and JSON mode support (e.g., GPT-4o, Claude 3.5 Sonnet) because the divergence detection task requires nuanced semantic comparison. Set temperature=0 to minimize variability in the divergence verdict. The output schema should include at minimum: a divergence_score (0-1 float), a divergence_detected boolean, a list of divergent_spans with exact text from the answer, and a rationale string. Parse this JSON response in your application code. If divergence_detected is true and the score exceeds your threshold (start with 0.3 and tune based on your tolerance), route the answer to a human review queue or trigger a regeneration with stricter grounding instructions. Log every verdict, including the score, rationale, and source-answer pair, to your observability platform for drift analysis over time.
Validation and retry logic are critical because this prompt itself can fail. Wrap the call in a retry loop (max 3 attempts) that catches JSON parse errors, missing required fields, or malformed divergent_spans that don't match text in the answer. If the model returns a refusal or an explanation without the structured object, retry with a stricter system instruction that demands JSON output. If retries are exhausted, fail open or closed based on your risk posture: for high-stakes domains (healthcare, legal, finance), fail closed by routing the answer to human review. For lower-stakes applications, fail open but log the harness failure as a high-severity alert. Implement a latency budget: if the divergence check adds more than 2 seconds to your pipeline, consider running it asynchronously after delivering the answer, with a mechanism to retract or annotate the answer if divergence is later detected. Finally, build an eval set of 50-100 source-answer pairs with known divergence labels (including subtle semantic drift, tone shifts, and concept introduction) to calibrate your threshold and monitor harness performance over time.
Expected Output Contract
Defines the structured JSON output schema for the Source-Answer Divergence Detection Prompt. Use this contract to parse, validate, and route the model's response in your production harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
divergence_score | float (0.0 to 1.0) | Must be a number between 0.0 and 1.0. 0.0 indicates perfect alignment; 1.0 indicates complete semantic divergence. | |
divergence_verdict | enum: ['aligned', 'minor_divergence', 'major_divergence'] | Must be one of the three defined string values. Map to divergence_score thresholds: aligned <= 0.2, minor <= 0.6, major > 0.6. | |
divergence_type | string or null | If divergence_verdict is not 'aligned', this field must be populated with a category like 'tone_shift', 'unsupported_detail', 'speculation', or 'contradiction'. Null allowed only when verdict is 'aligned'. | |
source_evidence_summary | string | A concise summary of the core claims found in the source documents. Must not be an empty string. Used to ground the divergence analysis. | |
answer_summary | string | A concise summary of the core claims made in the generated answer. Must not be an empty string. Used to ground the divergence analysis. | |
divergent_spans | array of objects | A list of specific text spans from the answer that diverge from the source. Each object must have 'answer_text' (string) and 'divergence_reason' (string) keys. Array can be empty if verdict is 'aligned'. | |
missing_source_concepts | array of strings | A list of key concepts, entities, or claims present in the answer but completely absent from the source documents. Null allowed if no missing concepts are detected. | |
confidence | float (0.0 to 1.0) | The model's self-reported confidence in its divergence assessment. Must be a number between 0.0 and 1.0. Use for downstream routing or human review thresholds. |
Common Failure Modes
Source-answer divergence is a subtle class of hallucination where the answer sounds plausible and uses source-adjacent language, but introduces concepts, tone, or details absent from the evidence. These failures evade keyword-overlap checks and require semantic comparison. Below are the most common failure modes and how to guard against them.
Concept Drift
What to watch: The answer introduces a related but unsupported concept that feels like a logical extension of the source. For example, a source discusses 'cloud storage costs' and the answer adds 'data egress fees' without evidence. Guardrail: Add a constraint in the divergence prompt requiring the model to list every claim in the answer and map it to an explicit source span. Flag any claim without a direct textual anchor as divergent.
Tone and Certainty Shift
What to watch: The source uses hedging language ('may reduce latency') but the answer states it as fact ('reduces latency by 40%'). The model amplifies certainty, converting tentative findings into definitive claims. Guardrail: Include a tone-alignment check in the divergence prompt. Instruct the model to compare the epistemic stance of each answer claim against the source and flag mismatches where the answer is more certain than the evidence supports.
Detail Fabrication Within Real Context
What to watch: The answer embeds fabricated details inside otherwise faithful summaries. A source mentions 'quarterly growth' and the answer specifies '12% quarterly growth' when no figure exists. The surrounding accuracy masks the fabrication. Guardrail: Require the divergence prompt to extract and verify all numeric values, dates, percentages, and proper nouns independently. Any specific datum not present in the source must be flagged as unsupported.
Cross-Source Contamination
What to watch: When multiple sources are provided, the answer blends information across them, creating a synthesis that no single source supports. The combined claim sounds authoritative but is a fabrication of the model's internal knowledge, not the provided evidence. Guardrail: Add a per-source grounding requirement. The divergence prompt should verify each claim against individual sources before accepting cross-source combinations. Flag any claim that requires merging two sources to justify.
Implied Causation from Correlation
What to watch: Sources describe correlated events or sequential occurrences. The answer infers a causal relationship ('X caused Y' or 'X led to Y') that the evidence never states. This is especially dangerous in analytical and financial contexts. Guardrail: Instruct the divergence prompt to explicitly check for causal language ('caused', 'led to', 'resulted in', 'due to') and verify that the source contains the same causal claim. Flag any causal assertion not directly stated in the evidence.
Temporal Generalization
What to watch: A source describes a past event or a time-bound statement, and the answer presents it as a current or ongoing truth. 'The team shipped feature X in Q2' becomes 'The team ships features regularly.' Guardrail: Include a temporal alignment check. The divergence prompt should extract time references from both source and answer, then flag any answer claim where the temporal scope has been broadened, narrowed, or shifted without source support.
Evaluation Rubric
Use this rubric to test the Source-Answer Divergence Detection prompt against a golden dataset before deploying it as a production guardrail. Each criterion targets a specific failure mode of semantic divergence detection.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Semantic Divergence Recall | Prompt flags all answer statements that introduce concepts, tone, or details absent from [SOURCE_DOCUMENTS]. | A fabricated claim is marked as 'grounded' or receives a low divergence score. | Run against a test set of 20 answers with known fabrications. Measure recall of fabricated statements >= 0.95. |
Faithful Paraphrase Precision | Prompt correctly identifies legitimate paraphrases and synonyms as grounded, not divergent. | A faithful restatement is incorrectly flagged as divergent or unsupported. | Run against a test set of 20 answers with only faithful paraphrases. Measure false positive rate < 0.10. |
Tone Shift Detection | Prompt detects when the answer adopts a more confident, urgent, or speculative tone than the source evidence supports. | An answer that adds hedging or certainty not present in [SOURCE_DOCUMENTS] passes without a tone divergence flag. | Include 5 answer pairs where tone is the only divergence. Confirm the prompt outputs a non-null [TONE_DIVERGENCE] field for each. |
Concept Injection Detection | Prompt identifies when the answer introduces a named entity, technical term, or domain concept not found in [SOURCE_DOCUMENTS]. | A hallucinated product name, person, or metric is missed in the divergence report. | Test with 10 answers containing injected concepts. Verify each injected concept appears in the [DIVERGENT_SPANS] output array. |
Granularity Mismatch Flagging | Prompt detects when the answer provides a level of detail (dates, percentages, quantities) absent from the source evidence. | An answer adds a specific number or date not in the source, and the prompt returns [DIVERGENCE_DETECTED]: false. | Test with 5 answers containing fabricated specifics. Confirm [GRANULARITY_DIVERGENCE] is true for each. |
Source Boundary Adherence | Prompt does not penalize the answer for omitting information present in [SOURCE_DOCUMENTS] that was not requested in [USER_QUERY]. | A concise, faithful answer is flagged as divergent because it did not include all source details. | Test with 5 answers that are faithful but selective. Confirm [DIVERGENCE_DETECTED] is false and [DIVERGENCE_SCORE] < 0.2. |
Output Schema Compliance | Prompt returns valid JSON matching the [OUTPUT_SCHEMA] on every run, even for edge-case inputs. | The model returns malformed JSON, missing required fields, or extra-text outside the JSON object. | Run 100 evaluations with varied inputs. Assert 100% parse success with a JSON schema validator against the expected [OUTPUT_SCHEMA]. |
Empty Source Handling | When [SOURCE_DOCUMENTS] is an empty string or null, the prompt marks all answer content as divergent and does not crash. | An empty source input causes a runtime error, a refusal, or a hallucinated divergence report. | Test with [SOURCE_DOCUMENTS] set to null and an answer with 3 factual statements. Confirm [DIVERGENCE_DETECTED] is true and all statements are flagged. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single source document and a generated answer. Focus on getting the divergence classification labels right before adding schema enforcement. Run the prompt in a notebook or playground with 10-20 examples to calibrate what counts as semantic divergence versus faithful paraphrase.
Simplify the output to a single divergence score and a one-sentence explanation. Skip structured JSON output initially—just ask for a label and rationale in plain text.
Watch for
- The model conflating stylistic differences with semantic divergence
- Over-flagging legitimate rephrasing as divergence
- Missing subtle tone shifts that change meaning without changing facts
- No baseline comparison against human judgments yet

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us