Sub topic 15
Measuring citation precision and recall
This chapter assumes you can call a model through an API, that you have a working RAG pipeline that numbers its sources, and that you have read the earlier chapters on citation markers and validation. You should be comfortable with Python sets and JSON.
Why validation is not evaluation
Validation checks one answer at a time. It tells you whether [7] points to a source that exists, or whether a quoted span appears in a source. Evaluation asks a different question: across many answers, how often does the system cite the right sources?
A citation can pass every validation check and still be wrong. The marker [2] may be in range, and the quote may occur in source 2, yet source 2 may not support the claim it is attached to. Evaluation measures that gap. It needs a reference to compare against, which is the main cost of doing it.
Two questions, two metrics
Citation quality has two sides.
- Citation precision asks: of the sources the answer cited, how many were correct? Low precision means the answer cites sources that do not support it. This is the misattribution problem.
- Citation recall asks: of the sources that should have been cited, how many were? Low recall means the answer relied on evidence it did not credit, or made claims with no citation at all.
The two can trade off. An answer that cites every source it was given has perfect recall and poor precision. An answer that cites nothing has no wrong citations, but its recall is zero whenever a citation was expected.
Building a gold set
Both metrics compare a predicted set of source ids against a gold set. The gold set is the list of source ids a careful human judges to support the answer. You build it by hand.
A practical gold set has these parts for each test case:
- A question.
- The retrieved sources, numbered exactly as the model saw them.
- The set of source ids that support a correct answer.
- A flag for questions that the sources cannot answer. For these the gold set is empty.
Keep the numbering frozen. If you change the retriever or the ordering, source [3] may become a different chunk, and your gold labels no longer line up. A stable chunk identifier, stored next to the display number, lets you re-map labels after a change.
A small test file might look like this:
{
"id": "q-014",
"question": "How many times does the service retry a failed request?",
"num_sources": 4,
"gold_source_ids": [2],
"answerable": true
}Aim for a few dozen cases at first. Include easy questions, questions that need two sources, and questions the sources cannot answer. A set made only of easy cases will make every system look good.
Computing the metrics for one answer
The function below compares the cited ids with the gold ids for a single answer.
def citation_precision_recall(predicted, gold):
"""predicted and gold are sets of source ids for one answer."""
if not predicted:
precision = 1.0 if not gold else 0.0
else:
precision = len(predicted & gold) / len(predicted)
if not gold:
recall = 1.0
else:
recall = len(predicted & gold) / len(gold)
return precision, recallLook at the edge cases, because they encode decisions.
| Predicted | Gold | Precision | Recall | Meaning |
|---|---|---|---|---|
| {2} | {2} | 1.0 | 1.0 | Exact match |
| {1, 2, 3} | {2} | 0.33 | 1.0 | Found the right source, plus noise |
| {2} | {2, 3} | 1.0 | 0.5 | Right but incomplete |
| {} | {2} | 0.0 | 0.0 | Answered without citing |
| {} | {} | 1.0 | 1.0 | Correctly abstained |
| {4} | {} | 0.0 | 1.0 | Cited a source for an unanswerable question |
The last row shows a quirk. When the gold set is empty, recall is 1.0 by definition, since nothing was missed. Precision carries the penalty, because any citation is wrong. This works, but only if you read both numbers together.
Running over a whole test set
To get the predicted set, reuse the extraction function from the validation chapter. Drop out-of-range ids first, because a fake citation should not count as a correct one. It also should not vanish from your results, so track it separately.
import re
def extract_citation_ids(answer):
return [int(n) for n in re.findall(r"\[(\d+)\]", answer)]
def evaluate(cases, answers):
"""cases: list of dicts with 'id', 'num_sources', 'gold_source_ids'.
answers: dict mapping case id to the model's answer text."""
rows = []
for case in cases:
answer = answers[case["id"]]
cited = set(extract_citation_ids(answer))
valid = {n for n in cited if 1 <= n <= case["num_sources"]}
invalid = cited - valid
gold = set(case["gold_source_ids"])
if not valid:
precision = 1.0 if not gold else 0.0
else:
precision = len(valid & gold) / len(valid)
recall = 1.0 if not gold else len(valid & gold) / len(gold)
rows.append({
"id": case["id"],
"precision": precision,
"recall": recall,
"invalid": sorted(invalid),
})
return rows
def summarize(rows):
n = len(rows)
return {
"mean_precision": sum(r["precision"] for r in rows) / n,
"mean_recall": sum(r["recall"] for r in rows) / n,
"answers_with_invalid_ids": sum(1 for r in rows if r["invalid"]),
}This computes the metrics for each answer, then averages them. That is a macro average, and each question counts equally. A micro average would pool all citations first, so questions with many citations would count for more. Macro averaging is usually easier to reason about for question answering. Pick one and keep it fixed so that runs stay comparable.
Reading the results
A single number hides the cause. Look at the pattern.
- Low precision, high recall. The model over-cites. Tighten the prompt so each statement cites only the source it relies on, and check whether the context contains many near-duplicate chunks.
- High precision, low recall. The model cites correctly but sparingly. It may skip citations on statements that combine several sources. Ask for a citation after every claim, or use structured output with one entry per claim.
- Both low. Look upstream. If the retriever never returned the supporting chunk, no prompt change will fix it. Check retrieval first, as the earlier chapter on retrieval quality explains.
- Many invalid ids. The model is inventing numbers. Check that the prompt states how many sources there are, and that the numbering in the context matches the numbering you evaluate against.
What these metrics do not tell you
Precision and recall on ids measure whether the right sources were named. They do not measure whether the sentence is true.
- Right source, wrong claim. The model may cite source 2 correctly and still misstate what source 2 says. The id matches the gold set, so the score is perfect.
- Gold labels are judgments. Two annotators may disagree on whether a source "supports" a claim. For important sets, have two people label and resolve differences.
- Sets ignore placement. The metric treats the answer as a bag of ids. It cannot tell whether
[2]was attached to the right sentence.
To close part of the gap, add a claim-level check. Label each claim in the answer as supported or not by its cited source, and report the share of supported claims. You can do this by hand on a sample, or with a second model call that is itself spot-checked by a person. Use the quote check from the verification chapter as a cheap first filter. A quote that is not in the source fails automatically, and only the remaining claims need judgment.
Practical habits
- Version your test set and store the retriever settings used to build it.
- Report precision, recall, and the count of invalid ids together, never one alone.
- Track abstention cases as their own group. Report how often the system correctly declines on unanswerable questions, and how often it declines on answerable ones.
- Re-run the set after every change to the prompt, model, chunking, or retriever. Compare against the previous run, not against an ideal.
- Read the worst ten answers by hand each time. Averages hide the failures that matter.
Exercise
A test case has gold source ids {1, 3}. The model's answer cites [3] and [5], and the context contained only four sources. What are the precision and recall, and what should you record about [5]?
Show answer
Source 5 is out of range, since only four sources were supplied, so it is an invalid citation. Drop it before scoring and record it separately. The valid predicted set is {3}. Precision is 1/1 = 1.0 and recall is 1/2 = 0.5. If you had left [5] in, precision would have been 0.5, which would blur a fake citation with a real but wrong one. Counting the invalid id separately keeps both problems visible.
Exercise
A system scores mean precision 0.95 and mean recall 0.40 on your test set. Name two likely causes and one change to try for each.
Show answer
One cause is that the model cites only some of the sources it relies on, for example one citation for a sentence that draws on two chunks. Try requiring a citation after every claim or switching to structured output with one entry per claim. Another cause is that the retriever misses supporting chunks, so the model cannot cite them. Check whether the gold sources appear in the retrieved set, and improve retrieval if they do not.
Exercise
Why can an answer score precision 1.0 and recall 1.0 and still be unfaithful to its source?
Show answer
The metrics compare only source ids. The answer can cite the correct source but misstate what it says, so the id matches the gold set while the claim is unsupported. A claim-level support check, or at least a quote verification step, is needed to catch this.