MODULE 02.2 · PUBLISHED · ~1-2h

Citations, Grounding & Abstention

Source-linked answers with inline citations, deterministic abstention when evidence is missing, claim-level grounding checks, and abstention precision/recall evaluation verified with pytest and GitHub Actions.

Retrieving relevant chunks is only half of a trustworthy RAG system. If the generation layer invents facts when context is missing, cites nonexistent chunk IDs, attaches a real citation to an unsupported claim, or slips extra unverified text around cited claims, users lose trust quickly.

In this module, you will build a deterministic, dependency-light grounded answering and verification layer covering inline chunk citations, abstention when evidence is missing, claim-level grounding, abstention verification, and answer-text consistency checks, plus abstention precision/recall evaluation verified with pytest and GitHub Actions.

What You Will Build

  • Grounded claim and response schemas: Represent retrieved evidence chunks, cited claims, grounded responses, abstention states, and evaluation cases with strict Pydantic v2 validation, non-blank string checks, finite float metrics, and edge-case count/metric consistency.
  • Deterministic grounded responder and abstention gate: Answer supported queries with inline [chunk_id] citations using chunk text when evidence meets a minimum support threshold, and abstain with a clear missing-evidence explanation when evidence is missing or below threshold.
  • Claim, abstention, and answer-text grounding verifier: Reject duplicate evidence IDs, verify every cited ID exists in retrieved chunks, check heuristic lexical support per claim, verify abstention responses match their abstention reason, and confirm answer_text matches the rendered inline citations.
  • Abstention evaluation assignment + CI: Implement evaluate_abstention_quality in the practice assignment to measure abstention precision, abstention recall, hallucinated answer rate, and citation validity rate, verified with pytest and GitHub Actions.

1. Inline Citations, Grounding Checks, and Abstention

  • Why forced answers hurt enterprise workflows: Standard instruction-tuned models are biased toward being helpful and answering every prompt. In enterprise support, legal, finance, or operations workflows, guessing when the knowledge base lacks the answer produces confident fabrications. Teaching and enforcing explicit abstention turns unknown queries into safe, auditable refusals.
  • Claim-level inline citations: Attaching specific citation_ids to each factual claim (rendered inline as Claim text [chunk-1].) makes answers auditable. Reviewers and automated verifiers can check both that each cited ID was actually retrieved and that the cited passage supports the statement.
  • Two-layer grounding verification and heuristic limits: First, check citation existence: every ID in claim.citation_ids must exist in the retrieved evidence chunks (and citation_ids must be non-empty and duplicate-free). Second, check evidence support: Token overlap is a lexical heuristic, not proof of semantic entailment. Production systems may use an NLI model, cross-encoder, or LLM judge, with appropriate evaluation and safeguards. Verifying answer_text against rendered claims (or against the abstention reason when abstained) prevents unverified or misleading text from slipping through.
  • Tuning abstention with precision and recall: Raising the minimum evidence threshold reduces hallucinations on unanswerable queries (higher abstention_recall) but can cause false refusals on valid queries (lower abstention_precision). Evaluating both metrics on a mixed golden set lets you calibrate the threshold intentionally.

2. Step-by-Step Build Walkthrough

  1. Set up the fde-02-2 repository and virtual environment: Create the package layout, configure .env.example, .gitignore, and pyproject.toml, and install editable dev dependencies.

    macOS / Linux:

    mkdir -p fde-02-2/src/fde_02_2 fde-02-2/tests
    cd fde-02-2
    python3 -m venv .venv
    source .venv/bin/activate
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    cp .env.example .env

    Windows (PowerShell):

    mkdir fde-02-2
    cd fde-02-2
    py -m venv .venv
    .\.venv\Scripts\Activate.ps1
    py -m pip install --upgrade pip
    py -m pip install -e ".[dev]"
    Copy-Item .env.example .env

    Windows (CMD):

    mkdir fde-02-2
    cd fde-02-2
    py -m venv .venv
    .venv\Scripts\activate.bat
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    copy .env.example .env
  2. Define strict evidence, cited-claim, grounded-response, and evaluation schemas: Enforce non-blank strings, unique citation IDs per claim, consistency between abstained and claims / abstention_reason, finite floats, and count/edge-case consistency on AbstentionMetrics.
    import math
    from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
    
    def _require_finite(value: float, field_name: str) -> float:
        if not math.isfinite(value):
            raise ValueError(f"{field_name} must be finite")
        return value
    
    def _require_non_blank(value: str, field_name: str) -> str:
        if not value.strip():
            raise ValueError(f"{field_name} must not be blank")
        return value
    
    class EvidenceChunk(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        chunk_id: str = Field(min_length=1)
        source_title: str = Field(min_length=1)
        text: str = Field(min_length=1)
    
        @field_validator("chunk_id", "source_title", "text")
        @classmethod
        def _validate_non_blank_fields(cls, value: str, info) -> str:
            return _require_non_blank(value, info.field_name)
    
    class CitedClaim(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        statement: str = Field(min_length=1)
        citation_ids: list[str] = Field(min_length=1)
    
        @field_validator("statement")
        @classmethod
        def _validate_statement(cls, value: str) -> str:
            return _require_non_blank(value, "statement")
    
        @field_validator("citation_ids")
        @classmethod
        def _validate_citation_ids(cls, values: list[str]) -> list[str]:
            if any(not cid.strip() for cid in values):
                raise ValueError("citation_ids must not contain empty strings")
            if len(values) != len(set(values)):
                raise ValueError("citation_ids must be unique")
            return values
    
    class GroundedResponse(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        abstained: bool
        answer_text: str = Field(min_length=1)
        claims: list[CitedClaim] = Field(default_factory=list)
        abstention_reason: str | None = None
    
        @field_validator("answer_text")
        @classmethod
        def _validate_answer_text(cls, value: str) -> str:
            return _require_non_blank(value, "answer_text")
    
        @model_validator(mode="after")
        def _validate_abstention_state(self) -> "GroundedResponse":
            if self.abstained:
                if self.claims:
                    raise ValueError("Abstained responses must not include claims")
                if not self.abstention_reason or not self.abstention_reason.strip():
                    raise ValueError("Abstained responses must include abstention_reason")
            else:
                if not self.claims:
                    raise ValueError("Non-abstained responses must include at least one claim")
                if self.abstention_reason is not None:
                    raise ValueError("Non-abstained responses must not set abstention_reason")
            return self
    
    class GroundingReport(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        is_grounded: bool
        unverified_claims: list[str]
        missing_citation_ids: list[str]
    
    class AbstentionEvalCase(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        case_id: str = Field(min_length=1)
        query: str = Field(min_length=1)
        chunks: list[EvidenceChunk]
        answerable: bool
    
        @field_validator("case_id", "query")
        @classmethod
        def _validate_non_blank(cls, value: str, info) -> str:
            return _require_non_blank(value, info.field_name)
    
    class AbstentionMetrics(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        total_cases: int = Field(ge=0)
        answerable_cases: int = Field(ge=0)
        unanswerable_cases: int = Field(ge=0)
        abstention_precision: float = Field(ge=0.0, le=1.0)
        abstention_recall: float = Field(ge=0.0, le=1.0)
        hallucinated_answer_rate: float = Field(ge=0.0, le=1.0)
        citation_validity_rate: float = Field(ge=0.0, le=1.0)
    
        @field_validator(
            "abstention_precision",
            "abstention_recall",
            "hallucinated_answer_rate",
            "citation_validity_rate",
        )
        @classmethod
        def _validate_finite_metrics(cls, value: float) -> float:
            if not math.isfinite(value):
                raise ValueError("Metric values must be finite")
            return value
    
        @model_validator(mode="after")
        def _validate_consistency(self) -> "AbstentionMetrics":
            if self.total_cases != self.answerable_cases + self.unanswerable_cases:
                raise ValueError("total_cases must equal answerable_cases + unanswerable_cases")
            if self.unanswerable_cases == 0:
                if not math.isclose(self.abstention_recall, 1.0):
                    raise ValueError("abstention_recall must be 1.0 when unanswerable_cases == 0")
                if not math.isclose(self.hallucinated_answer_rate, 0.0):
                    raise ValueError(
                        "hallucinated_answer_rate must be 0.0 when unanswerable_cases == 0"
                    )
            if self.total_cases == 0:
                if not math.isclose(self.abstention_precision, 1.0):
                    raise ValueError("abstention_precision must be 1.0 when total_cases == 0")
                if not math.isclose(self.citation_validity_rate, 1.0):
                    raise ValueError("citation_validity_rate must be 1.0 when total_cases == 0")
            return self
  3. Implement claim, abstention, and answer-text grounding verification: Reject duplicate evidence IDs, verify every cited chunk ID exists, check heuristic token-overlap support per claim, validate abstention consistency against abstention_reason, and confirm answer_text matches the rendered inline citations.
    import re
    
    _STOPWORDS = {
        "a", "an", "and", "are", "as", "at", "be", "by", "for", "from",
        "in", "is", "it", "of", "on", "or", "that", "the", "to", "was", "with",
    }
    
    def _content_tokens(text: str) -> set[str]:
        tokens = re.findall(r"[a-z0-9_]+", text.lower())
        return {tok for tok in tokens if tok not in _STOPWORDS and len(tok) > 1}
    
    def claim_support_ratio(statement: str, evidence_texts: list[str]) -> float:
        claim_tokens = _content_tokens(statement)
        if not claim_tokens:
            return 0.0
        evidence_tokens: set[str] = set()
        for text in evidence_texts:
            evidence_tokens.update(_content_tokens(text))
        if not evidence_tokens:
            return 0.0
        supported = claim_tokens.intersection(evidence_tokens)
        return len(supported) / len(claim_tokens)
    
    def render_inline_citations(claims: list[CitedClaim]) -> str:
        rendered_parts: list[str] = []
        for claim in claims:
            tags = "".join(f"[{cid}]" for cid in claim.citation_ids)
            clean_stmt = claim.statement.rstrip(". ")
            rendered_parts.append(f"{clean_stmt} {tags}.")
        return " ".join(rendered_parts)
    
    def render_abstention_text(reason: str, chunks: list[EvidenceChunk]) -> str:
        clean_reason = reason.strip().rstrip(".")
        searched_sources = ", ".join(sorted({c.source_title for c in chunks})) or "none"
        return f"Abstaining ({clean_reason}; searched sources: {searched_sources})."
    
    def verify_response_grounding(
        response: GroundedResponse,
        chunks: list[EvidenceChunk],
        min_support_ratio: float = 0.6,
    ) -> GroundingReport:
        if not math.isfinite(min_support_ratio) or not (0.0 <= min_support_ratio <= 1.0):
            raise ValueError("min_support_ratio must be finite and within [0.0, 1.0]")
    
        seen_chunk_ids: set[str] = set()
        chunk_map: dict[str, EvidenceChunk] = {}
        for chunk in chunks:
            if chunk.chunk_id in seen_chunk_ids:
                raise ValueError(f"Duplicate chunk_id in evidence chunks: {chunk.chunk_id}")
            seen_chunk_ids.add(chunk.chunk_id)
            chunk_map[chunk.chunk_id] = chunk
    
        if response.abstained:
            reason = (response.abstention_reason or "").strip()
            expected_abstention_text = render_abstention_text(reason, chunks)
            if not reason or response.answer_text.strip() != expected_abstention_text:
                return GroundingReport(
                    is_grounded=False,
                    unverified_claims=[response.answer_text],
                    missing_citation_ids=[],
                )
            return GroundingReport(
                is_grounded=True,
                unverified_claims=[],
                missing_citation_ids=[],
            )
    
        missing_ids: list[str] = []
        unverified: list[str] = []
    
        expected_answer_text = render_inline_citations(response.claims).strip()
        if response.answer_text.strip() != expected_answer_text:
            unverified.append(response.answer_text)
    
        for claim in response.claims:
            claim_missing = [cid for cid in claim.citation_ids if cid not in chunk_map]
            if claim_missing:
                for cid in claim_missing:
                    if cid not in missing_ids:
                        missing_ids.append(cid)
                if claim.statement not in unverified:
                    unverified.append(claim.statement)
                continue
    
            cited_texts = [chunk_map[cid].text for cid in claim.citation_ids]
            ratio = claim_support_ratio(claim.statement, cited_texts)
            if ratio < min_support_ratio and claim.statement not in unverified:
                unverified.append(claim.statement)
    
        return GroundingReport(
            is_grounded=(len(missing_ids) == 0 and len(unverified) == 0),
            unverified_claims=unverified,
            missing_citation_ids=missing_ids,
        )

    Token overlap is a lexical heuristic, not proof of semantic entailment. Production systems may use an NLI model, cross-encoder, or LLM judge, with appropriate evaluation and safeguards.

  4. Build the deterministic grounded responder with abstention: Select chunks matching query terms above min_query_support, emit inline [chunk_id] citations using the chunk text when supported, and return a consistent missing-evidence abstention when no retrieved chunk answers the query.
    def answer_with_grounding(
        query: str,
        chunks: list[EvidenceChunk],
        min_query_support: float = 0.5,
        max_claims: int = 2,
    ) -> GroundedResponse:
        _require_non_blank(query, "query")
        if not math.isfinite(min_query_support) or not (0.0 <= min_query_support <= 1.0):
            raise ValueError("min_query_support must be finite and within [0.0, 1.0]")
        if max_claims < 1:
            raise ValueError("max_claims must be at least 1")
    
        seen_ids: set[str] = set()
        for chunk in chunks:
            if chunk.chunk_id in seen_ids:
                raise ValueError(f"Duplicate chunk_id in retrieved chunks: {chunk.chunk_id}")
            seen_ids.add(chunk.chunk_id)
    
        scored_chunks: list[tuple[float, str, EvidenceChunk]] = []
        for chunk in chunks:
            ratio = claim_support_ratio(query, [chunk.text])
            if ratio >= min_query_support:
                scored_chunks.append((ratio, chunk.chunk_id, chunk))
    
        if not scored_chunks:
            reason = (
                f"No chunk met min_query_support={min_query_support:.2f} for query "
                f"'{query.strip()}'"
            )
            return GroundedResponse(
                abstained=True,
                answer_text=render_abstention_text(reason, chunks),
                claims=[],
                abstention_reason=reason,
            )
    
        scored_chunks.sort(key=lambda item: (-item[0], item[1]))
        selected = [item[2] for item in scored_chunks[:max_claims]]
    
        claims: list[CitedClaim] = []
        for chunk in selected:
            claims.append(
                CitedClaim(
                    statement=chunk.text.strip(),
                    citation_ids=[chunk.chunk_id],
                )
            )
    
        return GroundedResponse(
            abstained=False,
            answer_text=render_inline_citations(claims),
            claims=claims,
            abstention_reason=None,
        )
  5. Run tests and commit to Git: Verify deterministic unit tests with pytest, add .github/workflows/pytest.yml, and commit to Git.
    python -m pytest -v
    git status
    git add .
    git commit -m "Complete FDE module 02.2"

3. Common Pitfalls and Operational Hygiene

  • Allowing non-abstained responses without citations, with fabricated chunk IDs, or with extra unverified answer text: Validate that non-abstained responses carry non-empty claims, every cited ID exists in duplicate-free evidence chunks, and answer_text matches the rendered cited claims.
  • Treating token overlap as full semantic entailment: Token overlap is a lexical heuristic, not proof of semantic entailment. Production systems may use an NLI model, cross-encoder, or LLM judge, with appropriate evaluation and safeguards.
  • Testing only answerable queries or over-tuning abstention thresholds: Include unanswerable cases in your golden set and balance abstention precision vs. recall rather than guessing thresholds.

4. Completion Criteria

  • EvidenceChunk, CitedClaim, GroundedResponse, GroundingReport, AbstentionEvalCase, and AbstentionMetrics enforce strict validation, non-blank strings, unique citation IDs, finite floats, and abstention/count/metric invariants.
  • answer_with_grounding and verify_response_grounding emit inline citations for supported claims, abstain consistently when evidence is missing, reject duplicate evidence IDs, and flag fabricated citations, unsupported claims, mismatched abstention text, or unverified extra text in answer_text.
  • evaluate_abstention_quality implemented and tested across mixed answerable/unanswerable cases, hallucinated answers, over-refusals, and edge cases.
  • All pytest tests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Practice assignment

Build this

In fde-02-2, implement evaluate_abstention_quality(cases: list[AbstentionEvalCase], responder: Callable[[str, list[EvidenceChunk]], GroundedResponse], min_support_ratio: float = 0.6) -> AbstentionMetrics in src/fde_02_2/evals.py that runs responder(case.query, case.chunks) across all evaluation cases and returns an AbstentionMetrics summary containing:

  • total_cases, answerable_cases, and unanswerable_cases counts (validating total_cases == answerable_cases + unanswerable_cases).
  • abstention_precision: among cases where response.abstained is True, the fraction where case.answerable is False (1.0 when the responder never abstained).
  • abstention_recall: among cases where case.answerable is False, the fraction where response.abstained is True (1.0 when unanswerable_cases == 0).
  • hallucinated_answer_rate: fraction of unanswerable cases where response.abstained is False (0.0 when unanswerable_cases == 0).
  • citation_validity_rate: fraction of non-abstained responses that pass verify_response_grounding(response, case.chunks, min_support_ratio=min_support_ratio).is_grounded (1.0 when every response abstained).

Add unit tests in tests/test_evals.py and tests/test_grounding.py covering supported answers with inline citations, abstention on missing evidence, fabricated citation rejection, unsupported claim detection, extra unverified prose in answer_text, mismatched abstention text, duplicate evidence IDs, hallucinated answers on unanswerable queries, over-conservative abstention, and empty/all-answerable/all-unanswerable edge cases, then run python -m pytest -v and push fde-02-2 (including .github/workflows/pytest.yml) to GitHub.

View reference repository ↗

Knowledge check

Test your understanding

  1. Why is forcing an LLM to always produce an answer harmful in enterprise workflows, and how do you tune abstention?
  2. Why must every inline citation ID in a grounded response be validated against the actual retrieved evidence chunks?
  3. What is the difference between syntactic citation validity (pointing to a real retrieved chunk ID) and semantic grounding (the cited chunk actually supports the claim), and why is token overlap only a heuristic?
  4. How do abstention precision and abstention recall balance two failure modes: hallucinating on unanswerable queries vs. refusing to answer valid queries?
  5. What information should a helpful abstention response return to an end user or downstream workflow instead of a bare error?
Reveal self-review answers (attempt the questions first)
  1. Forcing answers vs. tuning abstention: When evidence is missing or ambiguous, forcing an answer causes confident hallucinations that break user trust and create compliance or operational risk; you tune abstention by setting minimum retrieval/grounding thresholds, prompting explicitly for refusal when evidence is absent, and measuring abstention precision vs. recall on an unanswerable eval slice.
  2. Validating citation IDs: Models can invent plausible-looking bracketed IDs (such as [doc-99]) that were never retrieved; verifying every cited ID against the retrieved chunk set blocks fabricated citations before the response reaches the user.
  3. Syntactic validity, semantic grounding, and token-overlap heuristics: Syntactic validity proves the cited chunk ID exists in the retrieved context, whereas semantic grounding checks whether the cited chunk's text actually supports the claim; token overlap is a lexical heuristic, not proof of semantic entailment.
  4. Abstention precision vs. recall: High abstention recall prevents hallucinations on unanswerable queries, while high abstention precision ensures the system does not over-refuse answerable queries; tuning thresholds balances both metrics for the workflow's risk tolerance.
  5. Actionable abstention responses: A good abstention states clearly what evidence is missing, lists which sources were searched, and avoids speculating beyond the retrieved chunks.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.