Inferensys

Prompt

Source Provenance Chain Prompt for RAG Systems

A practical prompt playbook for audit and compliance engineers who need to generate a complete, verifiable chain of custody for every claim in a RAG system, from the original document through retrieval and chunk selection to the final citation.
Developer working on RAG retrieval system, document chunks visible on screen, technical workspace with code editor.
PROMPT PLAYBOOK

When to Use This Prompt

Use this prompt to build a machine-readable audit artifact that proves every factual claim in a RAG-generated answer is traceable to its source document.

This prompt is designed for audit and compliance engineers who must demonstrate to internal reviewers, regulators, or downstream systems that a generated answer is fully grounded. It is not a general question-answering prompt. It assumes you already have a working RAG pipeline that produces answers with citations. The job-to-be-done is post-generation verification: taking the answer, its citations, and the retrieval results, then constructing a backward trace that links each claim through the retrieval step, the specific chunk selected, and the original document metadata. The output is a structured provenance chain artifact suitable for logging, audit review, or automated compliance checks.

Use this prompt when the cost of an unsupported claim is high—regulatory filings, legal document review, financial audit summaries, or clinical documentation. It is appropriate when you need to prove that every material statement in an answer can be mapped to a known source, and when you need to flag any broken links where a citation cannot be matched to a retrieval result. Do not use this prompt for real-time chat where latency matters more than auditability, or for creative generation tasks where factual grounding is not required. It is also not a substitute for a properly instrumented RAG pipeline; if your retrieval system does not preserve chunk IDs, document metadata, and retrieval scores, this prompt cannot reconstruct what was lost.

Before invoking this prompt, ensure your pipeline captures the full retrieval context: the original query, the list of retrieved chunks with their document IDs and metadata, the final answer, and the citations the model produced. The prompt will cross-reference these artifacts and flag gaps. After generation, validate the output against a schema that enforces the provenance chain structure. For high-risk domains, route outputs with broken provenance links to human review rather than silently accepting them. The next section provides the copy-ready prompt template you can adapt to your specific document schema and citation format.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Source Provenance Chain Prompt delivers value and where it introduces unnecessary complexity.

01

Good Fit: Regulatory Audit Trails

Use when: compliance or legal teams require a complete, immutable record of how an AI system arrived at an answer, from the original document through retrieval to the final citation. Value: The prompt generates a structured chain of custody that auditors can review step-by-step, reducing the time to prove evidence grounding from days to minutes.

02

Good Fit: High-Stakes Document Q&A

Use when: answers from financial filings, medical records, or legal contracts must be defensible. Value: Every claim is linked to a specific chunk, retrieval step, and source document, making it possible to trace and contest individual statements without re-running the entire pipeline.

03

Bad Fit: Real-Time Chatbots

Avoid when: latency budgets are under 500ms or the user expects conversational answers without provenance. Risk: The provenance chain adds significant token overhead and processing time. Mitigation: Use a lighter citation prompt for real-time use and reserve full provenance chains for async audit or batch review workflows.

04

Bad Fit: Low-Risk General Knowledge

Avoid when: the domain has no regulatory or compliance requirements and users do not need to verify sources. Risk: The detailed chain output adds noise and cost without user benefit. Mitigation: Default to a simpler answer-with-citation prompt and escalate to provenance chains only when an audit flag is raised.

05

Required Inputs

Must have: the original user query, the full list of retrieved chunks with their source document identifiers and retrieval scores, and the final generated answer. Strongly recommended: retrieval parameters (k, similarity threshold, embedding model version) and any reranking decisions. Missing inputs will produce broken provenance links that fail audit review.

06

Operational Risk: Silent Provenance Gaps

What to watch: The model may generate a plausible-looking provenance chain that skips a retrieval step or fabricates a chunk-to-claim link. Guardrail: Implement a completeness check that verifies every cited chunk exists in the original retrieval set and every claim in the final answer has at least one provenance link before the output is accepted.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your orchestration layer. Replace square-bracket placeholders with data from your RAG pipeline logs.

The following prompt template is designed to be injected into your model's context window after retrieval and before answer generation. It forces the model to construct an explicit provenance chain for every claim, linking the final answer back through the specific chunk, retrieval query, and source document. This is not a conversational prompt—it is a structured audit artifact generator. Use it when you need a verifiable trail for compliance review, debugging retrieval failures, or proving to a regulator that no information was hallucinated. Do not use this prompt for latency-sensitive user-facing chat where a full chain would overwhelm the response.

text
You are an audit-grade provenance tracer. Your only job is to produce a structured provenance chain for every factual claim you would make in response to the user's question.

## INPUTS
- USER_QUESTION: [USER_QUESTION]
- RETRIEVED_CHUNKS: [RETRIEVED_CHUNKS]
- CHUNK_METADATA: [CHUNK_METADATA]
- RETRIEVAL_QUERIES_USED: [RETRIEVAL_QUERIES_USED]
- SOURCE_DOCUMENT_IDS: [SOURCE_DOCUMENT_IDS]

## OUTPUT SCHEMA
Return a single JSON object with the following structure:
{
  "provenance_chain": [
    {
      "claim_id": "string (unique identifier for this claim)",
      "claim_text": "string (the exact factual statement)",
      "supporting_chunk_id": "string (ID from CHUNK_METADATA)",
      "supporting_chunk_text": "string (the exact text from RETRIEVED_CHUNKS)",
      "retrieval_query_used": "string (which query retrieved this chunk)",
      "source_document_id": "string (from SOURCE_DOCUMENT_IDS)",
      "confidence": "high|medium|low",
      "chain_completeness": "complete|broken_missing_chunk|broken_missing_query|broken_missing_document"
    }
  ],
  "unanswerable_claims": [
    {
      "claim_text": "string (claim that cannot be sourced)",
      "reason": "no_evidence_found|contradictory_evidence|insufficient_context"
    }
  ],
  "completeness_check": {
    "total_claims": "number",
    "sourced_claims": "number",
    "broken_links": "number",
    "overall_chain_health": "healthy|partial|broken"
  }
}

## CONSTRAINTS
1. Every claim in the answer MUST appear in the provenance_chain array.
2. If a claim cannot be linked to a specific chunk, query, and document, place it in unanswerable_claims.
3. Do not invent chunk IDs, document IDs, or query strings. Use only values provided in the INPUTS.
4. If a chunk was retrieved by multiple queries, list the most specific query.
5. Mark chain_completeness as "broken_missing_chunk" if the chunk ID is absent, "broken_missing_query" if the retrieval query is absent, and "broken_missing_document" if the source document ID is absent.
6. Set confidence to "low" if the chunk text only partially supports the claim.

## RISK LEVEL: [RISK_LEVEL]
- If RISK_LEVEL is "high", you MUST NOT output any claim with broken links. Place all broken-link claims in unanswerable_claims.
- If RISK_LEVEL is "medium", you may output claims with "low" confidence but must flag them.
- If RISK_LEVEL is "low", you may output all claims but must still populate the completeness_check accurately.

To adapt this template, wire your RAG pipeline's retrieval logs into the placeholders. [RETRIEVED_CHUNKS] should contain the raw text of every chunk passed to the model. [CHUNK_METADATA] must include unique chunk IDs, parent document IDs, and the retrieval query that fetched each chunk. If your retriever does not natively track which query produced which chunk, add that mapping in your orchestration layer before populating [CHUNK_METADATA]. The [RISK_LEVEL] placeholder should be set based on the downstream use case: "high" for regulatory filings and audit responses, "medium" for internal compliance checks, and "low" for exploratory research where broken links are acceptable but must be logged. After the model returns the JSON, validate it against the schema before allowing any downstream system to consume the provenance chain. A single missing claim_id or invented document_id is a compliance failure, not a formatting error.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder required by the Source Provenance Chain Prompt. Use this table to wire the prompt into your RAG pipeline, validate inputs before generation, and catch missing or malformed data before it reaches the model.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The original question or request that triggered the RAG retrieval and provenance generation.

What are the termination conditions for the master service agreement?

Required. Must be a non-empty string. Reject if only whitespace or exceeds max query length defined by retriever.

[RETRIEVED_CHUNKS]

The full set of document chunks returned by the retrieval step, including metadata for each chunk.

[{"chunk_id": "doc12_p4_c2", "text": "Either party may terminate...", "source": "MSA_2024.pdf", "page": 4, "section": "8.2"}]

Required. Must be a valid JSON array with at least one chunk object. Each chunk must contain chunk_id, text, and source fields. Reject if array is empty or any chunk is missing required fields.

[CHUNK_SELECTION_RATIONALE]

Explanation of which chunks were selected for the final answer and why, typically from a reranker or selection step.

Selected chunks 3 and 5 based on cosine similarity > 0.85 and keyword match on 'termination'. Chunk 7 excluded due to low relevance score.

Required if selection step exists. Must be a non-empty string. If no selection step is used, set to 'All retrieved chunks used without filtering.' and flag for review.

[RETRIEVAL_METHOD]

Identifier for the retrieval method used, including any query rewriting or expansion applied.

hybrid_search_v2 with query expansion: 'termination conditions OR cancellation terms OR end of agreement'

Required. Must be a non-empty string. Use a consistent naming convention across your system for audit traceability. Reject if method name is unrecognized or missing.

[MODEL_VERSION]

Identifier for the model generating the provenance chain, used for audit and reproducibility.

claude-sonnet-4-20250514

Required. Must match a known model identifier in your deployment registry. Reject if version string is empty or does not conform to your model naming convention.

[OUTPUT_SCHEMA]

The expected JSON schema for the provenance chain output, defining required fields and their types.

{"type": "object", "required": ["query", "claims", "provenance_chain"], "properties": {"claims": {"type": "array", "items": {"type": "object", "required": ["claim_text", "source_chunk_id", "source_page", "source_section"]}}}}

Required. Must be a valid JSON Schema object. Validate schema syntax before passing to the model. Reject if schema is missing required fields or contains circular references.

[CONFIDENCE_THRESHOLD]

Minimum confidence score a chunk must meet to be included as a citation source.

0.75

Required. Must be a float between 0.0 and 1.0. If set below 0.5, add a warning flag in logs. If null, default to 0.7 and log the default application.

[AUDIT_LOG_ENABLED]

Boolean flag indicating whether a full audit log entry should be generated alongside the provenance chain.

Required. Must be true or false. If true, ensure the output includes a timestamped audit_log object with retrieval parameters, model version, and any human override flags.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Source Provenance Chain prompt into a production RAG pipeline for reliable, auditable outputs.

The Source Provenance Chain prompt is not a standalone Q&A prompt—it is a post-retrieval audit layer that sits between your retrieval system and your final answer generation. In a production harness, you call this prompt after retrieval returns candidate chunks but before you generate the user-facing answer. The prompt receives the original query, the retrieved chunks with their metadata (document ID, chunk index, retrieval score, and source path), and any intermediate query rewrites or filter decisions. Its job is to produce a structured provenance chain that traces every piece of evidence from origin document through retrieval step to final chunk selection. This chain becomes the audit artifact you store alongside the generated answer, enabling downstream compliance review, debugging of retrieval failures, and user-facing citation display.

Wire this prompt into your RAG pipeline as a dedicated provenance step with strict input validation. Before calling the model, validate that every chunk in [RETRIEVED_CHUNKS] carries required metadata fields: doc_id, chunk_index, retrieval_method (e.g., vector, keyword, hybrid), retrieval_score, and source_path. If any chunk is missing these fields, reject the batch and log a schema violation before the model ever sees it. On the output side, parse the model's JSON response and validate that every claim in the provenance chain references a chunk that actually exists in the input set—this catches hallucinated chunk references. If the model produces a provenance link to a chunk ID not present in the input, flag the entire chain for human review and do not attach it to the user-facing answer. For high-compliance domains, implement a dual-write pattern: store both the raw model output and the validated provenance chain so auditors can inspect any validation corrections.

Model choice matters here. This prompt requires strong instruction-following and structured JSON output, so prefer models with proven schema adherence (GPT-4o, Claude 3.5 Sonnet, or fine-tuned variants). Avoid smaller models that tend to drop required fields or hallucinate chunk references under complex provenance constraints. Set temperature=0 to maximize deterministic output, and configure your harness to retry once with the same input if the initial response fails JSON schema validation. If the retry also fails, escalate to a human reviewer with the raw retrieval context and the failed outputs rather than silently dropping the provenance step. Log every provenance chain with a unique chain_id, the model version, retrieval parameters, and validation status for audit readiness. Finally, implement a completeness gate: before any answer reaches the user, confirm that a validated provenance chain exists and that its completeness_check field shows no broken links. If the chain is incomplete, suppress the answer and return a fallback indicating that provenance could not be verified.

IMPLEMENTATION TABLE

Expected Output Contract

Schema contract for the Source Provenance Chain output. Every claim in the response must map to a provenance node. Use this table to validate outputs before they reach downstream audit or compliance systems.

Field or ElementType or FormatRequiredValidation Rule

provenance_chain

array of objects

Must be a non-empty array. Reject if empty or missing.

provenance_chain[].claim_id

string (UUID v4)

Must match regex ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$. Reject if duplicate claim_id exists in the array.

provenance_chain[].claim_text

string

Must be non-empty and <= 500 characters. Reject if claim_text is identical to another claim in the same response.

provenance_chain[].source_document

string

Must match a document identifier provided in [SOURCE_DOCUMENTS]. Reject if identifier not found in input context.

provenance_chain[].retrieval_query

string

Must be non-empty. Reject if identical to the raw user input without any query rewriting or expansion.

provenance_chain[].retrieved_chunk_id

string

Must match a chunk identifier present in [RETRIEVED_CHUNKS]. Reject if chunk_id is not in the provided retrieval payload.

provenance_chain[].chunk_text_snippet

string

Must be a verbatim substring of the chunk identified by retrieved_chunk_id. Reject if snippet does not appear in the source chunk.

provenance_chain[].citation_location

string

Must include at least one locator: page, paragraph, section, or line. Reject if location is 'unknown' or 'N/A' without an explicit null reason.

provenance_chain[].provenance_gap

boolean

Must be true if any link in the chain (document -> retrieval -> chunk -> citation) is missing or unverifiable. Reject if gap is false but a required field is null.

provenance_chain[].gap_description

string or null

Required when provenance_gap is true. Must describe which link is broken. Reject if non-null when provenance_gap is false.

provenance_chain[].confidence_score

number (0.0 to 1.0)

Must be a float between 0.0 and 1.0 inclusive. Reject if score > 0.9 but provenance_gap is true.

provenance_chain[].human_review_required

boolean

Must be true if confidence_score < [CONFIDENCE_THRESHOLD] or provenance_gap is true. Reject if false when conditions are met.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when generating source provenance chains in production and how to guard against it.

01

Broken Retrieval Links

What to watch: The provenance chain references a chunk ID or document that no longer exists in the index due to re-indexing, deletion, or version drift. The chain becomes a dead link, failing audit requirements. Guardrail: Store immutable chunk hashes alongside IDs. Validate every provenance link against the current index before finalizing the chain. Flag 'stale reference' when a hash mismatch occurs.

02

Silent Chunk Boundary Gaps

What to watch: A claim is attributed to a single chunk, but the supporting evidence actually spans two adjacent chunks. The provenance chain looks complete but misses critical context, making the citation misleading under audit. Guardrail: Implement overlap-aware retrieval that fetches adjacent chunks. Add a 'boundary check' step in the prompt that asks the model to verify whether the cited chunk fully contains the evidence or requires neighbor context.

03

Hallucinated Intermediate Steps

What to watch: The model fabricates a plausible-sounding retrieval step, query rewrite, or chunk selection rationale that never actually occurred in the system logs. The chain reads as coherent but is fiction. Guardrail: Generate the provenance chain programmatically from actual system logs (retrieval calls, chunk IDs, scores) rather than asking the model to reconstruct the chain. Use the model only to annotate and explain the real log events.

04

Confidence Score Inflation

What to watch: The model assigns high confidence to every link in the chain, even when retrieval scores are low or evidence is tangential. This masks weak provenance and undermines audit trust. Guardrail: Pass raw retrieval scores and similarity metrics into the prompt as hard constraints. Instruct the model to map these to a defined confidence scale with explicit thresholds. Validate that low retrieval scores cannot produce 'high confidence' labels.

05

Multi-Hop Provenance Collapse

What to watch: When a claim requires evidence from multiple documents (e.g., a policy and an amendment), the chain collapses into a single-hop citation, omitting the amendment that modifies the original clause. The audit trail is incomplete. Guardrail: Prompt the model to enumerate all documents required to fully support a claim before building the chain. Add a 'completeness check' that asks: 'Does this claim depend on any other document not yet cited?'

06

Human Override Omission

What to watch: A human reviewer corrects or supplements a citation, but the provenance chain does not record the override. The audit log shows only the original model output, creating a false record of automated accuracy. Guardrail: Design the provenance chain schema to include an 'override' node type with mandatory fields for reviewer ID, timestamp, and reason. Never allow human edits to silently replace model-generated chain steps.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Source Provenance Chain Prompt before shipping to production. Each criterion targets a specific failure mode in provenance tracking, from broken retrieval links to missing audit metadata.

CriterionPass StandardFailure SignalTest Method

Provenance Link Completeness

Every claim in the output has a non-null provenance entry linking it to a retrieval step, chunk ID, and document source

Claims appear without provenance entries, or provenance entries contain null values for retrieval step or chunk ID

Parse output JSON and assert that for every claim in the claims array, there exists a corresponding entry in the provenance_chain array with non-null retrieval_step, chunk_id, and document_source fields

Retrieval Step Traceability

Each provenance entry includes a retrieval_step that matches an actual step in the retrieval log with query text, timestamp, and result count

Retrieval steps reference queries or timestamps not present in the provided retrieval log, or omit required fields

Cross-reference each provenance entry's retrieval_step against the input retrieval_log array; assert exact match on step_id and query_text

Chunk Selection Justification

Each provenance entry includes a chunk_selection_reason that explains why the specific chunk was chosen over other retrieved chunks

Chunk selection reasons are generic, missing, or identical across different claims with different evidence requirements

Sample 5 provenance entries and perform human review or LLM-as-judge check that chunk_selection_reason is claim-specific and references chunk content, not just position or score

Citation Boundary Accuracy

Each citation includes exact start_offset and end_offset within the chunk text that matches the supporting evidence span

Offsets point outside chunk boundaries, capture irrelevant text, or fail to match the cited evidence when extracted

Extract the cited span using start_offset and end_offset from the chunk text; assert that the extracted text contains the factual support for the claim and does not include unrelated sentences

Broken Link Detection

The output includes a completeness_check section that explicitly flags any claims where the provenance chain has gaps, missing steps, or unresolvable references

The completeness_check section reports no issues when provenance gaps exist, or flags false positives on intact chains

Inject test cases with deliberately broken provenance (missing retrieval step, chunk ID mismatch, offset out of bounds) and assert that completeness_check correctly identifies each injected gap

Confidence Score Calibration

Each provenance entry includes a confidence_score between 0.0 and 1.0 that correlates with evidence quality, not just retrieval score

Confidence scores are uniformly high despite weak evidence, or scores are missing for claims with partial support

Run 20 test cases with known evidence quality levels; assert that mean confidence for strong-evidence claims exceeds mean confidence for weak-evidence claims by at least 0.2

Audit Metadata Completeness

The output includes model_version, retrieval_config, timestamp, and any human_override fields required for audit trail reconstruction

Audit metadata fields are missing, contain placeholder values, or omit configuration details needed to reproduce the result

Validate output against a required audit schema; assert presence of model_version, retrieval_config.embedding_model, retrieval_config.top_k, timestamp in ISO 8601 format, and human_override as boolean

Cross-Document Reference Integrity

When provenance spans multiple documents, each document is uniquely identified and cross-references between documents are resolvable

Multiple documents share the same identifier, or a provenance entry references a document_id not present in the input document set

Extract all unique document_id values from provenance entries; assert each maps to exactly one document in the input set and that cross-reference fields use valid document_id values

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single retrieval step and simplified provenance fields. Replace the full chain with a flat mapping from claim to source chunk. Skip completeness checks and audit log formatting.

code
For each claim in [ANSWER], output:
- claim: [CLAIM_TEXT]
- source_chunk_id: [CHUNK_ID]
- document: [DOCUMENT_NAME]
- retrieval_query: [QUERY_USED]

Watch for

  • Missing intermediate retrieval steps when multiple queries were used
  • Chunk IDs that don't trace back to original documents
  • No detection of broken provenance links
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.