Understanding Citations and Source Attribution

Ma Mahalakshmi V Updated 16 Sep 2026
8 min read ·Lesson 68 of 224

Why Citations Matter More Than the Answer Itself

When a web-search-enabled response comes back, it is tempting to treat response.output_text as the entire deliverable. For many applications, that is a mistake. An answer without a visible source is a claim you are asking the user to trust blindly — and unlike a plain, ungrounded model response, a search-backed answer has actual evidence behind it that you can and should surface. Discarding that evidence throws away the main advantage of grounding in the first place.

Citations serve three distinct purposes, and it is worth separating them because each pushes toward different implementation choices:

  1. Trust. A user (or a downstream system) can independently verify a claim rather than taking the model's word for it.
  2. Debugging. When an answer turns out to be wrong, the citation tells you whether the model misread a good source, or whether the source itself was bad — two very different bugs with very different fixes.
  3. Compliance. Some domains — journalism, legal research, medical information — have obligations or strong norms around sourcing claims, and an application in those spaces may be required to show attribution, not just offer it as a nicety.

This lesson covers how citation information actually appears in a Responses API result, how to extract it reliably, and how to present it to a user in a way that keeps the connection between claim and source intact rather than losing it as an undifferentiated blob of links at the bottom.

Where Citation Data Lives in the Response

When the web search tool is used, the model's final message can include annotations that point back to the specific sources it drew from. These typically live nested inside the output message content, not as a flat top-level list, because a single answer can draw on several different sources for different parts of the same sentence.

from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-5.6-terra",
    tools=[{"type": "web_search"}],
    input="What is the current population of Iceland, and where did you find that figure?",
)

for item in response.output:
    if item.type == "message":
        for content_block in item.content:
            print("text:", content_block.text[:150])
            annotations = getattr(content_block, "annotations", [])
            for ann in annotations:
                print("  citation type:", ann.type)
                print("  url:", getattr(ann, "url", None))
                print("  title:", getattr(ann, "title", None))

This walks the response structure in three layers: response.output is the list of steps the model took, each message-type item has a content list (because a single message can be composed of multiple content blocks), and each content block can carry an annotations list identifying the specific source spans backing that text. Using getattr(ann, "url", None) instead of directly accessing ann.url is a defensive habit — it avoids crashing your program if a particular annotation object happens not to carry that attribute, which can happen if annotation shapes vary slightly across content types or API versions.

Note: The exact nesting — the annotation type name, and the specific attribute names like url and title — is a version-sensitive detail of the Responses API. Print the raw structure returned by your SDK version and check it against current documentation before writing production code that depends on these exact field names.

Extracting a Clean List of Sources

For most applications, you do not want to reproduce the entire nested walk above every time you need citations — you want a simple, flat list of the sources used, ready to render as a "Sources" section or footnote list.

from openai import OpenAI

client = OpenAI()


def get_citations(response) -> list[dict]:
    """Extract a de-duplicated list of source citations from a response."""
    seen_urls = set()
    citations = []

    for item in response.output:
        if item.type != "message":
            continue
        for content_block in item.content:
            for ann in getattr(content_block, "annotations", []) or []:
                url = getattr(ann, "url", None)
                if not url or url in seen_urls:
                    continue
                seen_urls.add(url)
                citations.append({
                    "url": url,
                    "title": getattr(ann, "title", url),
                })
    return citations


response = client.responses.create(
    model="gpt-5.6-terra",
    tools=[{"type": "web_search"}],
    input="What is the current speed record for a production electric car, and cite your source?",
)

for source in get_citations(response):
    print(f"- {source['title']}: {source['url']}")

The get_citations function does two useful things beyond the raw walk from the previous example. First, it de-duplicates by URL using a seen_urls set, since a model can legitimately cite the same source multiple times across different sentences, and you rarely want the same link listed five times in a "Sources" footer. Second, it falls back to using the URL itself as the title when no title annotation is present, via getattr(ann, "title", url), so downstream rendering code never has to handle a missing title as a special case — it always gets a usable string.

This function is a good candidate to keep as a small, tested utility in a real application, precisely because the underlying response structure is a nested, easy-to-get-wrong shape. Wrapping it once means every place in your codebase that needs citations calls the same well-tested function instead of re-implementing the walk with slightly different (and possibly buggy) logic each time.

Testing Citation Extraction Without Calling the API

Because get_citations is pure application logic — it processes a response object, it does not make an API call itself — it is a natural candidate for dependency-injection style testing with fake objects, rather than a live API call inside a test.

class FakeAnnotation:
    def __init__(self, url=None, title=None, ann_type="url_citation"):
        self.url = url
        self.title = title
        self.type = ann_type


class FakeContentBlock:
    def __init__(self, text, annotations=None):
        self.text = text
        self.annotations = annotations or []


class FakeMessageItem:
    def __init__(self, content):
        self.type = "message"
        self.content = content


class FakeSearchCallItem:
    def __init__(self):
        self.type = "web_search_call"


class FakeResponse:
    def __init__(self, output):
        self.output = output


def test_get_citations_deduplicates_and_falls_back_to_url():
    fake_response = FakeResponse(output=[
        FakeSearchCallItem(),
        FakeMessageItem(content=[
            FakeContentBlock(
                text="Iceland's population is about 380,000.",
                annotations=[
                    FakeAnnotation(url="https://example.org/iceland", title="Iceland Facts"),
                    FakeAnnotation(url="https://example.org/iceland", title="Iceland Facts"),
                ],
            ),
            FakeContentBlock(
                text="This figure is widely cited.",
                annotations=[
                    FakeAnnotation(url="https://example.org/other", title=None),
                ],
            ),
        ]),
    ])

    citations = get_citations(fake_response)

    assert len(citations) == 2, "duplicate URL should be collapsed to one entry"
    assert citations[0]["url"] == "https://example.org/iceland"
    assert citations[0]["title"] == "Iceland Facts"
    assert citations[1]["title"] == "https://example.org/other", "missing title should fall back to URL"

    print("PASS: get_citations deduplicates and falls back to URL for missing titles")


test_get_citations_deduplicates_and_falls_back_to_url()

This test builds a set of small fake classes — FakeAnnotation, FakeContentBlock, FakeMessageItem, FakeSearchCallItem, and FakeResponse — that mimic just enough of the real response object's shape for get_citations to run against them, without ever calling the actual API. This is the dependency-injection testing pattern used throughout this course: instead of mocking library internals or making a real network call (which would be slow, flaky, and cost money every time the test suite runs), you construct plain objects with exactly the attributes your function reads, and assert on the function's behavior against controlled input.

The test checks two things deliberately: that a duplicate URL collapses into a single citation, and that a missing title falls back to the URL. Both are edge cases that are easy to get wrong in the first draft of an extraction function, and both are exactly the kind of thing you want locked down by a test before this function ships inside a larger application like the research assistant built in Lesson 5.

Presenting Citations to Users

How you display citations depends on the interface, but a few patterns are worth calling out:

  • Inline citation markers (like [1], [2]) next to the claim they support, with a numbered source list at the end. This is the strongest form of attribution because it preserves the link between a specific sentence and its source, rather than one generic list at the bottom that could apply to anything in the response.
  • A flat "Sources" section, which is simpler to implement (exactly what get_citations produces) but weaker, since a user cannot tell which claim came from which link.
  • Hovercards or expandable references in a UI context, showing the source only when a user wants more detail, keeping the primary answer uncluttered.

For most application-building purposes in this course, producing the flat list from get_citations is the right starting point, and it is exactly what feeds into the research assistant built in the next lesson.

Common Mistakes

Discarding annotations and only using output_text, which causes you to lose the evidence trail entirely and forces users to trust the model's claim with no way to check it. Always check for citation annotations when the web search tool was used, even if your UI does not display them by default — you may need them later for debugging.

Not de-duplicating citations, which causes a cluttered, repetitive source list when the model legitimately references the same page multiple times across a longer answer. Track seen URLs, as shown in get_citations, before adding an entry to your final list.

Assuming every content block has annotations, which causes an AttributeError when a block that carries no citations (for instance, connective text the model wrote without needing a fresh source) is treated the same as one that does. Use a safe accessor pattern, such as getattr(content_block, "annotations", []), and always guard against None.

Best Practices

Always surface citations for any answer that depends on the web search tool, even in early prototypes, so that source quality problems (covered in Lesson 7) become visible during development rather than only in production.

Keep citation extraction as an isolated, tested utility function, separate from your prompt-building and display logic, so it can be unit tested with fake response objects and reused across every feature that touches web search.

Prefer inline, per-claim attribution over a single generic source list whenever your interface can support it, since it gives users the ability to judge which specific claims are well-supported and which are not.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Understanding Citations and Source Attribution and get answers drawn from it.

Signed-in readers only.