Sub topic 5
Choosing a Citation Format
This chapter assumes you can call a language model through an API, know what retrieval-augmented generation (RAG) is, and can read basic Python and JSON. By now your pipeline gives every retrieved chunk a stable identifier and builds a numbered context block. The next decision is how the model should point back to those sources in its answer. That choice shapes your prompt, your validation code, and what users see.
What a citation format has to do
A citation format is the agreed shape of the link between a claim in an answer and the source that supports it. A good format meets four requirements:
- The model can produce it reliably. If the format is awkward, the model will drift from it.
- Code can parse it. You must be able to extract every citation without guessing.
- Code can check it. You should be able to test each citation against the sources you supplied.
- People can use it. A reader should be able to go from a claim to its source in one step.
No format wins on all four. The sections below compare the main options so you can pick on purpose.
Option 1: Inline numeric markers
The model writes a number in square brackets after each statement that relies on a source:
The service retries failed requests up to three times [2]. Retries use exponential backoff [2][4].Each number matches the number you gave that chunk in the context block. The build_context function from the previous chapter produces exactly this numbering, starting at 1.
Strengths:
- Short, so it adds few output tokens.
- Familiar to readers from encyclopedias and papers.
- Easy to extract with a regular expression.
- Easy to render as links later.
Weaknesses:
- The marker says which source, not which passage in that source.
- A number is easy to get wrong. The model may write
[7]when only five sources exist. - Brackets can appear in normal text, such as
array[0]in a code answer, and be mistaken for citations. - The marker sits at an uncertain position. It may follow a sentence, a clause, or a whole paragraph, so you cannot always tell which claim it covers.
Here is a minimal prompt fragment that asks for this format:
INLINE_INSTRUCTION = (
"After each statement that relies on a source, add its number in square "
"brackets, for example [2]. Use one bracket pair per source, such as [1][3]."
)Asking for one bracket pair per source matters. Without it, the model sometimes writes [1, 3] or [1-3], and a simple pattern like \[(\d+)\] misses those numbers.
Option 2: Inline markers with other identifiers
Instead of numbers, you can use identifiers the model can read in the context, such as a short document key ([billing-faq]) or a hash fragment ([a91f]).
Strengths:
- Identifiers stay the same between requests. The number
[2]may refer to a different chunk on the next query, but[billing-faq]does not. - Logs and stored answers stay meaningful after the context changes.
Weaknesses:
- Longer identifiers are easier for the model to mistype.
- Opaque strings such as hashes are easy to invent, and a made-up hash looks just as plausible as a real one.
- Readers see strange tokens unless you render them.
A common compromise is to number sources per request for the model, then keep a mapping from each number to the stable chunk id in your own storage. The model sees [2]. Your logs record chunk_8f3a.
Option 3: Structured claims
In this format the model returns JSON. Each claim lists the source ids it relies on, and may include a short quote:
{
"answer": "The service retries failed requests up to three times.",
"claims": [
{
"text": "The service retries failed requests up to three times.",
"source_ids": [2],
"quote": "failed requests are retried up to three times"
}
]
}Strengths:
- No text parsing. You read fields from JSON.
- Each citation attaches to a specific claim, so there is no doubt what it covers.
- The quote lets code check that the passage exists in the source.
- You control rendering fully, since the answer and its evidence are separate fields.
Weaknesses:
- More output tokens, so higher cost and latency.
- Streaming is harder. A partial JSON object cannot be shown to a user until it is complete, unless you use a streaming parser.
- The model can produce invalid JSON, so you need a parse-and-retry path.
- The
answerfield and theclaimslist can disagree. The answer may say something that no claim covers.
The next chapter covers structured output in more detail. For now, treat it as the high-verification option.
Option 4: Quote-first citations
A variation puts the quotes before the answer. The model first extracts the relevant passages, each with a source number, and then writes an answer using only those extracts. This ordering gives the model less room to write unsupported statements, because it has already committed to evidence. It costs more tokens and adds a step, so teams usually reserve it for high-stakes domains such as legal, medical, or compliance questions.
Comparing the options
| Format | Parsing effort | Granularity | Checkable by code | Streaming | Token cost |
|---|---|---|---|---|---|
| Numeric inline markers | Low (regular expression) | Source level | Marker range only | Easy | Low |
| Named inline identifiers | Low to medium | Source level | Identifier lookup | Easy | Low to medium |
| Structured claims | Low (JSON parse) | Claim level | Ids and quotes | Harder | Medium to high |
| Quote-first | Medium | Passage level | Ids and quotes | Harder | High |
"Checkable by code" is the column that matters most for grounding. A numeric marker can only be tested for being in range. A quote can be tested for appearing in the source text. Neither proves the source supports the claim, which later chapters address.
A decision flow
The following diagram turns the trade-offs into a short procedure.
Most teams start with numeric inline markers. They work with streaming, add little cost, and are enough for a chat assistant over documentation. Move to structured claims when you need claim-level evidence, audit trails, or automatic rejection of unsupported statements.
Edge cases to plan for
Multiple sources for one claim
Two chunks may support the same statement. Decide how the model should write this. Adjacent brackets, [1][3], are easiest to parse. State the rule in the prompt and test it, because models vary.
Claims from general knowledge
Some sentences, such as a transition or a definition of a common word, rely on no source. Decide whether these are allowed. A strict policy says every factual sentence needs a citation. A relaxed policy allows uncited connective text. Whichever you choose, say it in the prompt, or you will get inconsistent behavior.
Sources with repeated or overlapping text
When two chunks contain the same passage, the model may cite either one. If your evaluation uses hand-labeled correct ids, a correct but different chunk will be scored as wrong. Deduplicate chunks before building context, or accept either id in your labels.
Citation numbers in code answers
If answers can contain code with square brackets, a naive regular expression will treat items[1] as a citation to source 1. Restrict extraction to prose, or use a distinct marker style such as [^1] or 【1】 that does not appear in code.
Marker position
Ask the model to put the marker immediately after the statement, before the final period or after it, and pick one. A consistent position lets you attach the marker to the right sentence when you render or check claims.
Putting the choice into the prompt
Whatever format you choose, the prompt must define it concretely. The prompt should name the marker syntax, give one example, say what to do when two sources apply, and state that markers must come only from the numbers shown. The following snippet shows the structured version of this instruction:
STRUCTURED_INSTRUCTION = """Return only JSON with this shape:
{"answer": "...", "claims": [{"text": "...", "source_ids": [1], "quote": "..."}]}
Use only source numbers that appear in the sources below.
Each quote must be copied exactly from the cited source.
Every factual statement in the answer must appear as a claim."""Note the last line. It ties the free-text answer to the claims list, which reduces the mismatch described above.
Common errors
- Choosing the format after writing the validator. Pick the format first. The validator follows from it.
- Mixing styles in one prompt. Asking for
[1]markers in one place and "cite the title" in another produces mixed output. - Numbering from zero in the code and from one in the prompt. The
enumerate(chunks, start=1)call prevents this. An off-by-one error silently shifts every citation to the wrong source. - Treating a well-formed citation as a correct one. A valid marker only shows the number exists. It does not show the source supports the claim.
- Reusing numbers across turns. In a multi-turn chat, source
[2]in turn one and[2]in turn two may differ. Store the mapping with each answer.
Summary of the decision
- Use numeric inline markers for simple, streaming, low-risk assistants.
- Use stable named identifiers, or a number-to-id mapping, when you need to trace answers in logs.
- Use structured claims with quotes when you need claim-level evidence and automated checks.
- Use quote-first extraction when an unsupported statement is costly.
Exercise
Your team is building a compliance assistant. Answers are shown only after they finish generating, and an auditor must be able to confirm that each statement is backed by a passage in a policy document. Which citation format fits best, and what can your code check automatically with it?
Show answer
Structured claims with quotes (or quote-first extraction). Each claim carries source ids and a verbatim quote, so code can check that every id is within the supplied range and that every quote appears in the cited source text. Streaming is not required, so the extra output tokens and JSON parsing are acceptable. Code still cannot confirm that the quote actually supports the claim's meaning, so a separate support check is needed.
Exercise
An answer about a Python library contains the sentence "Use config[1] to read the second value." Your marker extractor uses the pattern \[(\d+)\] and the context has five sources. What goes wrong, and how can you prevent it?
Show answer
The extractor reads [1] inside config[1] as a citation to source 1, which may produce a false citation or hide a real validation problem. Prevent it by extracting markers only from prose outside code spans and code blocks, or by choosing a marker style that does not appear in code, such as [^1].