Sub topic 3
Validating Citation Markers in Code
Assume you know basic Python, JSON, language-model APIs, and the main steps of retrieval-augmented generation (RAG). This chapter focuses on checks that run after retrieval and generation, before an answer reaches a user.
Validate markers before rendering
A citation marker such as [2] is only a reference to a retrieved chunk. It does not prove that the chunk supports the claim. First check that every marker points to an existing source.
import re
sources = [
{"url": "https://example.com/retries", "text": "Requests retry up to three times."},
{"url": "https://example.com/timeouts", "text": "Requests time out after 30 seconds."},
]
answer = "The client retries failed requests up to three times [1]."
def invalid_citations(answer, source_count):
ids = [int(n) for n in re.findall(r"\[(\d+)\]", answer)]
return sorted({n for n in ids if not 1 <= n <= source_count})
def render_citations(answer, sources):
def replace(match):
number = int(match.group(1))
if 1 <= number <= len(sources):
return f"[[{number}]]({sources[number - 1]['url']})"
return match.group(0)
return re.sub(r"\[(\d+)\]", replace, answer)
print(invalid_citations(answer, len(sources))) # []
print(render_citations(answer, sources))Rendering should happen only after validation. Invalid markers should be logged or rejected, not silently linked to the wrong document.
Verify quotes and claim support
If your output includes quotes, compare each quote with the cited source. Normalize case and whitespace, but do not accept a paraphrase as a verbatim quote.
def normalize(text):
return " ".join(text.lower().split())
def quote_is_supported(quote, source_text):
return normalize(quote) in normalize(source_text)
print(quote_is_supported(
"Requests retry up to three times.",
sources[0]["text"]
)) # TrueFor paraphrased claims, use a claim-support check: compare the claim with the source using a reviewer, entailment model, or carefully constrained second model. Record “supported,” “unsupported,” or “uncertain.” Poor retrieval limits this process. If the needed fact was never retrieved, citation validation cannot recover it.
Failure modes and evaluation
Watch for fake markers, misattribution between similarly numbered chunks, and instructions embedded in retrieved text. Treat source text as data, never as prompt instructions.
Evaluate a labeled set of answers. Citation precision is the fraction of cited sources that are correct. Citation recall is the fraction of needed sources that the answer cited.
def precision_recall(predicted, gold):
precision = len(predicted & gold) / len(predicted) if predicted else 0
recall = len(predicted & gold) / len(gold) if gold else 1
return precision, recallExercise
Why can an answer with only valid citation numbers still be ungrounded?
Show answer
The numbers may point to real chunks that do not support the claims attached to them.