Sub topic 2
Where Citations Fit in a RAG Pipeline
This chapter assumes you can call a language model through an API, know roughly what retrieval-augmented generation (RAG) is, and can read basic Python and JSON. It shows where citations are created and checked in a RAG pipeline. Later chapters build each step.
The pipeline at a glance
A RAG system answers a question in stages. Each stage either produces material a citation needs or checks one.
- Retrieve. Search an index and return the chunks most relevant to the question.
- Identify. Give each chunk a stable identifier and keep its metadata, such as the URL.
- Assemble. Put the numbered chunks into the prompt.
- Generate. The model writes an answer with citation markers.
- Validate. Code checks the markers, and optionally the quotes, against the sources.
- Render. Turn the checked markers into links for the user.
The model only handles stage 4. Your code handles the rest, so most of the work of making citations trustworthy happens outside the model.
Why the order matters
A citation is only a number the model writes. It points to something only if your code gave that number a meaning earlier. That is why identifiers come before generation, and why validation comes after it.
Here is the smallest version of the identify and assemble stages. It numbers chunks from 1 and keeps the URL beside each one.
def build_context(chunks):
"""chunks: list of dicts with 'url' and 'text'. Sources are numbered from 1."""
blocks = []
for i, chunk in enumerate(chunks, start=1):
blocks.append(f"[{i}] ({chunk['url']})\n{chunk['text']}")
return "\n\n".join(blocks)The list position in chunks is the link between a marker and a source. If you reorder or filter that list after building the prompt, the markers in the answer no longer match. Keep the same list for building the context, validating, and rendering.
After generation, the first check is simple. Does every marker point to a source you supplied?
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})What each stage can break
Errors in early stages carry forward. Later stages can catch some of them but not all.
| Stage | Typical error | Who can catch it |
|---|---|---|
| Retrieve | The right passage is never returned | Nothing downstream. The model cannot cite what it never saw. |
| Identify | Ids change between runs or shift after filtering | Your code, by using one list throughout |
| Generate | A marker such as `[7]` when only 4 sources exist | Marker validation |
| Generate | A valid marker on a claim the source does not support | Quote and support checks |
| Render | A marker links to the wrong URL | Tests on the render step |
Notice the second generate row. A marker can be in range and still be wrong. A citation shows where the model says its information came from. It does not prove the answer is grounded. Checking support is a separate job, covered later.
Where the weak points are
Retrieval limits everything. If the best passage is missing, the model either abstains, guesses, or cites a nearby but unhelpful chunk. Validation cannot fix that.
Validation is the stage most often skipped. It is also the cheapest, since a regular expression and a range check catch fabricated numbers.
Exercise
A model answers "Retries happen three times [5]" but you supplied four sources. Which stage should catch this, and what should the system do next?
Show answer
The validate stage should catch it, because 5 is outside the range 1 to 4 (invalid_citations(answer, 4) returns [5]). The system should not show the citation. It can retry the generation, remove the marker, or return a fallback reply.