Sub topic 6
Citations and annotations: showing your sources
This chapter assumes you can call the Responses API or the Messages API and read a response object in Python. It also assumes you have read the earlier chapters on enabling web search and on the tool-call items in a response. Here you will learn how a provider attaches sources to the answer text, how to turn those attachments into links a reader can check, and what the attachments do and do not prove.
What a citation is in the response
When a built-in tool such as web search or file search supplies facts, the provider can mark which parts of the answer came from which source. These markers are called annotations (OpenAI) or citations (Anthropic). They are structured data next to the text. They are not links written into the text by the model.
This has three consequences:
- You decide how citations look. You can render footnotes, inline links, hover cards, or a source list.
- You can store citations separately from the text, for audit logs or for a "sources" panel.
- A missing citation is a signal you can check in code. If the answer has no annotations, no source was attached to it.
OpenAI: annotations on output text
In the Responses API, the answer lives in an item of type message. Its content is a list of parts. A part of type output_text has a text string and an annotations list. Each annotation has a type:
| Annotation type | Produced by | Key fields |
|---|---|---|
| `url_citation` | Web search | `url`, `title`, `start_index`, `end_index` |
| `file_citation` | File search | `file_id`, `filename`, `index` |
For url_citation, start_index and end_index are character offsets into that part's text. They mark the span the source supports. A single sentence can carry several annotations, and the same URL can appear many times.
The annotations belong to one content part, not to the whole response. If you join several parts into one string, the offsets no longer line up. Keep each part's text and annotations together while you process them.
Anthropic: citations on text blocks
Anthropic returns a list of content blocks. With web search enabled, the list mixes block types:
server_tool_useis the search the provider ran, with the query.web_search_tool_resultholds the raw results the provider found.textblocks hold the answer. A text block can have acitationslist.
Each web citation has type: "web_search_result_location" and fields such as url, title, and cited_text, a short excerpt from the page. Anthropic attaches citations to whole text blocks. The model often splits an answer into several blocks, so the citation sits on the block that contains the claim. There are no character offsets to splice.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 3}],
messages=[
{"role": "user", "content": "What are the latest developments in solid-state batteries?"}
],
)
for block in message.content:
if block.type != "text":
continue
print(block.text)
for cite in getattr(block, "citations", None) or []:
print(" source:", cite.title, cite.url)
print(" excerpt:", cite.cited_text[:120])The cited_text field is useful for audits. It shows what the provider says it relied on, so you can compare it with the claim.
Turning OpenAI annotations into footnotes
The usual job is to produce text with numbered markers and a source list. Two details cause most bugs. You must number sources in reading order, and you must insert markers from the end of the string backward. Inserting at the front shifts every later offset.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "web_search"}],
input="What are the most recent stable releases of Python?",
)
def render_with_sources(response):
numbers = {} # (title, url) -> footnote number
rendered = []
for item in response.output:
if item.type != "message":
continue
for part in item.content:
if part.type != "output_text":
continue
cites = [
a for a in (part.annotations or []) if a.type == "url_citation"
]
# Pass 1: number sources in reading order.
for ann in sorted(cites, key=lambda a: a.end_index):
numbers.setdefault((ann.title, ann.url), len(numbers) + 1)
# Pass 2: insert markers from the end so earlier offsets stay valid.
text = part.text
for ann in sorted(cites, key=lambda a: a.end_index, reverse=True):
n = numbers[(ann.title, ann.url)]
text = text[: ann.end_index] + f"[{n}]" + text[ann.end_index :]
rendered.append(text)
lines = ["\n".join(rendered), "", "Sources:"]
for (title, url), n in sorted(numbers.items(), key=lambda kv: kv[1]):
lines.append(f"[{n}] {title} - {url}")
return "\n".join(lines)
print(render_with_sources(response))If you are not sure whether your SDK version counts offsets in Python characters, test with an answer that contains an emoji or an accented character. A drift of a few characters means the offsets use a different unit than Python string indices.
Where citations sit in the response
The web_search_call item tells you that a search happened. The annotations on the message tell you which parts of the answer used the results. These are different facts, so check both.
File citations
File search uses the same structure, with a different annotation type. A file_citation carries file_id and filename. It does not carry a URL, because your documents are not on the web. To show the reader something useful, keep your own map from file_id to a title or a link in your document system. If you use the filename directly, it may be a raw upload name that means little to a reader.
def file_sources(response):
found = {}
for item in response.output:
if item.type != "message":
continue
for part in item.content:
if part.type != "output_text":
continue
for ann in part.annotations or []:
if ann.type == "file_citation":
found[ann.file_id] = ann.filename
return foundWhat citations do not prove
A citation says the provider linked a span of the answer to a source. It does not say the source supports the claim. These are the common errors:
- Trusting the link without reading it. The model can paraphrase wrongly or combine two pages. For high-stakes answers, compare the claim with
cited_text(Anthropic) or fetch the page yourself. - Treating no citation as no source. The model can state a fact from its training data even when search ran. Uncited sentences are not grounded in the search results.
- Dropping citations when you post-process. If you strip, trim, or reformat the answer text, OpenAI offsets stop matching. Rebuild the markers from the original text, or recompute the offsets.
- Counting citations as quality. Five citations to one low-quality site is weaker than one citation to a primary source. Group by domain before you decide how much to trust an answer.
- Hiding the citation requirement from users. Some providers require that you show web search citations to end users. Read the current terms for your provider.
Storing citations for audit
Save the raw output list, or at least the annotations and the web_search_call items, with the request ID. If a user disputes an answer later, you can show which URL was cited and when. Page content changes, so a stored cited_text or a saved copy of the page is stronger evidence than a URL alone.
Exercise
Your code inserts footnote markers like "[1]" into an OpenAI answer, but they land in the wrong places after the second marker. The code loops over annotations in ascending order of end_index and inserts each marker into the string. What is wrong, and how do you fix it?
Show answer
Each insertion makes the string longer, so the offsets of all later annotations point to the wrong position. Process the annotations in descending order of end_index, so insertions near the end never move text that earlier annotations still refer to. Assign the footnote numbers in a separate first pass in ascending order, so the numbers still follow reading order.
Exercise
A response used file search and contains a file_citation annotation, but your UI shows a blank source link. Why, and what should you do?
Show answer
A file_citation has file_id and filename but no URL, because the source is a document in your vector store. Keep a mapping from file_id to a title or a link in your own system, and render that. Fall back to filename if no mapping exists.