"""Validate citations against retrieved passages and enforce unknown/next-steps hygiene.""" import re from typing import List, Set from src.schemas import GroundedAnswer, RetrievedPassage def validate_and_clean_citations( grounded: GroundedAnswer, top_passages: List[RetrievedPassage], ) -> GroundedAnswer: """Verify cited IDs exist in retrieved top-K passages and clean spurious action items.""" valid_ids: Set[str] = {rp.passage.passage_id for rp in top_passages} warnings: List[str] = list(grounded.citation_warnings) # Filter any hallucinated passage IDs from list cleaned_cited: List[str] = [] for cid in grounded.cited_passage_ids: if cid in valid_ids: if cid not in cleaned_cited: cleaned_cited.append(cid) else: warnings.append(f"Removed unretrieved citation ID '{cid}'.") # Sync valid inline [PASSAGE_ID] citations from answer prose inline_matches = re.findall(r"\[(N\d{2}-[PR]\d{2})\]", grounded.answer) for pid in inline_matches: if pid in valid_ids and pid not in cleaned_cited: cleaned_cited.append(pid) elif pid not in valid_ids: warnings.append(f"Inline citation [{pid}] not found in top-3 retrieved passages.") # Guardrail: if no passages were cited and missing_information indicates fully unanswerable, # ensure next_steps is empty so the model doesn't emit invented action steps. cleaned_steps = list(grounded.next_steps) missing_norm = (grounded.missing_information or "").strip().lower() if not cleaned_cited and missing_norm not in {"", "none", "n/a"} and cleaned_steps: cleaned_steps = [] warnings.append("Suppressed next_steps because zero evidence passages were cited.") if not cleaned_cited and missing_norm in {"", "none", "n/a"}: warnings.append("Answer made material claims with zero verified passage citations.") return grounded.model_copy( update={ "cited_passage_ids": cleaned_cited, "next_steps": cleaned_steps, "citation_warnings": warnings, } )