Sub topic 10
Showing citations to users
This chapter covers the last step of the citation pipeline: turning validated [n] markers into links and a source list that a person can read and follow. It assumes you can read Python and regular expressions, and that you have already validated markers against the supplied sources (see "Validating citation markers in code"). Rendering comes after validation, because a pretty link to the wrong place is worse than no link.
Rendering is a separate step
The model writes markers like [2] because they are cheap and easy to produce. Users need something different:
- A clickable link that opens the source.
- A readable label such as a title or domain.
- A list of sources at the end, so they can see everything the answer relied on.
- No broken or invented references.
Keeping these concerns outside the prompt has two benefits. You can change the interface without changing the prompt. You also never let the model write URLs. The URL always comes from your own chunk metadata, looked up by source number.
The simplest renderer
The baseline replaces each marker with a Markdown link to the matching source.
import re
def render_with_links(answer, sources):
"""sources: list of dicts with 'url'. Replaces [n] with a Markdown link to source n."""
def repl(match):
n = int(match.group(1))
if 1 <= n <= len(sources):
return f"[[{n}]]({sources[n - 1]['url']})"
return match.group(0)
return re.sub(r"\[(\d+)\]", repl, answer)Two details matter here. Sources are numbered from 1, so source n sits at index n - 1. An out-of-range marker is left unchanged, which is safe for the program but confusing for a reader. A stray [7] with no link looks like a broken citation.
This version is fine for a prototype. It has four weaknesses for production:
- Out-of-range markers stay visible.
- Numbers appear in the order the context was built, not the order the reader meets them, so an answer may start with
[3]. - There is no source list.
- URLs are inserted without any check.
Handling invalid markers
You have three options for a marker that points to no source.
| Option | What the user sees | When to use it |
|---|---|---|
| Leave it as plain text | A bare `[7]` | Debugging builds only |
| Remove it | The sentence with no citation | Most user-facing products |
| Remove it and flag the answer | A note that some statements could not be traced | Regulated or high-stakes settings |
Removing the marker hides the problem from the user, so log every removal. A rising count of invalid markers is a signal that the prompt or the model needs attention. If the answer ends up with no valid citations at all, treat that as a quality problem. Show the answer with a visible "no sources" notice, or fall back to your abstention reply.
Renumbering by first appearance
If the model cites [3], then [1], a reader sees a list that starts in the middle. Also, if the model used only 2 of 6 supplied sources, you should list only those 2. Renumber markers by order of first use, and show only cited sources.
A complete renderer
The function below validates, renumbers, restricts URLs to http and https, escapes characters that would break Markdown, and appends a source list.
import re
from urllib.parse import urlparse
MARKER = re.compile(r"[ \t]*\[(\d+)\]")
def is_safe_url(url):
return urlparse(url).scheme in ("http", "https")
def link_url(url):
return url.replace(" ", "%20").replace("(", "%28").replace(")", "%29")
def escape_text(text):
for ch in "[]\\":
text = text.replace(ch, "\\" + ch)
return text
def render_answer(answer, sources):
"""Return Markdown with numbered links and a source list.
sources: list of dicts with 'url' and optional 'title'.
Markers that match no usable source are removed.
"""
order = [] # original source numbers, in order of first use
def repl(match):
n = int(match.group(1))
if not 1 <= n <= len(sources) or not is_safe_url(sources[n - 1]["url"]):
return ""
if n not in order:
order.append(n)
label = order.index(n) + 1
space = match.group(0)[: match.start(1) - match.start(0)]
# keep the original leading space before the marker
space = match.group(0).split("[")[0]
return f"{space}[[{label}]]({link_url(sources[n - 1]['url'])})"
body = MARKER.sub(repl, answer)
if not order:
return body
lines = []
for label, n in enumerate(order, start=1):
src = sources[n - 1]
title = escape_text(src.get("title") or src["url"])
lines.append(f"{label}. [{title}]({link_url(src['url'])})")
return body + "\n\nSources:\n" + "\n".join(lines)
if __name__ == "__main__":
sources = [
{"url": "https://docs.example.com/overview", "title": "Overview"},
{"url": "https://docs.example.com/retries", "title": "Retry policy"},
{"url": "https://docs.example.com/timeouts", "title": "Timeouts"},
]
answer = (
"Failed requests are retried up to three times [2]. "
"Each attempt times out after 10 seconds [3]. "
"Retries are logged [2][9]."
)
print(render_answer(answer, sources))Running it prints:
Failed requests are retried up to three times [[1]](https://docs.example.com/retries). Each attempt times out after 10 seconds [[2]](https://docs.example.com/timeouts). Retries are logged [[1]](https://docs.example.com/retries).
Sources:
1. [Retry policy](https://docs.example.com/retries)
2. [Timeouts](https://docs.example.com/timeouts)Source 2 became label 1 because it was cited first. Source 1 ("Overview") is not listed because the answer never used it. The [9] marker was removed, along with the space in front of it. The same source cited twice keeps one label.
Edge cases to handle
- Grouped markers. Models sometimes write
[1, 2]or[1-3]. The regex above does not match these, so they pass through as plain text. Either forbid them in the prompt or normalize them to[1][2]before validation, so that validation and rendering both see them. - Markers in code. A source or answer may contain a Python snippet such as
items[1]. Because the regex matches digits in brackets, it would turn that into a link. If answers can contain code, skip fenced code blocks and inline code spans when substituting. - Existing Markdown links. If the model writes
[1](http://...)itself, the renderer may double-link it. Tell the model in the prompt to use bare markers only. - Titles with brackets. A title like
Config [legacy]would end the link text early. That is whatescape_textprevents. - Streaming. If you render tokens as they arrive, a marker can be split across chunks (
[in one,2]in the next). Buffer from an opening[until you see]or a character that cannot be part of a marker, then render.
What users need besides a link
A link to a whole page answers "where is this from?" but not "which part supports this sentence?" Consider these additions:
- Hover or tap preview. Show the title and the retrieved chunk text next to the marker. Because you already hold the chunk, this costs nothing.
- Quoted evidence. If you use structured claims with verified quotes, show the quote under the claim.
- Deep links. Where your chunk metadata includes a heading anchor or page number, append it to the URL. Many current browsers also support text fragments (
#:~:text=), which highlight a quoted passage on the destination page. - Honest labelling. A citation shows where the system found something. It does not prove the claim is right. Avoid wording such as "verified" unless you ran a support check.
Testing the renderer
Rendering is deterministic, so test it with plain assertions. Cover at least: an out-of-range marker, a repeated marker, markers cited out of order, an unsafe scheme, a title with brackets, and an answer with no markers. Keep the expected outputs as fixtures so a change in formatting shows up as a failing test.
Exercise
Using render_answer with three valid sources, what does it return for the answer "See the policy [4].", and what should the application do next?
Show answer
The marker [4] matches no source, so it is removed together with the space before it, and no source list is added. The function returns "See the policy.". The application should log the invalid marker and treat the answer as having no usable citations, for example by showing a "no sources" notice or falling back to the abstention reply.
Exercise
Why does the renderer renumber markers by first appearance instead of keeping the original source numbers?
Show answer
Original numbers reflect the order of the retrieved chunks, not the order the reader sees them. An answer could open with [3] and skip [1] and [2], which looks like missing references. Renumbering gives a contiguous list that starts at 1, and it lets you show only the sources the answer actually used.
Exercise
A source title contains the text Setup [v2]. What goes wrong if you place it directly in a Markdown link, and which function in this chapter prevents it?
Show answer
The closing ] in the title ends the link text early, so the link renders incorrectly. escape_text adds a backslash before [, ] and \, which keeps the title intact.