Skip to article
API429 / Field notes

Gemini URL Context with Structured Outputs: Citation and Schema Guide

Combine Gemini URL context and Grounding with Google Search with application-side JSON Schema validation, URL allowlists, and citation provenance checks.

Nested forms, metal brackets and a validation pencil
Editorial photo illustration: Nested forms, metal brackets and a validation pencil. Topic: Gemini URL Context with Structured Outputs: Citation and Schema Guide.

Combining external web evidence with structured JSON extraction introduces two distinct failure surfaces: the retrieval or grounding step can fail to fetch or cite a usable page, and the generation step can return truncated or schema-invalid JSON. This guide consolidates Gemini URL context extraction and search-grounded answer controls into one verification workflow so your application validates both citation provenance and JSON Schema compliance before persisting results.

Review Google's URL context documentation, Grounding with Google Search guide, and structured outputs specification to understand native tool behavior. When routing through an OpenAI-compatible gateway or direct provider endpoint, verify the exposed client contract in the API429 documentation and model catalog—never infer native tool or grounding support from a model name alone.

Separate URL context fetching, search grounding, and application crawlers

Google documents two distinct web-evidence tools in the Gemini API alongside application-managed retrieval:

  1. URL context (url_context): You supply explicit public URLs in the request so the model can read those pages. Google's documentation notes that URL context has its own retrieval status metadata (url_context_metadata), quota limits, and content restrictions (for example, paywalled pages, private intranets, or blocked robots paths cannot be read).
  2. Grounding with Google Search (google_search): The model issues search queries and returns groundingMetadata containing search queries, web source URIs, and grounding supports that link answer spans to retrieved passages.
  3. Application-owned fetch + structured extraction: Your worker fetches and sanitizes the HTML/PDF snapshot itself, stores a content hash, and passes the verified excerpt to POST /v1/chat/completions under your structured-output pipeline contract.
Evidence path Source control Provenance check required in app code When to use
Explicit URL context tool Caller supplies specific public URLs Verify url_context_metadata retrieval success and match cited URLs to the input allowlist Summarizing or extracting facts from known public pages on native Gemini endpoints
Grounding with Google Search Search tool selects live web results Inspect groundingMetadata chunks/supports; reject uncited claims when citations are mandatory Answering current-events or open-web questions with visible source attribution
Application fetch + OpenAI-compatible JSON extraction App fetches, snapshots, and hashes the document Validate JSON Schema and verify extracted quotes/fields against the stored snapshot Reproducible pipelines, authenticated sources, or gateway routes using standard chat completions

Prevent SSRF, unverified citations, and schema drift

Letting a pipeline submit arbitrary user-supplied URLs or accept grounded answers without inspecting metadata creates three operational hazards:

  • Unsafe or unstable target URLs: Always validate input URLs against an explicit HTTPS domain allowlist, block private IP ranges and localhost targets, and strip tracking tokens or session query parameters before submission.
  • Hallucinated or missing citations: A model can return valid JSON whose source_url field points to a URL that failed retrieval or was never in the grounding chunks. Your validator must cross-check every source_url in the parsed JSON object against the verified input allowlist or the returned grounding metadata URIs.
  • Unbounded retry amplification: Under Google Gemini API rate limits, tool-enabled calls consume both model token quotas and tool-specific quotas. If a target URL is dead (HTTP 404/403) or returns empty grounding supports, retrying the LLM call will not fix the broken web page. Classify retrieval failures separately from 429 Too Many Requests (RFC 6585 Section 4) and route transient 429s through your retry budget policy.

Runnable offline Python citation and schema validator

The standalone Python module below validates a structured extraction payload alongside retrieval/grounding metadata, ensuring that the JSON conforms to the required schema and every cited URL was actually retrieved from an approved HTTPS host:

import json
from dataclasses import dataclass
from urllib.parse import urlparse

@dataclass(frozen=True)
class CitedExtractionResult:
    status: str
    reason: str
    record: dict | None

def verify_https_allowlist(url: str, allowed_hosts: set[str]) -> bool:
    try:
        parsed = urlparse(url)
        return (
            parsed.scheme == "https"
            and bool(parsed.hostname)
            and parsed.hostname.lower() in allowed_hosts
            and not parsed.username
            and not parsed.password
        )
    except ValueError:
        return False

def validate_cited_extraction(
    raw_json: str,
    *,
    allowed_hosts: set[str],
    retrieved_urls: dict[str, str],
    require_exact_quote: bool = True,
) -> CitedExtractionResult:
    try:
        payload = json.loads(raw_json)
    except json.JSONDecodeError:
        return CitedExtractionResult("rejected", "json_parse_error", None)

    if not isinstance(payload, dict):
        return CitedExtractionResult("rejected", "root_must_be_object", None)

    for field in ("claim", "source_url", "supporting_quote"):
        if not isinstance(payload.get(field), str) or not payload[field].strip():
            return CitedExtractionResult("rejected", f"missing_or_empty:{field}", None)

    source_url = payload["source_url"].strip()
    if not verify_https_allowlist(source_url, allowed_hosts):
        return CitedExtractionResult("rejected", "source_url_not_in_allowlist", None)

    fetch_status = retrieved_urls.get(source_url)
    if fetch_status != "RETRIEVAL_SUCCESS":
        return CitedExtractionResult("rejected", f"url_not_retrieved:{fetch_status or 'missing'}", None)

    if require_exact_quote and len(payload["supporting_quote"].strip()) < 12:
        return CitedExtractionResult("rejected", "supporting_quote_too_short", None)

    return CitedExtractionResult("accepted", "verified_citation_and_schema", payload)

if __name__ == "__main__":
    hosts = {"ai.google.dev", "www.rfc-editor.org"}
    retrieved = {
        "https://ai.google.dev/gemini-api/docs/url-context": "RETRIEVAL_SUCCESS",
        "https://ai.google.dev/gemini-api/docs/missing": "RETRIEVAL_FAILED",
    }
    valid_sample = json.dumps({
        "claim": "URL context supports explicit public web pages.",
        "source_url": "https://ai.google.dev/gemini-api/docs/url-context",
        "supporting_quote": "You can provide public URLs to Gemini for context.",
    })
    unretrieved_sample = json.dumps({
        "claim": "Unsupported page claim.",
        "source_url": "https://ai.google.dev/gemini-api/docs/missing",
        "supporting_quote": "This page failed retrieval in metadata.",
    })
    print("Valid sample:", validate_cited_extraction(valid_sample, allowed_hosts=hosts, retrieved_urls=retrieved))
    print("Unretrieved URL:", validate_cited_extraction(unretrieved_sample, allowed_hosts=hosts, retrieved_urls=retrieved))

Coordinate token budgets and gateway routing

Fetched web pages and grounding passages expand input token counts unpredictably. Estimate input size before dispatch using the Gemini token counting guide and enforce per-task spending caps from the cost guardrails guide.

When connecting through API429, inspect the public OpenAPI specification, Google provider guide, and pricing page. If your workflow requires strict reproducibility across multiple models, fetch and clean the source text in your own worker first and send the bounded excerpt through POST /v1/chat/completions with application-side schema validation.

FAQ

Does structured JSON output guarantee that a cited URL was actually read?

No. JSON Schema validation checks only that source_url is formatted as a string. Your application must inspect url_context_metadata or groundingMetadata—or verify against your own fetched document snapshot—to confirm the URL was retrieved and supports the extracted claim.

Should a worker retry the Gemini API call when a target URL returns 404 or blocks fetching?

No. If the target web page is unreachable, paywalled, or blocked, repeating the LLM request wastes tokens and quota. Quarantine the broken URL or fall back to an application-fetched document snapshot.

Can any fallback model replace a search-grounded or URL-context Gemini call?

Only if the alternate route provides the same retrieval evidence or your application supplies the retrieved passages directly in the prompt. Never fail over a citation-required query to an ungrounded chat call without flagging that live web evidence is absent.

How should teams log URL-context and grounded extraction failures?

Record the job ID, schema_version, normalized target domain, retrieval status code, validation error code, and token usage. Do not log full scraped page bodies, private URLs with tokens, or API keys.

How do URL-context and search-grounding rate limits interact with model TPM?

Tool-enabled requests are evaluated against both the underlying Gemini model's request and input-token limits and the tool's own per-project quota. If your worker retries a failed extraction without checking whether the failure came from the web fetch or from HTTP 429 rate limiting, you can exhaust both tool and model quotas simultaneously.

Sources & further reading

  1. Google Gemini API — URL context tool
  2. Google Gemini API — Grounding with Google Search
  3. Google Gemini API — Structured outputs
  4. Google Gemini API — Rate limits
  5. RFC 6585 Section 4 — 429 Too Many Requests
  6. API429 — Client documentation
  7. API429 — Public OpenAPI specification

Put the next step into practice.

Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

Telegram