Sub topic 9
Validating citation markers in code
This chapter assumes you can write basic Python and call a language model through an API. It also assumes you know what retrieval-augmented generation (RAG) is and have read the earlier chapters on numbering sources and prompting the model to cite. Here the model has already produced an answer with markers such as [2]. Your code must check those markers before a user sees them.
Why a model's citations need checking
A citation marker is text the model generated. Like any generated text, it can be wrong. The model may cite a number that was never supplied, cite a real source that does not say what the answer claims, or leave a claim with no citation at all. A marker that looks tidy does not show that the answer is grounded.
Validation is a set of cheap, deterministic checks that run after generation. Each check catches one class of error and says nothing about the others. This chapter covers the checks that need no second model call:
- Syntactic checks: are the markers well formed and do they point at real sources?
- Coverage checks: do the statements that need a citation have one?
- Abstention checks: does a refusal contain stray citations?
Checks that ask whether a source actually supports a claim come in later chapters.
What the validator receives
Assume the prompt numbered the sources from 1, as in the context-assembly chapter. The validator needs two inputs: the answer text and the number of sources that were placed in the prompt. Compare against what was actually in the prompt, not against what was retrieved. If you retrieved 10 chunks but trimmed the context to 6 to fit a token budget, only [1] to [6] are valid.
Extracting markers
The first step is to find every marker in the answer.
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, including repeats. invalid_citations turns them into a set, keeps those outside the range 1 to num_sources, and sorts them so the output is stable.
For example, if the prompt had three sources and the answer cites [2], [5] and [0], the function returns [0, 5]. Both numbers are errors. The range check starts at 1 because the numbering starts at 1, so [0] is invalid even though it is a number.
What this regular expression misses
The pattern \[(\d+)\] matches only a single number in square brackets. Models often write other forms:
| Model output | Matched by `\[(\d+)\]` | Typical cause |
|---|---|---|
| `[2]` | Yes | The format you asked for |
| `[2, 3]` | No | Grouping two sources in one bracket |
| `[2][3]` | Yes, as two markers | Adjacent markers |
| `[2-4]` | No | Range shorthand |
| `[Source 2]` | No | Ignoring the format instruction |
| `(2)` | No | Different bracket style |
An unmatched form is dangerous because it silently passes validation. The answer looks as though it has no invalid citations, but it may contain one. You have two options. You can tighten the prompt to forbid grouped forms and then reject any bracket that does not match the strict pattern. Or you can widen the parser to accept grouped forms. The first option is simpler and keeps the rendering code simple, so it is the usual choice.
A strict detector looks for any bracketed content that looks citation-like but is not a clean single number:
import re
STRICT = re.compile(r"\[(\d+)\]")
LOOSE = re.compile(r"\[[^\]]*\d[^\]]*\]")
def malformed_markers(answer):
"""Bracketed groups that contain a digit but are not a single clean number."""
return [m for m in LOOSE.findall(answer) if not STRICT.fullmatch(m)]LOOSE matches any bracket group that contains a digit. STRICT.fullmatch accepts only the clean form. Whatever is left over is malformed. With the input "Retries happen [2, 3] and also [4].", the function returns ['[2, 3]'].
This also flags brackets that are not citations, such as array[0] in a code sample or [1.5] in a numeric result. If your domain has many of these, you have a real choice: switch the marker format to something less ambiguous, such as [S2], or accept some false alarms.
Building one validation report
Separate checks are easier to test, but callers want one answer. Combine them into a report object that lists problems without raising errors. A report lets the application decide what to do, such as retry, strip the markers, or show a warning.
import re
from dataclasses import dataclass, field
ABSTENTION = "I could not find this in the provided sources."
STRICT = re.compile(r"\[(\d+)\]")
LOOSE = re.compile(r"\[[^\]]*\d[^\]]*\]")
@dataclass
class CitationReport:
cited: list = field(default_factory=list)
out_of_range: list = field(default_factory=list)
malformed: list = field(default_factory=list)
uncited_sentences: list = field(default_factory=list)
is_abstention: bool = False
@property
def ok(self):
return not (self.out_of_range or self.malformed or self.uncited_sentences)
def split_sentences(text):
parts = re.split(r"(?<=[.!?])\s+", text.strip())
return [p for p in parts if p]
def validate_answer(answer, num_sources):
report = CitationReport()
report.is_abstention = answer.strip() == ABSTENTION
report.cited = [int(n) for n in STRICT.findall(answer)]
report.out_of_range = sorted({n for n in report.cited if not 1 <= n <= num_sources})
report.malformed = [m for m in LOOSE.findall(answer) if not STRICT.fullmatch(m)]
if not report.is_abstention:
report.uncited_sentences = [
s for s in split_sentences(answer) if not STRICT.search(s)
]
return report
if __name__ == "__main__":
answer = "The service retries failed requests [2]. Timeouts default to 30 seconds. It logs errors [7]."
report = validate_answer(answer, num_sources=3)
print(report.ok)
print(report.out_of_range)
print(report.uncited_sentences)Running this prints:
False
[7]
['Timeouts default to 30 seconds.']The answer fails for two reasons. Marker [7] points at a source that does not exist, and the middle sentence has no citation.
Coverage: the uncited sentence check
Range checking only tells you that the markers present are valid. It cannot tell you about the markers that are missing. A model that cites nothing at all produces an empty invalid_citations list, so a range check alone would pass it.
The uncited-sentence check treats every sentence in a non-abstaining answer as a claim that needs a marker. It is a heuristic, and it has known weak spots:
- Sentence splitting on punctuation breaks on abbreviations such as "e.g." and on decimal numbers in some formats.
- Some sentences are not claims, such as a short transition ("Here is what the sources say."). These produce false alarms.
- A marker at the end of a paragraph may cover several sentences. Whether that is acceptable is a policy decision.
Decide your policy before you write the check. A strict policy, where every sentence needs a marker, is easy to enforce and easy to explain. A looser policy, where each paragraph needs at least one marker, produces fewer false alarms but lets uncited claims slip through.
Handling abstentions
Earlier you defined a fixed reply for questions the sources cannot answer. Validation should recognize it by exact match and skip the coverage check, because the refusal has no claims to cite.
An abstention that contains a marker is suspicious. The text "I could not find this in the provided sources [2]" mixes a refusal with a citation. Treat it as a format error, because downstream code that tests for the exact abstention string will fail to recognize it.
The opposite case also matters. If the model writes a confident answer and cites nothing, the coverage check catches it. If it writes a hedged refusal in its own words, such as "The documents don't seem to mention that," the exact-match test fails and the coverage check flags every sentence. Either outcome is acceptable, since it sends the answer to the failure path rather than to the user.
Deciding what to do with failures
Validation produces a verdict. The application still has to act on it. Common responses, from least to most disruptive:
- Strip invalid markers and show the rest. This keeps the answer, but you are now showing text whose citation support you have partly removed.
- Retry the model call once with the error appended, for example "Your answer cited source 7, but only sources 1 to 3 exist."
- Fall back to the abstention reply.
- Show the answer with a visible warning that some citations could not be verified.
Retrying works well for range errors, because the model usually fixes them when told what is wrong. Limit retries to one or two. A loop that retries until validation passes can run forever and burn tokens on an answer that will never be valid.
What validation does not prove
Every check in this chapter is structural. A passing report means the answer cites only sources that exist and that each sentence carries a marker. It does not mean the cited source says what the sentence says. A model can attach [1] to a claim that only source 3 supports, and every check above will pass.
This gap is the reason later chapters add quote verification and claim-support checks. Treat structural validation as a filter that removes the cheapest class of error. It does not certify an answer.
Common mistakes
- Validating against the retrieved count instead of the count placed in the prompt.
- Forgetting that numbering starts at 1, so
[0]slips through a check written asn >= 0. - Using a parser that ignores
[2, 3], which lets grouped markers bypass the range check. - Treating "no invalid markers" as "answer is cited". An empty list also results from an answer with no markers.
- Retrying without a limit.
Exercises
Exercise
A prompt contained 4 numbered sources. The model answers: "Requests time out after 30 seconds [1]. Retries are capped at three [2, 4]. Logs are kept for a week [9]." Using the code in this chapter, what does validate_answer(answer, 4) put in cited, out_of_range and malformed, and what is ok?
Show answer
cited is [1, 9], because [2, 4] does not match the strict pattern. out_of_range is [9]. malformed is ['[2, 4]']. uncited_sentences is empty because each sentence contains a bracket that matches the strict pattern or, for the second sentence, none: the second sentence has only [2, 4], which the strict pattern does not match, so it is listed in uncited_sentences as "Retries are capped at three [2, 4]." ok is False.
Exercise
Why is checking only that cited numbers fall within 1 to num_sources not enough to call an answer cited?
Show answer
An answer with no markers has no out-of-range numbers, so it passes a range check. A coverage check is also needed. Even then, the checks only confirm structure, not that the source supports the claim.
Exercise
The retriever returned 8 chunks, but you included only the top 5 in the prompt. What value should you pass as num_sources, and why?
Show answer
Pass 5. The model can only see sources 1 to 5, so a marker such as [6] refers to something it never received and must be treated as invalid.