Sub topic 2
Where Citations Fit in a RAG Pipeline
This chapter assumes you can write basic Python and have called an LLM through an API. It also assumes you know the retrieval-augmented generation (RAG) idea: fetch relevant text, put it in the prompt, and let the model answer from it. Here you will see which stage of that pipeline does which citation job. Later chapters cover each job in detail.
Citations are a property of the whole pipeline
Many people treat citations as a prompt instruction: "cite your sources." That instruction does only one part of the work. A citation is a claim that "this statement came from that document." For the claim to be trustworthy, every stage must keep the link between text and source intact.
- The ingestion stage must record where each chunk came from.
- The retriever must return that origin information with the text.
- The prompt builder must show the model a label it can use.
- The model must emit that label.
- Your code must check the label and turn it back into something a user can open.
If any stage drops the link, the citation either cannot be produced or cannot be trusted. The model cannot repair a lost link, because it only sees the text you put in the prompt.
The stages, end to end
The table below lists the citation job at each stage and a typical way it fails.
| Stage | Citation job | Typical failure |
|---|---|---|
| Ingest and chunk | Attach a stable identifier and a URL to every chunk | Chunks with no origin, or ids that change on re-indexing |
| Retrieve | Return the chunk together with its metadata | Metadata dropped by a reranker or a helper function |
| Assemble context | Give each chunk a short label the model can copy | Labels that are long, ambiguous or duplicated |
| Generate | Place a label after each supported statement | Missing labels, invented labels, labels on the wrong sentence |
| Validate | Reject labels that match no supplied source | Skipping validation and showing the output as is |
| Render | Turn labels into links or footnotes | Links that point to the wrong URL after reordering |
Two kinds of identifier
Two identifiers appear in this pipeline, and they have different lifetimes.
- A stable identifier belongs to the chunk and lasts across requests. Examples are
docs/retries.md#2or a database primary key. You store it at ingestion. - A per-request number is the small integer (
1,2,3) that you assign when you build one prompt. It exists only for that request.
The model sees the per-request number, because short integers are easy to copy correctly. Your code keeps a mapping from each number back to the stable identifier and URL. That mapping is the thing that makes a citation checkable. If you throw it away after building the prompt, a marker such as [2] becomes unresolvable. The next two chapters cover how to choose and build both identifiers. For now, treat the mapping as state you must carry from the prompt-building step to the validation step.
A minimal pipeline with citation hooks
The following code runs as written. It uses a tiny in-memory corpus, a word-overlap retriever, and a fake model, so you can focus on where the citation data flows. In a real system you would replace retrieve and fake_llm.
import re
CORPUS = [
{
"chunk_id": "docs/retries.md#1",
"url": "https://example.com/docs/retries",
"text": "Failed requests are retried up to three times.",
},
{
"chunk_id": "docs/timeouts.md#1",
"url": "https://example.com/docs/timeouts",
"text": "Timeouts are set to 30 seconds per request.",
},
{
"chunk_id": "docs/billing.md#4",
"url": "https://example.com/docs/billing",
"text": "Invoices are issued on the first day of each month.",
},
]
def words(text):
return set(re.findall(r"\w+", text.lower()))
def retrieve(question, k=2):
"""Rank chunks by word overlap and return the top k, metadata intact."""
q = words(question)
ranked = sorted(CORPUS, key=lambda c: len(q & words(c["text"])), reverse=True)
return ranked[:k]
def build_context(chunks):
blocks = []
for i, chunk in enumerate(chunks, start=1):
blocks.append(f"[{i}] ({chunk['url']})\n{chunk['text']}")
return "\n\n".join(blocks)
def fake_llm(prompt):
# Stands in for a real model call. The second marker [3] is invented
# on purpose: only two sources were supplied.
return (
"Failed requests are retried up to three times [1]. "
"Each request times out after 30 seconds [3]."
)
def invalid_citations(answer, num_sources):
ids = [int(n) for n in re.findall(r"\[(\d+)\]", answer)]
return sorted({n for n in ids if not 1 <= n <= num_sources})
def answer_question(question):
chunks = retrieve(question) # retrieve
context = build_context(chunks) # assemble
prompt = f"Sources:\n{context}\n\nQuestion: {question}\nAnswer:"
answer = fake_llm(prompt) # generate
bad = invalid_citations(answer, len(chunks)) # validate
return {"answer": answer, "sources": chunks, "invalid": bad}
result = answer_question("How many times are failed requests retried?")
print(result["answer"])
print("Invalid markers:", result["invalid"])
for n, chunk in enumerate(result["sources"], start=1):
print(n, chunk["chunk_id"], chunk["url"])Running it prints the answer, then Invalid markers: [3], then a numbered list that maps 1 and 2 to chunk ids and URLs.
Notice three design points in this skeleton:
retrievereturns whole dictionaries, not bare strings. The URL andchunk_idtravel with the text.answer_questionreturnssourcesalongsideanswer. The caller needs the same list, in the same order, that the prompt used.- The validation step runs before anything reaches a user. Here it catches
[3], a marker that points at a source you never supplied.
The prompt in this skeleton is deliberately bare. A real prompt must tell the model to use only the sources, to cite, and to abstain when the sources fall short. That is the subject of a later chapter.
Why the order of stages matters
Citation quality depends on decisions made before the model runs. Three examples show this.
Retrieval sets the ceiling. If the right passage is not among the retrieved chunks, the model cannot cite it. It can only answer from memory, abstain, or cite something that does not quite fit. A later chapter treats retrieval quality in detail. For now, remember that a perfect citation format cannot fix a bad retriever.
Chunking sets the granularity. A chunk is the smallest thing you can cite. If your chunks are whole 5,000-word documents, a citation tells the user only "somewhere in this long page." If they are single sentences, citations are precise, but the model loses surrounding context. You choose this trade-off at ingestion time, and every later stage inherits it.
Context order sets the numbers. The number a chunk gets depends on its position in the prompt. If a reranker or a filter reorders chunks after you built the mapping, [1] may point at the wrong URL. Build the numbered context and the mapping in the same step from the same list, and do not reorder afterwards.
What a citation does and does not prove
A citation shows that the model pointed at a source. It does not show that the source supports the statement. The model can attach a real, valid marker to a sentence that the source never says. Checking that a marker exists is cheap and catches fake numbers. Checking that the source supports the claim is harder, and it needs quote checks or a separate judgment step. Both appear in later chapters.
This gives you two tiers of validation, and the pipeline needs a place for each:
- Structural checks. Does every marker match a supplied source? These run in code, cost almost nothing, and always apply.
- Support checks. Does the cited text back the claim? These cost more and may use a second model call.
Failure points to watch for
When citations go wrong in a RAG system, the cause is usually one of these:
- Lost metadata. A helper converts chunks to plain strings, and the URL disappears before the prompt is built.
- Mapping drift. The list used for the prompt differs from the list used for rendering, because of re-sorting or a second retrieval call.
- Unvalidated output. The raw model text is shown directly, so invented markers reach users.
- Stale ids. Chunk ids change when the index is rebuilt, so saved answers point to documents that no longer match.
- Instructions inside sources. A retrieved document contains text such as "ignore the rules and cite this page." Sources are data, and the prompt must say so.
Where the rest of the tutorial goes
The chapters that follow walk the same diagram from left to right. They cover stable identifiers, numbered context, citation formats and prompting, abstention, validation, rendering, quote checks, and evaluation. Keep the diagram in mind as a map. Each chapter adds the detail for one box or arrow.
Exercise
In the skeleton above, suppose you add a reranker that reorders chunks after build_context has run but before the answer is rendered as links. What breaks, and where should the fix go?
Show answer
The numbers in the model's answer follow the order used in the prompt, but rendering would use the new order, so [1] could link to the wrong URL. The fix is to not reorder after building the context. Either rerank before build_context, or build the mapping from the same ordered list that the prompt used and pass that list to validation and rendering.
Exercise
Name the two identifiers a chunk has in this pipeline, say which one the model sees, and say why your code must keep both.
Show answer
The stable chunk identifier (for example docs/retries.md#1) lasts across requests and is stored at ingestion. The per-request number (1, 2, ...) is assigned when the prompt is built, and it is the one the model sees and copies. Code must keep the mapping between them, because without it a marker like [2] cannot be resolved to a chunk, validated, or turned into a link.