Sub topic 9
Validating citation markers in code
This chapter assumes you can write basic Python, call an LLM API, and know what a RAG pipeline is. By now your prompt numbers each source from 1 and asks the model to cite with markers like [2]. A model can still write a marker that points to nothing. Your code should check every marker before a user sees it.
What validation can and cannot prove
Marker validation is a structural check. It tells you whether a marker refers to a source you actually supplied. It does not tell you whether that source supports the claim. A citation that passes this check can still be wrong. Later chapters cover quote and faithfulness checks. Here we handle the cheap, reliable first layer.
Extracting markers
Markers follow a fixed pattern: square brackets around digits. A regular expression finds them.
import re
def extract_citation_ids(answer):
return [int(n) for n in re.findall(r"\[(\d+)\]", answer)]
def invalid_citations(answer, num_sources):
"""Return citation numbers that do not match any provided source."""
return sorted({n for n in extract_citation_ids(answer) if not 1 <= n <= num_sources})extract_citation_ids returns every number in order, with repeats. invalid_citations keeps only numbers outside the range 1 to num_sources, removes duplicates, and sorts them. The range starts at 1 because build_context numbers sources from 1.
Try it:
answer = "The service retries failed requests [2]. Timeouts are 30 seconds [5]."
print(extract_citation_ids(answer)) # [2, 5]
print(invalid_citations(answer, 3)) # [5]Only three sources were supplied, so [5] is fake.
Where validation sits
Validation runs after generation and before rendering. The result decides what happens next.
Deciding what to do with a failure
You have three reasonable options when invalid_citations returns a non-empty list.
| Option | Behavior | Trade-off |
|---|---|---|
| Retry | Call the model again, optionally naming the bad numbers | Costs another call and may fail again |
| Strip | Remove the bad markers and keep the text | The claim is now uncited, so users may trust it too much |
| Reject | Return a fallback message | Safe, but loses a possibly useful answer |
A common pattern is to retry once, then reject. Stripping is the weakest choice because it hides the problem.
Other checks worth adding
Range checking misses some cases. Consider these:
- No markers at all. An answer with zero markers may be unsupported. If the answer is not the abstention reply, treat it as suspect.
- Markers in the abstention reply. The fixed reply "I could not find this in the provided sources." should have no markers.
- Unused sources. Not an error. The model does not have to cite every source.
ABSTAIN = "I could not find this in the provided sources."
def check_answer(answer, num_sources):
if answer.strip() == ABSTAIN:
return "abstained"
ids = extract_citation_ids(answer)
if not ids:
return "uncited"
if invalid_citations(answer, num_sources):
return "invalid"
return "ok"Common mistakes
- Using
range(num_sources)and checking from 0, which is off by one against 1-based numbering. - Matching markers that are not citations, such as
[0]in array notation or[10]in code samples. Keep your pattern strict and consider asking the model to avoid brackets for other uses. - Validating against the number of retrieved chunks instead of the number actually placed in the prompt. If you truncate context to fit a token limit, use the truncated count.
Exercise
A prompt contained 4 sources. The model answers "Retries happen three times [1][3]. The limit is configurable [0][4]." What does invalid_citations(answer, 4) return, and why?
Show answer
It returns [0]. Valid numbers run from 1 to 4, so 0 is out of range. The number 4 is in range, and 1 and 3 are also valid. Whether source 4 really supports the claim is a separate question this check cannot answer.