Inferensys

Prompt

RAG Answer Faithfulness Trace Audit Prompt

A practical prompt playbook for using RAG Answer Faithfulness Trace Audit Prompt 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

Diagnose why a RAG system produced an unfaithful answer by auditing a single production trace for hallucinated claims, omissions, and evidence gaps.

Quality engineers and RAG developers use this prompt to audit a single production trace for answer faithfulness. The prompt compares the final generated answer against every piece of retrieved evidence in the trace, producing a structured faithfulness score, a list of hallucinated or omitted claims, and a comparison against any available human faithfulness judgment. Use this prompt when you need to diagnose why a RAG system produced an unfaithful answer, calibrate automated faithfulness metrics, or build a review queue for high-risk responses.

This is a diagnostic trace-analysis prompt, not a real-time guard prompt. It assumes you already have a logged trace containing the user query, retrieved passages, final answer, and optional human rating. The prompt works best when traces include the full retrieved context—not just the top-k chunks—so the auditor can distinguish between 'evidence was retrieved but ignored' and 'evidence was never retrieved.' Run this prompt on sampled traces from production, on eval failures flagged by automated monitoring, or on user-reported hallucinations. Do not use this prompt as a streaming guardrail; its strength is thorough post-hoc analysis, not low-latency intervention.

Before running this prompt, verify that your trace contains the complete retrieved context and the final generated answer. If the trace is missing retrieval metadata or only stores truncated context, the faithfulness audit will produce unreliable results. After running the audit, feed the structured output into your evaluation pipeline: compare automated faithfulness scores against human judgments to calibrate thresholds, track hallucination categories over time, and route high-severity findings to a human review queue. Avoid using this prompt on traces where the answer was intentionally creative or speculative—faithfulness auditing requires a groundable answer against specific evidence.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before embedding this audit into your RAG pipeline.

01

Good Fit: Post-Deployment Quality Audits

Use when: You need to sample production RAG traces and verify that generated answers are faithful to the retrieved evidence. Guardrail: Run this prompt on a statistically significant sample of traces, not every single request, to balance cost and coverage.

02

Bad Fit: Real-Time Guardrails

Avoid when: You need to block an unfaithful answer before it reaches the user. This prompt is a forensic audit tool, not a low-latency safety classifier. Guardrail: Pair this offline audit with a lightweight, real-time hallucination detector for synchronous checks.

03

Required Inputs: Full Retrieval-to-Generation Trace

Risk: Running this prompt without the complete trace—user query, retrieved chunks, final answer, and citations—produces unreliable scores. Guardrail: Validate that the trace payload includes all required fields before invoking the audit; abort and flag incomplete traces.

04

Operational Risk: High Token Consumption

Risk: Auditing a trace with many retrieved chunks can consume significant context window tokens, increasing cost and latency. Guardrail: Set a maximum chunk count per audit; if exceeded, either sample chunks or escalate to a human reviewer for manual inspection.

05

Calibration Risk: Faithfulness Score Drift

Risk: The model's internal threshold for flagging a claim as "unsupported" may drift across model versions, making scores incomparable over time. Guardrail: Maintain a golden set of 20–50 human-annotated traces and run this prompt against them weekly to detect calibration drift.

06

Human-in-the-Loop: Escalation for Ambiguous Cases

Risk: Borderline claims—where evidence partially supports the answer—can produce false positives or negatives in the faithfulness score. Guardrail: Route traces with a confidence score below a defined threshold to a human review queue instead of auto-accepting the audit verdict.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for auditing RAG answer faithfulness against retrieved evidence in a production trace.

This prompt template is designed to be pasted directly into your trace analysis tool, evaluation pipeline, or LLM-as-judge harness. It instructs the model to act as a quality engineer reviewing a complete retrieval-to-generation trace. The model must compare every factual claim in the final answer against the retrieved context, produce a faithfulness score, and flag specific hallucinations or omissions. Use square-bracket placeholders to inject the trace data, scoring rubric, and output schema before execution.

text
You are a quality engineer auditing a RAG (Retrieval-Augmented Generation) system. Your task is to review the full production trace below and assess whether the final generated answer is faithful to the retrieved evidence.

## INPUT

### User Query
[USER_QUERY]

### Retrieved Context
[RETRIEVED_CONTEXT]

### Generated Answer
[GENERATED_ANSWER]

### Trace Metadata (optional)
[TRACE_METADATA]

## INSTRUCTIONS

1. Extract every factual claim from the Generated Answer. A factual claim is any statement that asserts something about the world, including dates, names, numbers, events, relationships, or properties.

2. For each claim, search the Retrieved Context for supporting evidence. A claim is supported only if the context directly states it or it can be logically inferred from the context without adding external knowledge.

3. Classify each claim into one of three categories:
   - **Grounded**: The claim is directly supported by the Retrieved Context.
   - **Hallucinated**: The claim contradicts the Retrieved Context or introduces information not present in the context.
   - **Omitted**: The Retrieved Context contains information relevant to the User Query that the Generated Answer failed to include.

4. Produce a faithfulness score from 0.0 to 1.0, where 1.0 means every claim is grounded and no relevant context was omitted. Use this formula: (Number of Grounded Claims) / (Number of Grounded Claims + Number of Hallucinated Claims). Penalize omissions separately in the omission flag list.

5. For each hallucinated claim, explain why it is unsupported and cite the specific passage from the Retrieved Context that contradicts it or the absence of supporting evidence.

6. For each omitted fact, cite the specific passage from the Retrieved Context that contains the missing information.

## CONSTRAINTS

- Do not use any knowledge outside the Retrieved Context.
- If the Retrieved Context is empty or irrelevant, mark all claims as hallucinated and set the faithfulness score to 0.0.
- If the Generated Answer is empty, return a score of 0.0 and note that no answer was provided.
- Do not penalize the answer for style, grammar, or fluency. Only assess factual faithfulness.
- If the User Query is ambiguous, note the ambiguity but still assess claims against the context as provided.

## OUTPUT SCHEMA

Return a JSON object with this exact structure:

{
  "faithfulness_score": float,
  "total_claims": int,
  "grounded_claims": int,
  "hallucinated_claims": int,
  "omitted_facts": int,
  "claim_analysis": [
    {
      "claim_text": string,
      "classification": "grounded" | "hallucinated",
      "supporting_evidence": string | null,
      "contradicting_evidence": string | null,
      "explanation": string
    }
  ],
  "omission_flags": [
    {
      "omitted_fact": string,
      "source_passage": string,
      "relevance": string
    }
  ],
  "overall_assessment": string
}

## EXAMPLES

### Example 1: Fully Faithful Answer
User Query: "What is the capital of France?"
Retrieved Context: "Paris is the capital and most populous city of France."
Generated Answer: "The capital of France is Paris."

Output:
{
  "faithfulness_score": 1.0,
  "total_claims": 1,
  "grounded_claims": 1,
  "hallucinated_claims": 0,
  "omitted_facts": 0,
  "claim_analysis": [
    {
      "claim_text": "The capital of France is Paris.",
      "classification": "grounded",
      "supporting_evidence": "Paris is the capital and most populous city of France.",
      "contradicting_evidence": null,
      "explanation": "The claim directly matches the retrieved context."
    }
  ],
  "omission_flags": [],
  "overall_assessment": "All claims are grounded. No omissions detected."
}

### Example 2: Hallucinated Claim
User Query: "When was the Eiffel Tower built?"
Retrieved Context: "The Eiffel Tower was completed in 1889."
Generated Answer: "The Eiffel Tower was built in 1887 and opened in 1889."

Output:
{
  "faithfulness_score": 0.5,
  "total_claims": 2,
  "grounded_claims": 1,
  "hallucinated_claims": 1,
  "omitted_facts": 0,
  "claim_analysis": [
    {
      "claim_text": "The Eiffel Tower was built in 1887.",
      "classification": "hallucinated",
      "supporting_evidence": null,
      "contradicting_evidence": "The Eiffel Tower was completed in 1889.",
      "explanation": "The context states completion in 1889, not 1887. The 1887 date is unsupported."
    },
    {
      "claim_text": "The Eiffel Tower opened in 1889.",
      "classification": "grounded",
      "supporting_evidence": "The Eiffel Tower was completed in 1889.",
      "contradicting_evidence": null,
      "explanation": "Completion in 1889 supports the opening claim."
    }
  ],
  "omission_flags": [],
  "overall_assessment": "One hallucinated claim detected. The 1887 construction date is not supported by the retrieved context."
}

## RISK LEVEL
[HIGH] - Faithfulness audits are used to detect hallucination in production RAG systems. Incorrect scores can lead to overconfident deployment of unreliable answers. Always validate a sample of audit outputs against human judgments before relying on automated scores for gating decisions.

After pasting this template, replace each square-bracket placeholder with real trace data. The [RETRIEVED_CONTEXT] should include the full text of every retrieved passage, not just IDs or summaries. If your trace system captures reranking scores or metadata filters, include those in [TRACE_METADATA] to help the model understand retrieval quality. For high-stakes domains such as healthcare or legal, always run a human review sample against the automated faithfulness scores to calibrate the model's judgment before trusting the output for gating or monitoring decisions.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the RAG Answer Faithfulness Trace Audit Prompt. Each placeholder must be populated from production trace data before the audit prompt executes. Missing or malformed inputs will cause the faithfulness scoring to fail or produce unreliable results.

PlaceholderPurposeExampleValidation Notes

[FULL_TRACE_JSON]

Complete production trace containing retrieval steps, context window contents, and generated answer with citations

{"trace_id": "abc123", "steps": [{"type": "retrieval", "chunks": [...]}, {"type": "generation", "output": "...", "citations": [...]}]}

Must be valid JSON with trace_id, steps array, and at least one retrieval step and one generation step. Reject if trace is truncated or missing generation output.

[USER_QUERY]

Original user question or prompt that triggered the RAG pipeline

What are the side effects of metformin for elderly patients?

Must be non-empty string. Should match the query captured in the trace metadata. Reject if query is redacted or placeholder text.

[RETRIEVED_CHUNKS_ARRAY]

All retrieved document chunks passed into the context window, with source identifiers

[{"chunk_id": "doc12_chunk3", "source": "clinical_guidelines_2024.pdf", "text": "Metformin is generally well-tolerated..."}]

Must be a non-empty array of objects with chunk_id, source, and text fields. Validate that text fields are not null or whitespace-only. Reject if array is empty.

[GENERATED_ANSWER]

Final model-generated answer text including any inline citations or reference markers

Based on the retrieved evidence, metformin may cause gastrointestinal side effects [1][2]. Lactic acidosis is rare but serious [3].

Must be non-empty string. Should contain citation markers if the system is configured for cited output. Flag if answer is a refusal or fallback message rather than a substantive response.

[CITATION_MAP]

Mapping from citation markers in the generated answer to specific retrieved chunk IDs

{"[1]": "doc12_chunk3", "[2]": "doc12_chunk4", "[3]": "doc15_chunk1"}

Must be a valid JSON object. Every citation marker in the generated answer must have a corresponding entry. Flag missing mappings as potential hallucination indicators before audit begins.

[HUMAN_FAITHFULNESS_LABEL]

Optional human-annotated faithfulness judgment for calibration comparison

{"label": "partially_faithful", "annotator_notes": "Answer is faithful to chunks 1-2 but claim about lactic acidosis is not in chunk 3", "flagged_claims": ["lactic acidosis risk"]}

Nullable. If provided, must be valid JSON with label field containing one of: fully_faithful, partially_faithful, not_faithful. Used for eval calibration, not required for audit execution.

[FAITHFULNESS_THRESHOLD]

Minimum faithfulness score required for the answer to pass automated quality gates

0.85

Must be a float between 0.0 and 1.0. Default 0.80 if not specified. Scores below threshold should trigger human review or regeneration. Validate that threshold is not set to 0.0 or 1.0 without explicit override reason.

[OUTPUT_SCHEMA]

Expected JSON schema for the faithfulness audit output including score, flags, and per-claim analysis

{"type": "object", "properties": {"faithfulness_score": {"type": "number"}, "hallucination_flags": {"type": "array"}, "omission_flags": {"type": "array"}, "per_claim_analysis": {"type": "array"}}}

Must be a valid JSON Schema object. Reject if schema is missing required fields: faithfulness_score, hallucination_flags, omission_flags. Validate that schema matches downstream consumer expectations before audit execution.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the RAG Answer Faithfulness Trace Audit Prompt into a production evaluation pipeline with validation, retries, and human review gates.

The faithfulness audit prompt is not a one-off debugging tool; it belongs inside a structured evaluation harness that runs against production traces or sampled sessions. The harness must feed the prompt a complete trace object containing the user query, all retrieved chunks with their metadata, and the final generated answer. Before calling the model, validate that the trace includes retrieval timestamps, chunk rankings, and source identifiers. If any required field is missing, the harness should log the incomplete trace and skip evaluation rather than producing a misleading faithfulness score. This prompt works best with models that have strong instruction-following and structured output capabilities, such as GPT-4o, Claude 3.5 Sonnet, or equivalent. Avoid running it on models smaller than ~7B parameters without extensive few-shot calibration, as hallucination detection requires nuanced reasoning about evidence boundaries.

Wire the prompt into a batch evaluation pipeline that processes traces in groups, with each trace evaluated independently. The harness should enforce a strict JSON output schema using the model's native structured output mode or a post-processing validator. Define the expected schema fields: faithfulness_score (0-1 float), hallucination_flags (array of objects with claim, evidence_gap, severity), omission_flags (array of objects with missing_fact, available_evidence, impact), and comparison_to_human_judgment (object with agreement, discrepancy_notes). After each model call, validate that all required fields are present, scores are within range, and flag arrays contain the expected subfields. If validation fails, retry once with the same trace and a stronger constraint instruction appended to the prompt. If the retry also fails, route the trace to a human review queue with the raw trace, the failed output, and the validation error details. Log every evaluation attempt, including the prompt version, model, trace ID, raw output, validation result, and final disposition, so that evaluation quality itself can be audited over time.

For high-stakes domains such as healthcare, legal, or finance, do not rely solely on the model's faithfulness score. The harness should include a human review gate for any trace where the faithfulness score falls below 0.8, where hallucination flags carry severity: critical, or where the model's judgment disagrees with a prior human faithfulness label. Route these traces to a review interface that displays the original answer, the retrieved evidence side by side, and the model's flagged claims with evidence gaps highlighted. The reviewer can confirm, override, or annotate each flag. Store the human-reviewed result as ground truth for future eval calibration. Over time, this feedback loop improves both the prompt's accuracy and the team's understanding of where the RAG pipeline produces unfaithful answers. Avoid wiring this prompt into synchronous user-facing flows; the audit is an offline evaluation step, not a real-time guardrail. For continuous monitoring, schedule the harness to run on a sample of production traces daily, with aggregate faithfulness metrics pushed to your observability dashboard alongside retrieval quality and latency metrics.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the JSON object produced by the RAG Answer Faithfulness Trace Audit Prompt. Use this contract to parse the model's output and gate downstream processing.

Field or ElementType or FormatRequiredValidation Rule

faithfulness_score

number (0.0 to 1.0)

Must be a float between 0.0 and 1.0 inclusive. Parse check: 0.0 <= score <= 1.0.

classification

string (enum)

Must be exactly one of: faithful, unfaithful, partially_faithful. Schema check: strict string match.

hallucination_flags

array of objects

Each object must contain claim (string), evidence_ref (string or null), and severity (enum: critical, major, minor). Null allowed for evidence_ref if no source is cited.

omission_flags

array of objects

Each object must contain missing_fact (string) and source_document_id (string). Source document must exist in the trace's retrieved context. Citation check: ID cross-reference.

evidence_alignment_summary

string

Must be a non-empty string summarizing how the answer aligns with or diverges from the retrieved evidence. Null not allowed.

trace_id

string

Must match the [TRACE_ID] input exactly. Parse check: string equality comparison.

human_judgment_comparison

object

If [HUMAN_JUDGMENT] is provided, this object must contain agreement (boolean) and discrepancy_note (string or null). Approval required if agreement is false.

audit_timestamp

string (ISO 8601)

Must be a valid ISO 8601 datetime string. Parse check: new Date(str) does not throw and matches regex.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when auditing RAG answer faithfulness from production traces, and how to guard against it.

01

Retrieved Evidence Is Irrelevant

What to watch: The faithfulness audit flags hallucinations that are actually caused by retrieval returning off-topic or tangentially related documents. The model generates faithfully from bad context, but the answer is still wrong. Guardrail: Run a retrieval relevance scoring step before the faithfulness audit. If retrieved chunks score below a relevance threshold, classify the failure as a retrieval gap, not a generation hallucination.

02

Citation Points to Wrong Source Location

What to watch: The model cites a real document but the specific claim appears in a different section or chunk than the one referenced. The audit may incorrectly flag this as hallucination when the evidence exists elsewhere in the retrieved set. Guardrail: Expand citation verification to search all retrieved chunks, not just the cited chunk. Flag citation-location mismatches separately from unsupported claims.

03

Trace Truncation Hides Evidence

What to watch: The production trace captures only partial retrieved context due to logging limits or token budget constraints. The faithfulness audit sees missing evidence and flags hallucinations that were actually grounded in the truncated portion. Guardrail: Verify trace completeness before running the audit. If the trace is truncated, mark the audit result as inconclusive and escalate for full-trace capture.

04

Paraphrased Claims Fail Exact-Match Verification

What to watch: The model rephrases retrieved evidence using different vocabulary, and a strict string-matching or embedding-similarity audit incorrectly flags faithful paraphrases as unsupported. Guardrail: Use an LLM judge with a rubric that explicitly distinguishes between faithful paraphrase and unsupported fabrication. Calibrate similarity thresholds against human-labeled paraphrase pairs.

05

Multi-Hop Reasoning Breaks Single-Chunk Attribution

What to watch: The answer combines facts from multiple retrieved chunks through reasoning, but the faithfulness audit checks each claim against individual chunks in isolation. Legitimate synthesis is flagged as hallucination. Guardrail: Extend the audit to evaluate whether a claim is supported by the union of all retrieved chunks. Flag claims that require cross-chunk reasoning separately and apply a different verification standard.

06

Human Faithfulness Judgments Are Inconsistent

What to watch: The audit compares model outputs against human faithfulness labels, but human annotators disagree on borderline cases, inflating false-positive rates. Guardrail: Measure inter-annotator agreement before using human labels as ground truth. For claims with low annotator agreement, exclude them from strict pass/fail evaluation or use a consensus adjudication step.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the output of the RAG Answer Faithfulness Trace Audit Prompt before integrating it into a production quality pipeline. Each criterion maps to a specific failure mode observed in trace audits.

CriterionPass StandardFailure SignalTest Method

Faithfulness Score Calibration

Score aligns with human judgment within a 0.5 tolerance on a 1-5 scale

Score differs from human judgment by more than 1.0 on the same trace

Compare model-assigned score against 3 human evaluators on a golden set of 20 traces

Hallucination Flag Precision

Every flagged hallucination maps to a claim not supported by retrieved evidence

Flagged hallucination is actually supported by a retrieved passage or is a false positive

For each flag, manually verify the claim against the full retrieved context in the trace

Omission Flag Recall

All factual claims in the retrieved evidence that are missing from the answer are flagged

A key fact present in retrieved evidence is absent from the answer but not flagged as an omission

Extract all facts from retrieved evidence and check if missing ones appear in the omission report

Citation Grounding Accuracy

Every citation in the answer points to a source that contains the cited claim

A citation points to a source that does not contain the claim or is fabricated

For each citation, locate the source in the trace and verify the claim is present

Evidence Boundary Respect

Answer contains no claims beyond what is in the retrieved evidence

Answer includes a claim that cannot be found in any retrieved passage

Diff the answer claims against the union of all retrieved passage claims

Trace Completeness Check

All retrieval steps, tool calls, and context assembly events are referenced in the audit

Audit omits a retrieval step or context window event visible in the raw trace

Compare audit event list against the full trace log for missing steps

Confidence Annotation Validity

Low-confidence annotations appear only on claims with ambiguous or conflicting evidence

High-confidence annotation on a claim with clearly contradictory evidence in the trace

Review all high-confidence claims against evidence for contradictions

Output Schema Compliance

Output matches the defined schema with all required fields present and correctly typed

Missing field, wrong type, or extra field not in the schema

Validate output against the JSON schema using a schema validator

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single model call and manual review of the output. Remove strict schema requirements initially. Focus on getting the faithfulness reasoning right before adding structured scoring.

Simplify the output to a narrative assessment:

code
Review the retrieved context and generated answer. Identify any claims in the answer that are not supported by the context. Flag hallucinations and omissions.

Retrieved Context: [RETRIEVED_CONTEXT]
Generated Answer: [GENERATED_ANSWER]

Watch for

  • Overly broad hallucination claims without specific evidence
  • Missing distinction between omission and contradiction
  • Inconsistent severity judgments across traces
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.