Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
AI & Machine Learning

Implementing Passage-Level Attribution in RAG: Mapping LLM Claims to Specific Source Sentences with Span Highlighting and Confidence Thresholds

Document-level citations aren't enough for high-stakes RAG deployments. Learn how to decompose LLM responses into atomic claims, match them to specific source sentences with dual-signal confidence scoring, and render highlighted attributions with calibrated thresholds — all in production-ready Python.

⚡ Practitioner22 min readDec 4, 2026Updated Dec 4, 2026
Implementing Passage-Level Attribution in RAG: Mapping LLM Claims to Specific Source Sentences with Span Highlighting and Confidence Thresholds
On this page
  • Introduction
  • Prerequisites
  • The Attribution Problem, Precisely Stated
  • Step 1: Decomposing LLM Responses into Atomic Claims
  • Step 2: Sentence Segmentation and Span Indexing of Retrieved Chunks
  • Step 3: Claim-to-Span Matching with Confidence Scoring
  • Step 4: Setting and Calibrating Confidence Thresholds
  • Step 5: Rendering Span Highlights
  • Putting It All Together: The Attribution Pipeline
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Attributing synthesized claims to fragments
  • Mistake 2: spaCy sentence boundaries in legal or technical text
  • Mistake 3: Embedding the same spans repeatedly across requests
  • Mistake 4: Ignoring multi-claim-to-one-span collisions
  • Summary & Next Steps

Implementing Passage-Level Attribution in RAG: Mapping LLM Claims to Specific Source Sentences with Span Highlighting and Confidence Thresholds

Introduction

You've built a RAG pipeline. It retrieves relevant chunks, stuffs them into a prompt, and the LLM synthesizes a coherent answer. Users are happy — until one day someone asks, "Where exactly does that claim come from?" and you realize your system can only point to a chunk of 500 tokens. That's not attribution. That's a suggestion.

Document-level or chunk-level citations are table stakes. If you're deploying RAG in legal, medical, financial, or any compliance-sensitive domain, you need to go further: you need to know which sentence in the source text supports which claim in the generated response. This is passage-level attribution — the ability to draw a line from a specific LLM output claim back to the exact sentence or span in a source document that justifies it, complete with a confidence score so you can decide whether to surface it or suppress it.

By the end of this article, you'll be able to implement a complete passage-level attribution system on top of an existing RAG pipeline. You'll build a claim extractor, a sentence-level span matcher, a confidence scorer, and a lightweight renderer that highlights supporting text. This is production-oriented work: you'll handle the messy cases, understand the failure modes, and leave with code you can actually deploy.

What you'll learn:

  • How to decompose LLM responses into atomic claims suitable for attribution
  • How to segment retrieved chunks into sentence-level spans and index them for matching
  • How to score claim-to-span alignment using a combination of semantic similarity and lexical overlap
  • How to apply confidence thresholds to decide which attributions to surface and which to suppress
  • How to render span-highlighted attributions in a format usable by a frontend or audit log

Prerequisites

You should already be comfortable building RAG pipelines end-to-end. If not, Building Your First RAG Pipeline and RAG Fundamentals will get you there first. You should understand chunk retrieval, vector similarity, and how prompts are structured for grounding — if you need a refresher on the prompt design side, Prompt Engineering for RAG covers that well. You'll need familiarity with Python, sentence-transformers, and either OpenAI's API or a local LLM.

Dependencies for this lesson:

pip install sentence-transformers spacy openai nltk scikit-learn
python -m spacy download en_core_web_sm

The Attribution Problem, Precisely Stated

Let's be specific about what we're solving before we write a line of code.

A typical RAG pipeline passes retrieved chunks to an LLM and gets back a synthesized answer. The LLM might draw on three different chunks and blend information from all of them into a single paragraph. Your current citation might look like this:

"The interest rate on Series I bonds adjusts every six months based on inflation. [Source: Treasury FAQ, chunk 3]"

The problem is that "chunk 3" might be 400 words long. You can't highlight what matters. You can't programmatically verify that the specific claim about six-month adjustments is actually stated in that chunk versus inferred or hallucinated. And you can't distinguish between high-confidence attributions (the sentence is basically quoted) and low-confidence ones (the LLM synthesized something loosely related).

Passage-level attribution means resolving this down to the sentence level:

"The interest rate on Series I bonds adjusts every six months based on inflation."
→ Source: Treasury FAQ, paragraph 4, sentence 2 — "I bond earnings rates change every 6 months." — Confidence: 0.84

That's what we're building. It requires three things working together:

  1. Claim decomposition: breaking the LLM's response into atomic, attributable units
  2. Span indexing: segmenting and indexing source text at the sentence level
  3. Attribution scoring: finding the best-matching span for each claim and scoring that match

Key insight

Most hallucinations are not outright fabrications — they're plausible extrapolations from real retrieved text. Passage-level attribution is what lets you detect the gap between what the source says and what the LLM claims. That's why this matters for faithfulness evaluation as well as citation.


Step 1: Decomposing LLM Responses into Atomic Claims

An LLM response is a composite object. A single paragraph might contain six distinct factual claims blended together. You cannot do attribution on prose — you need to decompose it first.

The cleanest approach is to ask an LLM to do this decomposition for you, using a structured output prompt. Here's a reusable claim extractor:

import openai
import json
from dataclasses import dataclass
from typing import List

@dataclass
class Claim:
    text: str
    claim_id: int
    source_sentence_range: tuple  # character offsets in the original response

def extract_claims(response_text: str, client: openai.OpenAI) -> List[Claim]:
    """
    Decomposes an LLM response into atomic, attributable claims.
    Each claim should be verifiable against a single source sentence.
    """
    system_prompt = """You are a fact decomposition assistant. 
    Given a paragraph of text, extract every distinct factual claim as a separate item.
    Each claim must be:
    - Self-contained (understandable without the surrounding text)
    - Atomic (makes exactly one assertion)
    - Declarative (a statement of fact, not a question or instruction)
    
    Return a JSON array of strings. Example:
    ["The bond rate adjusts every six months.", "Adjustments are tied to CPI-U inflation data."]
    """
    
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": f"Decompose this text into atomic claims:\n\n{response_text}"}
        ],
        response_format={"type": "json_object"},
        temperature=0
    )
    
    raw = json.loads(response.choices[0].message.content)
    # Handle both {"claims": [...]} and direct array responses
    claims_list = raw.get("claims", raw) if isinstance(raw, dict) else raw
    
    return [
        Claim(text=claim_text, claim_id=i, source_sentence_range=(0, 0))
        for i, claim_text in enumerate(claims_list)
    ]

Tip

Use gpt-4o-mini or a similarly cheap model for this decomposition step — it's a simple structural task that doesn't require the full power of GPT-4. If you're calling the attribution pipeline at high volume, this keeps costs manageable. For structured output contracts like this, always validate the shape of the returned JSON before proceeding.

Let's see what this produces on a realistic example. Suppose the user asked about Series I bonds and the LLM returned:

"Series I bonds are a type of U.S. savings bond designed to protect against inflation. 
The composite interest rate consists of a fixed rate and an inflation rate. 
The inflation component adjusts every six months based on changes in the Consumer Price Index 
for all Urban Consumers (CPI-U). I bonds can be purchased through TreasuryDirect.gov or in 
paper form using a tax refund."

The decomposed claims would be:

  1. "Series I bonds are a type of U.S. savings bond."
  2. "Series I bonds are designed to protect against inflation."
  3. "The composite interest rate consists of a fixed rate and an inflation rate."
  4. "The inflation component adjusts every six months."
  5. "The adjustment is based on changes in the CPI-U."
  6. "I bonds can be purchased through TreasuryDirect.gov."
  7. "I bonds can be purchased in paper form using a tax refund."

Seven attributable claims from four sentences of output. This granularity is what makes span-level attribution possible.


Step 2: Sentence Segmentation and Span Indexing of Retrieved Chunks

Now we need to prepare the retrieval side. The standard RAG pipeline retrieves chunks (say, 300–500 tokens each). We need to further segment those chunks into individual sentences and store their character offsets so we can highlight them precisely.

import spacy
from dataclasses import dataclass, field
from typing import List, Dict

nlp = spacy.load("en_core_web_sm")

@dataclass
class SourceSpan:
    text: str
    start_char: int        # offset within the chunk
    end_char: int
    chunk_id: str          # which retrieved chunk this came from
    document_id: str       # the source document
    sentence_index: int    # position within the chunk

@dataclass  
class IndexedChunk:
    chunk_id: str
    document_id: str
    full_text: str
    spans: List[SourceSpan] = field(default_factory=list)

def index_chunk_into_spans(
    chunk_text: str,
    chunk_id: str,
    document_id: str
) -> IndexedChunk:
    """
    Segments a retrieved chunk into sentence-level spans with character offsets.
    """
    doc = nlp(chunk_text)
    indexed = IndexedChunk(
        chunk_id=chunk_id,
        document_id=document_id,
        full_text=chunk_text
    )
    
    for i, sent in enumerate(doc.sents):
        # Strip leading/trailing whitespace but preserve offsets
        sent_text = sent.text.strip()
        if len(sent_text) < 10:  # skip fragments, headers, lone punctuation
            continue
            
        indexed.spans.append(SourceSpan(
            text=sent_text,
            start_char=sent.start_char,
            end_char=sent.end_char,
            chunk_id=chunk_id,
            document_id=document_id,
            sentence_index=i
        ))
    
    return indexed

def index_retrieved_chunks(retrieved_chunks: List[Dict]) -> List[IndexedChunk]:
    """
    Takes a list of retrieved chunks (as from a vector store query) 
    and returns span-indexed versions.
    
    retrieved_chunks format: [{"id": str, "document_id": str, "text": str}, ...]
    """
    return [
        index_chunk_into_spans(
            chunk_text=chunk["text"],
            chunk_id=chunk["id"],
            document_id=chunk["document_id"]
        )
        for chunk in retrieved_chunks
    ]

Warning

SpaCy's sentence segmenter performs well on clean prose but struggles with heavily formatted text — bullet points, tables, code blocks. If your documents contain structured content, consider pre-processing with a rule-based splitter for non-prose sections before passing to spaCy. This is especially relevant if you're working with document ingestion pipelines that handle heterogeneous content.

After indexing, a 400-token chunk might become 8–12 SourceSpan objects, each with precise character offsets. These are your attribution targets.


Step 3: Claim-to-Span Matching with Confidence Scoring

This is the core of the system. For each extracted claim, we need to find the best-matching span across all retrieved chunks, and score that match well enough to decide whether to surface it.

We'll use a two-signal approach: semantic similarity (embedding cosine distance) and lexical overlap (token-level F1). Neither signal alone is sufficient:

  • Semantic similarity alone can match a claim to a span that talks about the same topic but doesn't actually support the specific claim
  • Lexical overlap alone misses paraphrases, synonyms, and reformulations that the LLM commonly produces

The combined score is more robust than either individually.

import numpy as np
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.tokenize import word_tokenize
import nltk
nltk.download('punkt', quiet=True)

# Load once at module level — this model is fast and good for this task
embedder = SentenceTransformer("all-MiniLM-L6-v2")

def compute_token_f1(claim: str, span: str) -> float:
    """
    Computes token-level F1 between claim and span.
    This is the same metric used in SQuAD evaluation.
    Handles common words as noise by ignoring stopwords.
    """
    STOPWORDS = {"the", "a", "an", "is", "are", "was", "were", "be", "been",
                 "being", "have", "has", "had", "do", "does", "did", "will",
                 "would", "could", "should", "may", "might", "of", "in", "on",
                 "at", "to", "for", "with", "by", "from", "and", "or", "but"}
    
    claim_tokens = set(word_tokenize(claim.lower())) - STOPWORDS
    span_tokens = set(word_tokenize(span.lower())) - STOPWORDS
    
    if not claim_tokens or not span_tokens:
        return 0.0
    
    common = claim_tokens & span_tokens
    precision = len(common) / len(claim_tokens)
    recall = len(common) / len(span_tokens)
    
    if precision + recall == 0:
        return 0.0
    
    return 2 * precision * recall / (precision + recall)

@dataclass
class AttributionResult:
    claim: Claim
    matched_span: SourceSpan
    semantic_score: float
    lexical_score: float
    combined_score: float
    is_attributed: bool  # whether combined_score >= threshold

def score_claim_against_spans(
    claim: Claim,
    all_spans: List[SourceSpan],
    span_embeddings: np.ndarray,
    semantic_weight: float = 0.7,
    lexical_weight: float = 0.3,
    confidence_threshold: float = 0.5
) -> AttributionResult:
    """
    Finds the best-matching span for a claim and returns a scored attribution.
    
    span_embeddings: pre-computed embeddings for all spans (N x D matrix)
    Returns the top match with combined score.
    """
    # Embed the claim
    claim_embedding = embedder.encode([claim.text])
    
    # Semantic similarity: cosine between claim and all spans
    semantic_scores = cosine_similarity(claim_embedding, span_embeddings)[0]
    
    # Lexical scores: token F1 for all spans
    lexical_scores = np.array([
        compute_token_f1(claim.text, span.text) 
        for span in all_spans
    ])
    
    # Combined score
    combined_scores = (
        semantic_weight * semantic_scores + 
        lexical_weight * lexical_scores
    )
    
    best_idx = int(np.argmax(combined_scores))
    best_span = all_spans[best_idx]
    
    return AttributionResult(
        claim=claim,
        matched_span=best_span,
        semantic_score=float(semantic_scores[best_idx]),
        lexical_score=float(lexical_scores[best_idx]),
        combined_score=float(combined_scores[best_idx]),
        is_attributed=combined_scores[best_idx] >= confidence_threshold
    )

def attribute_response(
    claims: List[Claim],
    indexed_chunks: List[IndexedChunk],
    confidence_threshold: float = 0.5
) -> List[AttributionResult]:
    """
    Main attribution function. Takes extracted claims and indexed chunks,
    returns a scored attribution for every claim.
    """
    # Flatten all spans
    all_spans = [
        span 
        for chunk in indexed_chunks 
        for span in chunk.spans
    ]
    
    if not all_spans:
        raise ValueError("No spans found in retrieved chunks — check your indexing step.")
    
    # Pre-compute all span embeddings in one batch (much faster than one-by-one)
    span_texts = [span.text for span in all_spans]
    span_embeddings = embedder.encode(span_texts, batch_size=64, show_progress_bar=False)
    
    return [
        score_claim_against_spans(
            claim=claim,
            all_spans=all_spans,
            span_embeddings=span_embeddings,
            confidence_threshold=confidence_threshold
        )
        for claim in claims
    ]

Key insight

Pre-computing span embeddings once per query (rather than per claim) is essential for performance. If you have 10 retrieved chunks with 10 sentences each, that's 100 spans. Computing embeddings 7 times (once per claim) instead of 700 times (once per claim-span pair) is a 7x speedup, and it scales linearly with the number of claims.


Step 4: Setting and Calibrating Confidence Thresholds

The confidence threshold is not a hyperparameter you set once and forget. It's a policy decision that trades off two error modes:

  • Too low a threshold: you attribute claims to spans that don't actually support them. Users see confident citations pointing to irrelevant text. Trust erodes.
  • Too high a threshold: you suppress valid attributions. The system says "no source found" for claims that are supported. Utility drops.

Here's how to calibrate thresholds empirically on a small labeled set:

from dataclasses import dataclass
from typing import List, Tuple
import numpy as np

@dataclass
class ThresholdAnalysis:
    threshold: float
    precision: float
    recall: float
    f1: float
    coverage: float  # fraction of claims that get attributed

def analyze_threshold_curve(
    attribution_results: List[AttributionResult],
    ground_truth_labels: List[bool],  # True = this claim actually IS supported by matched span
    thresholds: List[float] = None
) -> List[ThresholdAnalysis]:
    """
    Given attribution results and human labels, compute precision/recall
    at different threshold values to find the optimal operating point.
    """
    if thresholds is None:
        thresholds = [round(t, 2) for t in np.arange(0.3, 0.9, 0.05)]
    
    scores = [r.combined_score for r in attribution_results]
    analyses = []
    
    for threshold in thresholds:
        predicted_attributed = [s >= threshold for s in scores]
        
        tp = sum(p and g for p, g in zip(predicted_attributed, ground_truth_labels))
        fp = sum(p and not g for p, g in zip(predicted_attributed, ground_truth_labels))
        fn = sum(not p and g for p, g in zip(predicted_attributed, ground_truth_labels))
        
        precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
        recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
        f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
        coverage = sum(predicted_attributed) / len(predicted_attributed)
        
        analyses.append(ThresholdAnalysis(
            threshold=threshold,
            precision=precision,
            recall=recall,
            f1=f1,
            coverage=coverage
        ))
    
    return analyses

def select_threshold(
    analyses: List[ThresholdAnalysis],
    min_precision: float = 0.85  # your business requirement
) -> float:
    """
    Select the lowest threshold that meets your precision requirement.
    This maximizes recall (and coverage) while holding precision above the floor.
    """
    valid = [a for a in analyses if a.precision >= min_precision]
    if not valid:
        raise ValueError(f"No threshold achieves precision >= {min_precision}. "
                         f"Check your scoring approach or loosen requirements.")
    
    # Lowest threshold that meets precision = highest recall
    return min(valid, key=lambda a: a.threshold).threshold

In practice, the right precision floor depends on your use case. For a legal research tool where a wrong citation is a serious problem, you might set min_precision=0.92. For an internal knowledge base assistant where convenience matters more, 0.75 might be fine.

Note

These thresholds should be calibrated per domain, not globally. A threshold that works well for clean prose in a corporate policy document will likely be wrong for scientific abstracts with dense technical language. If you're deploying across multiple document types, consider maintaining separate threshold configs per document category — this is closely related to metadata filtering strategies you may already have in your pipeline.


Step 5: Rendering Span Highlights

Attribution scores mean nothing if you can't surface them. Let's build two renderers: one for a plain-text audit log, and one that produces HTML with inline <mark> highlights suitable for a frontend.

from typing import List, Optional
import html

def render_attribution_as_text(
    response_text: str,
    attributions: List[AttributionResult],
    show_unattributed: bool = True
) -> str:
    """
    Renders a human-readable attribution report for logging and audit.
    """
    lines = ["=== ATTRIBUTION REPORT ===\n", f"Response: {response_text}\n", "--- Claims ---"]
    
    for attr in attributions:
        status = "✓ ATTRIBUTED" if attr.is_attributed else "✗ UNATTRIBUTED"
        lines.append(f"\n[{attr.claim.claim_id}] {status}")
        lines.append(f"  Claim: {attr.claim.text}")
        
        if attr.is_attributed:
            lines.append(f"  Source: {attr.matched_span.document_id} "
                        f"(chunk {attr.matched_span.chunk_id}, "
                        f"sentence {attr.matched_span.sentence_index})")
            lines.append(f"  Matching span: \"{attr.matched_span.text}\"")
            lines.append(f"  Confidence: {attr.combined_score:.3f} "
                        f"(semantic={attr.semantic_score:.3f}, "
                        f"lexical={attr.lexical_score:.3f})")
        elif show_unattributed:
            lines.append(f"  Best candidate: \"{attr.matched_span.text}\"")
            lines.append(f"  Best score: {attr.combined_score:.3f} (below threshold)")
    
    return "\n".join(lines)

def render_attribution_as_html(
    retrieved_chunks: List[dict],
    indexed_chunks: List[IndexedChunk],
    attributions: List[AttributionResult],
    confidence_threshold: float = 0.5
) -> str:
    """
    Produces HTML where attributed spans are highlighted in the source text.
    Color intensity reflects confidence score.
    
    Returns a full HTML snippet for embedding in a document viewer.
    """
    # Build a lookup: (chunk_id, sentence_index) -> attribution result
    span_to_attribution = {}
    for attr in attributions:
        if attr.is_attributed:
            key = (attr.matched_span.chunk_id, attr.matched_span.sentence_index)
            # Keep highest-confidence attribution if multiple claims point to same span
            if key not in span_to_attribution or attr.combined_score > span_to_attribution[key].combined_score:
                span_to_attribution[key] = attr
    
    html_parts = ['<div class="attribution-view">']
    
    for chunk in indexed_chunks:
        html_parts.append(f'<div class="source-chunk" data-chunk-id="{html.escape(chunk.chunk_id)}">')
        html_parts.append(f'<div class="chunk-header">Source: {html.escape(chunk.document_id)}</div>')
        html_parts.append('<div class="chunk-body">')
        
        # Reconstruct the chunk text with highlights applied
        chunk_text = chunk.full_text
        
        # Collect all spans with their attributions, sorted by start position
        highlighted_spans = []
        for span in chunk.spans:
            key = (span.chunk_id, span.sentence_index)
            if key in span_to_attribution:
                attr = span_to_attribution[key]
                highlighted_spans.append((span.start_char, span.end_char, attr.combined_score, attr.claim.claim_id))
        
        highlighted_spans.sort(key=lambda x: x[0])
        
        # Build highlighted HTML
        last_pos = 0
        for start, end, score, claim_id in highlighted_spans:
            # Text before this span
            if start > last_pos:
                html_parts.append(html.escape(chunk_text[last_pos:start]))
            
            # Confidence-based opacity (0.3 to 1.0 range)
            opacity = 0.3 + 0.7 * min(score, 1.0)
            html_parts.append(
                f'<mark class="attribution-highlight" '
                f'data-claim-id="{claim_id}" '
                f'data-confidence="{score:.3f}" '
                f'style="background-color: rgba(255, 220, 0, {opacity:.2f}); '
                f'cursor: pointer;" '
                f'title="Supports claim {claim_id} (confidence: {score:.2f})">'
                f'{html.escape(chunk_text[start:end])}</mark>'
            )
            last_pos = end
        
        # Remaining text
        if last_pos < len(chunk_text):
            html_parts.append(html.escape(chunk_text[last_pos:]))
        
        html_parts.append('</div></div>')  # close chunk-body, source-chunk
    
    html_parts.append('</div>')
    return "\n".join(html_parts)

The HTML output uses data attributes (data-claim-id, data-confidence) that a frontend can use to build interactive features — hover to see the full claim, click to jump between claims and their sources.


Putting It All Together: The Attribution Pipeline

Now let's wire all the pieces into a single callable function that you can drop into an existing RAG pipeline:

from typing import Optional
import openai

def run_attribution_pipeline(
    query: str,
    llm_response: str,
    retrieved_chunks: List[dict],
    openai_client: openai.OpenAI,
    confidence_threshold: float = 0.52,
    output_format: str = "text"  # "text" | "html" | "structured"
):
    """
    Full attribution pipeline. Takes query context and returns attributed response.
    
    retrieved_chunks: [{"id": str, "document_id": str, "text": str}, ...]
    output_format: 
        "text" -> plain-text audit report
        "html" -> highlighted HTML for rendering
        "structured" -> raw AttributionResult list for downstream use
    """
    print(f"Extracting claims from {len(llm_response.split())} word response...")
    claims = extract_claims(llm_response, openai_client)
    print(f"  → {len(claims)} atomic claims extracted")
    
    print(f"Indexing {len(retrieved_chunks)} chunks into sentence spans...")
    indexed_chunks = index_retrieved_chunks(retrieved_chunks)
    total_spans = sum(len(c.spans) for c in indexed_chunks)
    print(f"  → {total_spans} sentence spans indexed")
    
    print(f"Running attribution scoring (threshold={confidence_threshold})...")
    attributions = attribute_response(claims, indexed_chunks, confidence_threshold)
    
    attributed_count = sum(1 for a in attributions if a.is_attributed)
    print(f"  → {attributed_count}/{len(claims)} claims attributed above threshold")
    
    if output_format == "structured":
        return attributions
    elif output_format == "html":
        return render_attribution_as_html(
            retrieved_chunks, indexed_chunks, attributions, confidence_threshold
        )
    else:
        return render_attribution_as_text(llm_response, attributions)

Tip

In production, you'll want to run the attribution pipeline asynchronously from the main RAG response — stream the LLM answer to the user immediately, then backfill the attribution data once it's computed. This avoids adding 300–500ms of latency to every response from the user's perspective. The attribution result can be delivered as a second payload or populated progressively in the UI.


Hands-On Exercise

Apply everything you've learned by building an attribution layer for a document Q&A scenario.

Scenario: You have a 10-page employee handbook (use any multi-section text you have available, or fetch a public one). A user asks: "Can I carry over unused vacation days, and if so, how many?"

Your task:

  1. Build a simple RAG pipeline that retrieves the top 3 chunks from the handbook using a vector store of your choice (see Vector Databases Compared for options).

  2. Generate a 2–3 sentence response using an LLM.

  3. Run the full attribution pipeline on the response with a threshold of 0.5.

  4. Evaluate the attributions manually: does each attributed span actually support the corresponding claim?

  5. Adjust the threshold up or down until you're satisfied with precision, then document your reasoning.

Extension challenge: Add a "conflict detection" step that flags when two claims in the response are attributed to different source spans that appear to contradict each other. This is a common quality signal in faithfulness evaluation — if you're interested in going deeper, Evaluating RAG Systems: Precision, Recall, and Faithfulness covers the broader evaluation framework.


Common Mistakes & Troubleshooting

Mistake 1: Attributing synthesized claims to fragments

What happens: The LLM synthesizes a claim like "The policy was last updated following the 2023 regulatory changes" — a reasonable inference from two separate retrieved spans. Your attribution system finds a decent match in one of them (score 0.61) and surfaces it as a confident citation, but the span doesn't actually say that.

Fix: For synthesized or inferential claims, your semantic similarity score will tend to be moderate but your lexical F1 will be low (because the specific wording doesn't appear in any source). Add a rule: if lexical_score < 0.1 and semantic_score > 0.5, flag the attribution as "inferred" rather than "supported" — these are the claims most likely to reflect LLM hallucination rather than direct grounding.

def classify_attribution_type(attr: AttributionResult) -> str:
    if not attr.is_attributed:
        return "unattributed"
    elif attr.lexical_score < 0.1 and attr.semantic_score > 0.45:
        return "inferred"  # topically related but not textually grounded
    elif attr.lexical_score >= 0.3:
        return "direct"    # strong lexical overlap — likely quoted or paraphrased
    else:
        return "supported" # semantically aligned, some lexical match

Mistake 2: spaCy sentence boundaries in legal or technical text

What happens: spaCy splits "See §14.2(b)(iii). This provision applies..." as one sentence instead of two, or splits mid-abbreviation on "Corp. v. Smith" creating fragments.

Fix: For legal text, use a custom sentence boundary component or a rules-based fallback:

def robust_sentence_split(text: str) -> List[Tuple[str, int, int]]:
    """Fallback sentence splitter that handles legal/technical text."""
    import re
    # Sentence boundary: period/question/exclamation followed by whitespace + capital
    # but NOT after common abbreviations
    abbrevs = r"(?<!Inc)(?<!Corp)(?<!Ltd)(?<!Dr)(?<!Mr)(?<!Mrs)(?<!vs)(?<!§)"
    pattern = abbrevs + r"(?<=[.!?])\s+(?=[A-Z])"
    
    parts = re.split(pattern, text)
    spans = []
    pos = 0
    for part in parts:
        part = part.strip()
        if len(part) > 10:
            start = text.find(part, pos)
            spans.append((part, start, start + len(part)))
            pos = start + len(part)
    return spans

Mistake 3: Embedding the same spans repeatedly across requests

What happens: Every query recomputes embeddings for the same source document sentences. If you're running 50 queries per hour against a 100-page handbook that hasn't changed, you're wasting significant compute.

Fix: Pre-compute and cache span embeddings at ingestion time, keyed by a hash of the span text. Store them alongside the vector store. This is especially important at scale — it's worth reviewing Retrieval Latency Optimization for the broader caching strategy.

import hashlib
import pickle
from pathlib import Path

def get_or_compute_embeddings(spans: List[SourceSpan], cache_dir: str = ".span_cache") -> np.ndarray:
    Path(cache_dir).mkdir(exist_ok=True)
    span_texts = [s.text for s in spans]
    cache_key = hashlib.md5("|".join(span_texts).encode()).hexdigest()
    cache_path = Path(cache_dir) / f"{cache_key}.pkl"
    
    if cache_path.exists():
        with open(cache_path, "rb") as f:
            return pickle.load(f)
    
    embeddings = embedder.encode(span_texts, batch_size=64, show_progress_bar=False)
    with open(cache_path, "wb") as f:
        pickle.dump(embeddings, f)
    
    return embeddings

Mistake 4: Ignoring multi-claim-to-one-span collisions

What happens: Seven claims in the LLM response all point to the same sentence in the source (the most topically salient one). The other sentences receive no citations. The rendering shows one aggressively highlighted sentence and 6 "unattributed" claims.

Fix: After attribution, apply a soft coverage constraint — if more than 3 claims map to the same span, re-evaluate the lower-confidence ones against their second-best candidates. This distributes attribution more fairly and usually catches genuine secondary sources.

Warning

Don't over-correct this — if a span is genuinely the best match for multiple claims, force-distributing attribution to weaker matches introduces false citations. The goal is to surface the collision for review, not to automatically reassign.


Summary & Next Steps

You've built a complete passage-level attribution system: claim decomposition via LLM, sentence-level span indexing with character offsets, dual-signal confidence scoring (semantic + lexical), threshold calibration, and two rendering formats for audit and display.

The key ideas to carry forward:

  • Attribution requires decomposition first. You can't attribute prose to spans — you need atomic claims as your unit of work.
  • Two signals beat one. Semantic similarity catches paraphrases; lexical F1 catches direct grounding. Neither alone produces reliable confidence scores.
  • Thresholds are policy, not hyperparameters. Calibrate them against labeled examples, by domain, and revisit them when your document types change.
  • The unattributed claims are the signal. A claim that scores below threshold is a hallucination candidate — this is valuable data for evaluating faithfulness and for corrective RAG pipelines that catch bad retrievals before they reach the user.

Where to go from here:

  • Integrate this attribution layer with a reranking step — if you're using cross-encoders as described in Reranking Retrieved Results, you can reuse the cross-encoder score as a third attribution signal.
  • Extend to multi-hop attributions for answers that genuinely require synthesizing across multiple documents — this connects directly to Graph RAG if your knowledge is relationship-structured.
  • Use low-attribution rates as a monitoring signal in production. If a session consistently returns claims with scores below 0.4, something is wrong upstream — either retrieval is failing, the query is out of domain, or chunking is fragmented. This feeds naturally into Production RAG monitoring.
Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

RAG & AI Agents

Previous

What Is a Vector Embedding? How AI Converts Text into Numbers You Can Search

Related Insights

AI & Machine LearningFoundation

Scheduling and Triggering LLM Jobs with Cron, Task Queues, and Event-Driven Pipelines

18 min
AI & Machine LearningFoundation

How to Use AI Tools at Work: A Practical Guide to ChatGPT, Claude, and Copilot for Everyday Business Tasks

19 min
AI & Machine LearningFoundation

What Is a Vector Embedding? How AI Converts Text into Numbers You Can Search

17 min

On this page

  • Introduction
  • Prerequisites
  • The Attribution Problem, Precisely Stated
  • Step 1: Decomposing LLM Responses into Atomic Claims
  • Step 2: Sentence Segmentation and Span Indexing of Retrieved Chunks
  • Step 3: Claim-to-Span Matching with Confidence Scoring
  • Step 4: Setting and Calibrating Confidence Thresholds
  • Step 5: Rendering Span Highlights
  • Putting It All Together: The Attribution Pipeline
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Attributing synthesized claims to fragments
  • Mistake 2: spaCy sentence boundaries in legal or technical text
  • Mistake 3: Embedding the same spans repeatedly across requests
  • Mistake 4: Ignoring multi-claim-to-one-span collisions
  • Summary & Next Steps