Inferensys

Prompt

Source Document Grounding Scorecard Prompt

A practical prompt playbook for using Source Document Grounding Scorecard 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

Defines the ideal operational context for the Source Document Grounding Scorecard Prompt, clarifying its role in offline trace analysis and when it should not be used.

This prompt is designed for offline trace analysis and automated evaluation workflows, not for real-time user-facing responses. Its primary job is to produce a structured, per-document grounding scorecard by comparing a final generated output against the full list of retrieved documents captured in a production trace. The ideal user is a RAG developer, quality engineer, or AI reliability engineer who needs to populate retrieval quality dashboards, debug hallucination root causes, or generate structured evidence for eval pipelines. It assumes you already have a production trace containing the generated output, the list of retrieved documents with their content, and trace event identifiers.

Use this prompt when you need to answer specific diagnostic questions: Which retrieved documents were actually used in the final answer? Were they used faithfully, or was their content distorted? Which documents were ignored entirely, and was that a correct decision? The output is a per-document scorecard classifying each source as Used Faithfully, Used Partially, Used Unfaithfully, or Ignored, with a brief justification anchored to the trace. This structured output is ideal for feeding into monitoring dashboards, triggering alerts when grounding fidelity drops, or building datasets for fine-tuning retrieval and generation models.

Do not use this prompt for real-time guardrails that block responses before they reach the user—its analysis is too detailed and latency-intensive for synchronous use. It is also not a replacement for human review in high-risk domains like healthcare or legal applications; the scorecard should inform human judgment, not automate it. For live user-facing systems, pair this offline analysis with a lightweight, real-time faithfulness check. If your trace does not contain the full text of retrieved documents, this prompt will produce unreliable results because it cannot verify grounding against source content it cannot see. Ensure your tracing infrastructure captures complete document payloads before running this analysis.

PRACTICAL GUARDRAILS

Use Case Fit

The Source Document Grounding Scorecard is a diagnostic tool for RAG evaluation pipelines. It works best in structured, traceable environments and can mislead when applied to creative or conversational use cases.

01

Good Fit: Automated RAG Evaluation Pipelines

Use when: you have a production RAG system with structured traces capturing retrieved documents and final output. The scorecard automates per-document faithfulness checks at scale, feeding directly into retrieval quality dashboards and eval metrics. Guardrail: Ensure traces include document IDs, retrieval ranks, and full text spans to make scoring deterministic.

02

Bad Fit: Creative or Open-Ended Generation

Avoid when: the model is expected to synthesize, paraphrase, or draw novel inferences beyond the source material. The scorecard penalizes legitimate abstraction and may flag faithful synthesis as 'partially used' or 'unsupported.' Guardrail: Reserve this prompt for fact-dense, citation-required outputs such as compliance reports or technical answers.

03

Required Inputs: Trace Completeness

What to watch: The scorecard cannot function without a complete trace containing the user query, retrieved document set, and final generated output. Missing retrieval metadata or truncated context windows produce false negatives. Guardrail: Validate trace schema before scoring; abort with a clear error if required fields are absent.

04

Operational Risk: Scorecard Drift Over Time

What to watch: As retrieval pipelines, embedding models, or prompt versions change, the scorecard's calibration may drift. A document previously scored as 'faithfully used' might later be flagged due to subtle output phrasing changes. Guardrail: Run the scorecard against a golden holdout set weekly and track score distribution shifts as a monitoring metric.

05

Scale Risk: Cost and Latency at High Volume

What to watch: Scoring every document in every trace is token-intensive and can dominate your evaluation budget if applied indiscriminately. Guardrail: Sample traces strategically—prioritize high-risk query categories, low-confidence responses, or user-reported issues rather than scoring 100% of traffic.

06

Interpretation Risk: Over-Reliance on Aggregate Scores

What to watch: A high average grounding score can mask systematic failures in specific document types, query categories, or user segments. Guardrail: Always disaggregate scores by retrieval source, document type, and query cluster before declaring a system 'grounded.' A single aggregate number is insufficient for production decisions.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your evaluation harness to score each retrieved document on usage and faithfulness.

This prompt template is designed to be dropped directly into your RAG evaluation pipeline. It takes a production trace—containing the user query, the list of retrieved documents, and the final generated answer—and produces a per-document grounding scorecard. The scorecard classifies each document as used, partially used, or ignored, and then assesses whether its use was faithful (accurately represented) or unfaithful (distorted, hallucinated, or contradicted). The output is structured for direct ingestion into retrieval quality dashboards, allowing you to monitor the precision and recall of your retrieval step in terms of actual generation impact, not just vector similarity.

text
You are an expert retrieval-augmented generation (RAG) auditor. Your task is to analyze a production trace and produce a per-document grounding scorecard.

## INPUT DATA

[USER_QUERY]
[RETRIEVED_DOCUMENTS]
[GENERATED_ANSWER]

## TASK

For each document in [RETRIEVED_DOCUMENTS], perform the following analysis:

1.  **Usage Classification**: Determine if the document's content was used in [GENERATED_ANSWER].
    *   `used`: Specific claims or information from this document appear in the answer.
    *   `partially_used`: Some information was used, but other parts were ignored or a key point was missed.
    *   `ignored`: No information from this document is present in the answer.

2.  **Faithfulness Assessment**: If the document was `used` or `partially_used`, evaluate if its information was represented faithfully.
    *   `faithful`: The information in the answer accurately reflects the source document without distortion.
    *   `unfaithful`: The answer hallucinates details not in the document, contradicts the document, or misinterprets its core claim.
    *   `n/a`: For documents classified as `ignored`.

3.  **Evidence**: Provide a short, verbatim quote from the document and the corresponding sentence from the answer to justify your classification. If `ignored`, provide a quote from the document that was most relevant to the query but missed.

## OUTPUT FORMAT

Return a single JSON object with a key `"scorecard"` containing an array of objects. Each object must conform to this schema:

{
  "document_id": "string",
  "usage": "used" | "partially_used" | "ignored",
  "faithfulness": "faithful" | "unfaithful" | "n/a",
  "evidence": {
    "source_quote": "string",
    "answer_quote": "string"
  },
  "notes": "string (optional, for brief auditor commentary)"
}

## CONSTRAINTS

*   Base your analysis strictly on the provided [RETRIEVED_DOCUMENTS] and [GENERATED_ANSWER]. Do not use outside knowledge.
*   If the answer contains information not found in any document, note this in the `notes` field of the most relevant document or flag it as an overall issue in a final `ungrounded_claims` array.
*   Be precise with quotes. The `source_quote` and `answer_quote` must be verbatim substrings.
*   If [RETRIEVED_DOCUMENTS] is empty, return an empty `scorecard` array and a note.

To adapt this template, replace the square-bracket placeholders with data from your trace logger. [USER_QUERY] is the raw user input. [RETRIEVED_DOCUMENTS] should be a serialized list of objects, each with a unique document_id and content field. [GENERATED_ANSWER] is the final text output from your LLM. For high-stakes domains like healthcare or finance, the evidence field is critical; it creates a direct audit trail that a human reviewer can use to quickly verify the model's judgment. If your trace data includes retrieval scores or document metadata, consider appending it to the document content to give the auditor more context, but avoid bloating the prompt with non-essential fields that could distract from the grounding task.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Source Document Grounding Scorecard Prompt. Each variable must be populated from trace data before the prompt is assembled and sent.

PlaceholderPurposeExampleValidation Notes

[FINAL_OUTPUT]

The generated answer or claim text that needs grounding verification

The Acme 3000 release was in Q3 2023 and included the new flux capacitor.

Must be non-empty string. Truncate to 32K tokens if needed. Null triggers abort.

[RETRIEVED_DOCUMENTS]

Array of source documents retrieved during the RAG pipeline execution

[{doc_id: 'doc-1', content: '...', rank: 1, score: 0.92}]

Must be valid JSON array with at least one document. Each doc requires doc_id and content fields. Empty array triggers abstention score.

[TRACE_ID]

Unique identifier for the production trace being analyzed

trace-2025-03-15-0042-a1b2c3

Must match trace system format. Used for output lineage only. Null allowed if scoring offline.

[DOCUMENT_USAGE_THRESHOLD]

Minimum semantic overlap score to classify a document as partially used vs ignored

0.35

Float between 0.0 and 1.0. Default 0.3 if null. Values below 0.2 produce noisy usage labels.

[FAITHFULNESS_STRICTNESS]

Controls whether paraphrased or summarized use counts as faithful when exact quotes are absent

moderate

Must be one of: strict, moderate, lenient. Strict requires exact quote match. Lenient allows semantic equivalence. Invalid value defaults to moderate.

[OUTPUT_SCHEMA_VERSION]

Schema version for the scorecard output format

v2

Must match a supported schema version in the evaluation pipeline. Mismatch causes downstream parsing failures.

[MAX_DOCS_TO_SCORE]

Upper limit on number of retrieved documents to include in the scorecard

20

Integer between 1 and 100. Documents beyond this count are omitted with a truncation flag in output metadata.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Source Document Grounding Scorecard Prompt into an evaluation pipeline, observability dashboard, or continuous monitoring harness.

The Source Document Grounding Scorecard Prompt is designed to run as a post-generation evaluation step within a RAG trace pipeline. After a model produces a final answer and the trace captures the full set of retrieved documents, this prompt scores each document on two axes: usage (was the document used, partially used, or ignored in the final output?) and faithfulness (if used, did the output represent the document's content accurately?). The resulting per-document scorecard is a structured artifact that feeds directly into retrieval quality dashboards, allowing teams to monitor precision, recall, and hallucination signals at the document level rather than relying solely on aggregate answer-level metrics.

To integrate this prompt into an application harness, you must first ensure the trace contains the required inputs: the final generated output, the list of retrieved documents with their identifiers and full text, and any metadata about retrieval rank or source. The harness should iterate over each retrieved document, calling the prompt once per document or batching multiple documents into a single call if the model's context window permits. Validation is critical: parse the JSON output and confirm that each scorecard entry contains a valid usage_status (one of used, partially_used, ignored), a faithfulness object with a status field (faithful, partially_faithful, unfaithful, not_applicable), and a non-empty evidence array citing specific spans from both the document and the output. Reject malformed responses and retry with a stricter schema reminder. For high-stakes domains such as healthcare or legal review, route any document scored as unfaithful or partially_faithful to a human review queue before the scorecard is considered final.

Model choice matters for this evaluation task. Use a model with strong instruction-following and structured output capabilities (such as GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro) because the prompt requires precise span extraction and consistent JSON formatting. Avoid smaller or older models that may conflate partially_used with ignored or produce hallucinated evidence spans. Logging should capture the full prompt input, the raw model response, the parsed scorecard, and any validation failures for every document evaluated. Store these logs alongside the original trace so that dashboard queries can join retrieval decisions with grounding scores. Retries: if validation fails due to malformed JSON, retry once with an explicit error message appended to the prompt. If the retry also fails, flag the document as eval_error and exclude it from aggregate metrics rather than silently accepting a broken score. Tool use: this prompt does not require external tools, but the harness may call a separate span-extraction tool to verify that the cited evidence offsets actually exist in the source documents before trusting the faithfulness score.

For continuous monitoring, schedule this prompt to run on a sample of production traces (e.g., 10% of sessions or all traces flagged by a lightweight anomaly detector). Feed the resulting scorecards into a dashboard that tracks per-document grounding rates over time, broken down by retrieval source, document type, or prompt version. Set alerts on threshold breaches: for example, if the unfaithful rate exceeds 5% for any document source in a rolling window, trigger an investigation. Avoid running this prompt on every trace without sampling unless your cost and latency budget explicitly supports it—each trace may involve dozens of documents, and the evaluation cost can quickly exceed the generation cost. Start with sampled evaluation, validate that the scorecard correlates with user-reported issues, and then expand coverage based on observed failure patterns.

PRACTICAL GUARDRAILS

Common Failure Modes

When scoring source document grounding in RAG traces, these failures surface first. Each card identifies a specific breakdown and the operational guardrail to prevent it.

01

Citation Without Content Match

What to watch: The model cites a document, but the cited passage does not actually support the claim. This happens when the model learns to associate a source with a topic rather than verifying the specific content. Guardrail: Require the scorecard to extract the exact sentence or span from the source that supports each claim. Flag any citation where the extracted span is semantically unrelated to the generated statement.

02

Partial Use Presented as Full Support

What to watch: The model uses one fact from a document but writes as if the entire document endorses the output. This inflates perceived grounding quality and misleads downstream reviewers. Guardrail: Add a 'coverage' field to the scorecard that measures what percentage of the document's claims were actually used. Require explicit 'partially used' labels when the model cherry-picks facts while ignoring contradictory evidence in the same source.

03

Faithful Extraction, Unfaithful Synthesis

What to watch: Each individual fact is correctly extracted from a source, but the model combines them in a way that creates a new, unsupported conclusion. This is the hardest hallucination to catch because per-document scores look clean. Guardrail: Add a cross-document synthesis check to the scorecard. After scoring individual documents, evaluate whether the combined claim requires an inferential step not present in any single source. Flag multi-source aggregations for human review.

04

Ignored High-Relevance Documents

What to watch: The retriever surfaces a highly relevant document, but the model ignores it in favor of a less authoritative or partially relevant source. This signals a generation-time relevance mismatch. Guardrail: Include an 'ignored relevance' score for each retrieved document. If a document with high retrieval score is marked 'ignored' in the output, trigger a retrieval quality review. This often reveals context-window crowding or poor prompt prioritization.

05

Hallucinated Document Metadata

What to watch: The model fabricates document titles, dates, authors, or section headers that sound plausible but do not exist in the trace. This is common when the prompt asks for structured citations without strict schema enforcement. Guardrail: Cross-reference every metadata field in the generated citation against the trace's document object. The scorecard should include a 'metadata accuracy' boolean per citation. Reject any citation with hallucinated metadata before it reaches a user.

06

Scorecard Blindness to Near-Miss Matches

What to watch: The grounding scorecard marks a document as 'used' because the model referenced a related concept, but the actual claim is not supported. Near-miss semantic similarity fools simple overlap metrics. Guardrail: Implement a two-pass scoring approach. First, check for exact or near-exact span matches. Second, run a contradiction check: does the source say the opposite of the claim? Flag documents that are topically related but factually misaligned as 'near-miss, not supporting.'

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Source Document Grounding Scorecard Prompt before deploying it into a production RAG evaluation pipeline. Each criterion targets a specific failure mode in per-document grounding classification.

CriterionPass StandardFailure SignalTest Method

Per-Document Classification Completeness

Every document in the [RETRIEVED_DOCUMENTS] list receives exactly one classification label (used, partially_used, ignored)

Missing documents in output; multiple labels per document; unlabeled documents

Parse output JSON; assert len(classifications) == len(input_documents); assert no null labels

Classification Label Validity

All classification labels are from the allowed enum: used, partially_used, ignored

Labels outside enum appear (e.g., 'referenced', 'maybe_used', 'cited')

Validate each label against allowed enum set; reject unknown values

Faithfulness Flag Accuracy for 'used' Documents

Documents classified as 'used' have a faithfulness flag (faithful or unfaithful) with a specific unfaithfulness reason when unfaithful

Missing faithfulness flag on 'used' documents; flag present on 'ignored' documents; unfaithful without reason

Filter for label='used'; assert faithfulness_flag is not null; assert unfaithfulness_reason is not null when flag='unfaithful'

Evidence Span Traceability

Each classification includes at least one evidence_span from the document text or a null reason explaining absence

Missing evidence_span field; evidence_span text not found in source document; fabricated spans

For each classification, substring-search evidence_span in corresponding document text; flag misses

Output Schema Conformance

Output matches the [OUTPUT_SCHEMA] exactly: top-level array, required fields present, no extra fields, correct types

Missing required fields (document_id, classification, evidence_span); wrong types (string instead of array); extra undeclared fields

Validate against JSON Schema; reject on additionalProperties; check field types

Ignored Document Justification

Documents classified as 'ignored' include a specific reason (e.g., 'irrelevant_to_query', 'redundant_with_higher_ranked_doc', 'below_confidence_threshold')

Ignored documents lack reason; reason is generic placeholder like 'not used'; reason contradicts retrieval score

Filter for label='ignored'; assert ignore_reason is not null and not empty; check reason specificity

Partially Used Span Identification

Documents classified as 'partially_used' identify which specific spans were used and which were not, with rationale

Partially used documents lack used_spans or unused_spans; spans cover entire document; no rationale for partial use

Filter for label='partially_used'; assert used_spans array is not empty; assert unused_spans array is not empty; assert rationale field present

Cross-Document Consistency

No document is classified as both 'used' and 'ignored' across the scorecard; document_ids are unique and match input

Duplicate document_ids in output; conflicting classifications for same document; document_ids not in input set

Assert unique document_ids in output; assert set(output_ids) == set(input_ids); no duplicate entries

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a small batch of 5-10 traces. Skip strict schema enforcement and focus on whether the scorecard logic correctly distinguishes used, partially used, and ignored documents. Run against a frontier model with the full trace context inline.

code
[SYSTEM]: You are a grounding auditor. For each retrieved document in [TRACE], classify its usage as USED, PARTIALLY_USED, or IGNORED. If USED or PARTIALLY_USED, classify faithfulness as FAITHFUL, DISTORTED, or OVERCLAIMED.

Watch for

  • Overly generous USED classifications when the document was only topically related
  • Missing PARTIALLY_USED nuance when only one sentence was cited
  • No distinction between DISTORTED and OVERCLAIMED
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.