Back to Blog

Gemini API Grounding Citations: Fix Missing Sources

Tutorials and Guides8390
Gemini API Grounding Citations: Fix Missing Sources

The answer looks convincing. It mentions a recent product announcement, gives a date, and explains why the change matters. Your search assistant displays the paragraph perfectly. The source links are missing.

Adding “please include citations” to the prompt seems like an obvious repair. It may produce a bibliography-shaped answer, but that does not establish which search evidence supported each statement. If the API already returned structured citations and your gateway adapter discarded them, a prompt change addresses the wrong layer.

This article follows a hypothetical integration incident from the user interface back to the Gemini API response. It is a debugging exercise, not a claim about an outage at 4SAPI or Google. The goal is practical: preserve the relationship between a grounded answer, its citation annotations, and the interface shown to the person who requested it.

For a developer evaluating an API relay, this is a much stronger acceptance test than “the model returned text.” A search feature is only complete when the application receives and correctly presents the evidence that makes the answer useful.

The incident: a successful request and an incomplete product

Imagine a SaaS team adding a research panel to its customer dashboard. The backend calls a Gemini model with Google Search enabled. A generic adapter then turns the response into a familiar application object containing text, model, and usage.

The UI team receives that object and builds a polished answer card. Everything works until a customer asks where a particular claim came from. The backend engineer opens the original response and finds citation data that never reached the browser.

No component necessarily crashed. The loss happened because the adapter's definition of success was too narrow. It preserved the words while discarding the structure needed to interpret those words.

The first repair is therefore to change the response contract. A grounded answer needs more than a text field. It needs text blocks, their annotations, and the associated search presentation information required by the provider. Treat those fields as part of the feature, not optional debugging metadata.

If you are choosing a route through 4SAPI, begin with the gateway integration guide, then verify the exact Gemini operation. Compatibility with ordinary text generation is not proof of compatibility with every grounding response field.

Follow the evidence through four boundaries

The investigation becomes easier when each boundary has an explicit question.

BoundaryQuestionEvidence to inspect
Application requestWas Google Search configured?The serialized request, with credentials removed
Model operationDid this response contain search activity and citations?The native response shape
Gateway and adapterWere relevant fields preserved?A field-level comparison before UI normalization
User interfaceWere annotations applied to their original text?A deterministic rendering fixture

Do not skip directly to the browser. A response can lack citations because no search occurred, because the selected operation differs from the one your parser expects, or because the citation data was discarded upstream.

The official Google Search grounding guide documents search tools and citation annotations for the Interactions API. Enabling the tool does not mean every answer must invoke it. Inspect the actual response rather than labeling every successful request “search verified.”

This distinction also prevents misleading product copy. “Search available for this answer” and “this answer contains grounded claims” are different statements. Your interface should describe what happened on the request it is displaying.

Identify the API dialect before writing a parser

Gemini integration examples can describe different operations. The official Interactions overview explains the newer interaction structure, while existing integrations may still use generateContent.

The published 4SAPI native Gemini example documents a generateContent route. That page alone does not confirm an Interactions route or prove that grounding fields are preserved. Verify the operation and feature support available to your account before applying the parser below.

This article's code targets Interactions-style text blocks and URL citation annotations. A generateContent response requires an adapter for its own documented schema. Do not rename a few top-level fields and assume the two formats have identical citation semantics.

Similarly, selecting a model and selecting an operation are separate decisions. Google's current Gemini Carbon model documentation lists gemini-4-carbon and Google Search grounding support. That establishes native model capability; it does not establish availability, pricing, or complete feature forwarding on a third-party gateway.

For broader model integration background, see the existing Gemini developer guide. Keep model selection, route availability, and citation rendering as three independently testable parts of the integration.

Preserve each text block before decorating it

In the documented Interactions response, a model output can contain text blocks with URL citation annotations. The annotation includes a source URL, a title, and start and end offsets associated with that block's text.

An easy mistake is to concatenate every block, add a heading, normalize whitespace, translate the answer, and only then apply the original offsets. The numbers still exist, but they no longer refer to the text being displayed.

Apply annotations before transformations that change positions. Keep the original block alongside any derived display representation. If the product translates or rewrites the answer, do not carry old offsets into the new wording as though the alignment were unchanged.

This is particularly important when one backend serves several clients. A web client may collapse whitespace, a mobile client may replace punctuation, and an email renderer may flatten paragraphs. Each transformation needs a defined relationship to the original evidence markers.

The Gemini schema migration article discusses a related engineering habit: make the data contract explicit when response formats evolve. Here, the contract is about source alignment rather than nullable business fields.

A citation renderer with strict input checks

The following Python component renders one text block. It escapes text, restricts source links to HTTP or HTTPS, validates annotation ranges, and inserts reference markers at the end of the supported span. Numbering is local to the block.

This is a component test, not a complete grounding interface. It does not render Google Search Suggestions, manage provider attribution, or implement every display requirement. Those elements must be handled through the provider's supported presentation approach before shipping the feature.

python
import html
from urllib.parse import urlsplit


def render_cited_block(block):
    if block.get("type") != "text":
        raise ValueError("Expected an Interactions text block")
    text = block.get("text")
    if not isinstance(text, str):
        raise ValueError("The original text is required")

    markers = {}
    sources = []
    source_numbers = {}
    annotations = block.get("annotations", [])
    if not isinstance(annotations, list):
        raise ValueError("annotations must be a list")

    for item in annotations:
        if not isinstance(item, dict):
            raise ValueError("Invalid annotation")
        if item.get("type") != "url_citation":
            continue
        start, end = item.get("start_index"), item.get("end_index")
        if type(start) is not int or type(end) is not int:
            raise ValueError("Citation offsets must be integers")
        if not 0 <= start < end <= len(text):
            raise ValueError("Citation range is outside this text block")

        url = item.get("url")
        if not isinstance(url, str):
            raise ValueError("Citation URL is missing")
        parsed = urlsplit(url)
        if (parsed.scheme not in {"https", "http"}
                or not parsed.hostname or parsed.username or parsed.password
                or any(ord(c) < 32 for c in url)):
            raise ValueError("Unsafe or invalid citation URL")

        if url not in source_numbers:
            source_numbers[url] = len(sources) + 1
            title = item.get("title")
            sources.append((url, title if isinstance(title, str) else url))
        number = source_numbers[url]
        markers.setdefault(end, set()).add(number)

    pieces = []
    previous = 0
    for end in sorted(markers):
        pieces.append(html.escape(text[previous:end]))
        for number in sorted(markers[end]):
            url = sources[number - 1][0]
            pieces.append(
                '<sup><a href="' + html.escape(url, quote=True) + '">'
                + str(number) + '</a></sup>'
            )
        previous = end
    pieces.append(html.escape(text[previous:]))

    references = [
        {"number": i + 1, "url": url, "title": title}
        for i, (url, title) in enumerate(sources)
    ]
    return {"answer_html": "".join(pieces), "references": references}

The returned reference titles remain plain data. If you render them as HTML elsewhere, escape them there too. Do not treat a title or URL as trusted executable markup.

This example uses Python string indexing, consistent with the slicing approach shown in Google's guide. When porting it to another language, verify offset behavior with non-ASCII text and real response fixtures. JavaScript string positions, Unicode code points, and encoded byte positions are not interchangeable concepts.

A renderer should also avoid silently concealing malformed annotations. In development, reject invalid fixtures. In production, use a defined fallback that makes the absence of reliable citations visible rather than attaching a source to an unrelated sentence.

Inspect a native request before testing a relay

Here is the shape of a native Google Interactions request for a development experiment. Supply a currently supported model identifier and use Google's own credential for this native endpoint. A 4SAPI credential belongs only on its documented gateway endpoint.

json
{
  "model": "gemini-4-carbon",
  "input": "Find the official announcement for the latest stable release of Python and cite the source.",
  "tools": [{"type": "google_search"}],
  "store": false
}

The documented native operation is POST https://generativelanguage.googleapis.com/v1beta/interactions. Google's current examples use an x-goog-api-key credential and an Api-Revision header. Consult the live documentation for the revision your client targets rather than assuming a gateway accepts those headers unchanged.

This sample is not a recorded benchmark or a promise about which source the model will choose. It gives you a small request whose response structure is easy to inspect. Run native and gateway tests only on routes and credentials you are authorized to use, and compare the fields relevant to your application.

The comparison should answer a narrow question: can this route carry the grounded-search feature needed by this product? It should not become an attempt to force all providers into one text-only abstraction.

Search discovery is different from opening a supplied URL

A customer may ask your assistant to find an announcement, or may paste the announcement and ask for a summary. These are different retrieval tasks. Google's URL context documentation describes working with provided URLs; Google Search grounding addresses search-driven discovery.

The existing 4SAPI URL-context retrieval check is useful when a supplied page was not successfully accessed. That failure should not be diagnosed by changing the citation renderer. First establish which retrieval mechanism the request actually used.

Likewise, an annotated answer does not prove that every statement in the paragraph has equal support. A product can help users by keeping citations close to their associated text and avoiding a single decorative “sources” badge for an entire conversation.

If your application also supports Claude search, the Claude web-search domain controls guide provides a separate provider-specific discussion. Reuse the product-level evidence standard, while retaining the protocol details appropriate to each provider.

Display and retention requirements belong in the acceptance criteria

Review Google's current terms for Grounding with Google Search. They include requirements concerning associated Search Suggestions and restrictions on use and retention. A citation renderer alone does not satisfy the complete feature contract.

Keep Search Suggestions separate from the escaped answer text and render them through an appropriate supported integration. Do not blindly insert arbitrary tool output as trusted HTML. Equally, do not strip required search presentation elements merely because a generic adapter has nowhere to store them.

Avoid designing a reusable scraped-link database or click-tracking system from grounding output without first confirming that the intended use is permitted. For product conversion analysis, measure your own documentation and registration calls to action separately; do not attach those analytics assumptions to source links in grounded results.

Your development fixtures also need a retention policy. Prefer synthetic fixtures for routine renderer tests. When real responses are necessary, limit access and retention to what the applicable terms and your application's requirements allow.

Close the incident with observable behavior

A useful regression set includes two text blocks, several citations on one span, repeated source URLs, accented characters, emoji, missing annotations, malformed ranges, and HTML-like text. Test the renderer without making paid model calls. Then perform a small live feature test on the chosen route.

Success means that the user receives the original answer with correctly attached evidence and the required search presentation. It also means that an unsupported or ungrounded response is represented honestly. The UI must not fabricate confidence by generating source links that were never present in the evidence structure.

During multi-turn work, preserve the other protocol information that the operation requires. The Gemini thought-signature integration guide covers a different category of state that a text-only adapter can accidentally lose.

For a team evaluating 4SAPI, the next step is specific: use the API documentation to confirm the operation, model, grounding capability, and returned metadata for the intended route. If those requirements are met, create a development token and run the citation fixture through your own application before moving customer traffic.

The value of the evaluation is a working search experience with evidence users can inspect. That is the feature a developer should register to test—and the feature an enterprise should require before approving production use.

Tags:Gemini API grounding citationsGemini Carbon API search citationsGemini Google Search grounding gatewayGemini citation annotationsGemini missing sources API

Recommended reading

Explore more frontier insights and industry know-how.