URL-Kontext

Mit dem Tool für den URL-Kontext können Sie dem Modell zusätzlichen Kontext in Form von URLs zur Verfügung stellen. Das Modell kann auf die Inhalte dieser URLs zugreifen, um seine Antwort zu fundieren und zu verbessern.

Der URL-Kontext bietet folgende Vorteile:

  • Daten extrahieren: Sie können spezifische Informationen wie Preise, Namen oder wichtige Ergebnisse aus einem Artikel oder mehreren URLs bereitstellen.

  • Informationen vergleichen: Sie können mehrere Berichte, Artikel oder PDFs analysieren, um Unterschiede zu erkennen und Trends zu verfolgen.

  • Inhalte zusammenfassen und erstellen: Sie können Informationen aus mehreren Quell-URLs kombinieren, um genaue Zusammenfassungen, Blogposts, Berichte oder Test fragen zu erstellen.

  • Code und technische Inhalte analysieren: Sie können URLs zu einem GitHub-Repository oder einer technischen Dokumentation bereitstellen, um Code zu erklären, Einrichtungsanleitungen zu generieren oder Fragen zu beantworten.

Beachten Sie die Best Practices und die Einschränkungen bei der Verwendung des Tools für den URL-Kontext.

Unterstützte Modelle

  • gemini-3.1-pro-preview
  • gemini-3-flash-preview
  • gemini-3.1-flash-lite-preview
  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite

Unterstützte Sprachen

Siehe unterstützte Sprachen für Gemini Modelle.

Tool für den URL-Kontext verwenden

Sie können das Tool für den URL-Kontext auf zwei Arten verwenden:

Nur Tool für den URL-Kontext

Klicken Sie auf Ihren Gemini API Anbieter, um anbieterspezifische Inhalte und Code auf dieser Seite aufzurufen.

Wenn Sie die GenerativeModel-Instanz erstellen, geben Sie UrlContext als Tool an. Geben Sie dann direkt in Ihrem Prompt die spezifischen URLs an, auf die das Modell zugreifen und die es analysieren soll.

Das folgende Beispiel zeigt, wie Sie zwei Rezepte von verschiedenen Websites vergleichen können:

Swift


import FirebaseAILogic

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
    modelName: "GEMINI_MODEL_NAME",
    // Enable the URL context tool.
    tools: [Tool.urlContext()]
)

// Specify one or more URLs for the tool to access.
let url1 = "FIRST_RECIPE_URL"
let url2 = "SECOND_RECIPE_URL"

// Provide the URLs in the prompt sent in the request.
let prompt = "Compare the ingredients and cooking times from the recipes at \(url1) and \(url2)"

// Get and handle the model's response.
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")

Kotlin


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Enable the URL context tool.
    tools = listOf(Tool.urlContext())
)

// Specify one or more URLs for the tool to access.
val url1 = "FIRST_RECIPE_URL"
val url2 = "SECOND_RECIPE_URL"

// Provide the URLs in the prompt sent in the request.
val prompt = "Compare the ingredients and cooking times from the recipes at $url1 and $url2"

// Get and handle the model's response.
val response = model.generateContent(prompt)
print(response.text)

Java


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Enable the URL context tool.
                        List.of(Tool.urlContext(new UrlContext())));

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Specify one or more URLs for the tool to access.
String url1 = "FIRST_RECIPE_URL";
String url2 = "SECOND_RECIPE_URL";

// Provide the URLs in the prompt sent in the request.
String prompt = "Compare the ingredients and cooking times from the recipes at " + url1 + " and " + url2 + "";

ListenableFuture response = model.generateContent(prompt);
  Futures.addCallback(response, new FutureCallback() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
          String resultText = result.getText();
          System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
          t.printStackTrace();
      }
  }, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Enable the URL context tool.
    tools: [{ urlContext: {} }]
  }
);

// Specify one or more URLs for the tool to access.
const url1 = "FIRST_RECIPE_URL"
const url2 = "SECOND_RECIPE_URL"

// Provide the URLs in the prompt sent in the request.
const prompt = `Compare the ingredients and cooking times from the recipes at ${url1} and ${url2}`

// Get and handle the model's response.
const result = await model.generateContent(prompt);
console.log(result.response.text());

Dart


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ai/firebase_ai.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  // Enable the URL context tool.
  tools: [
    Tool.urlContext(),
  ],
);

// Specify one or more URLs for the tool to access.
final url1 = "FIRST_RECIPE_URL";
final url2 = "SECOND_RECIPE_URL";

// Provide the URLs in the prompt sent in the request.
final prompt = "Compare the ingredients and cooking times from the recipes at $url1 and $url2";

// Get and handle the model's response.
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

Einheit


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Enable the URL context tool.
  tools: new[] { new Tool(new UrlContext()) }
);

// Specify one or more URLs for the tool to access.
var url1 = "FIRST_RECIPE_URL";
var url2 = "SECOND_RECIPE_URL";

// Provide the URLs in the prompt sent in the request.
var prompt = $"Compare the ingredients and cooking times from the recipes at {url1} and {url2}";

// Get and handle the model's response.
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

Informationen zum Auswählen eines Modells , der für Ihren Anwendungsfall und Ihre App geeignet ist

Klicken Sie auf Ihren Gemini API Anbieter, um anbieterspezifische Inhalte und Code auf dieser Seite aufzurufen.

Sie können sowohl den URL-Kontext als auch die Fundierung mit der Google Suche aktivieren. Mit dieser Konfiguration können Sie Prompts mit oder ohne bestimmte URLs schreiben.

Wenn auch die Fundierung mit der Google Suche aktiviert ist, verwendet das Modell möglicherweise zuerst die Google Suche, um relevante Informationen zu finden, und dann das Tool für den URL-Kontext, um den Inhalt der Suchergebnisse zu lesen und die Informationen besser zu verstehen. Dieser Ansatz ist hilfreich für Prompts, die sowohl eine breite Suche als auch eine detaillierte Analyse bestimmter Seiten erfordern.

Im Folgenden sind einige Anwendungsfälle beschrieben:

  • Sie geben im Prompt eine URL an, um bei der generierten Antwort zu helfen. Um eine geeignete Antwort zu generieren, benötigt das Modell jedoch weitere Informationen zu anderen Themen. Daher verwendet es das Tool für die Fundierung mit der Google Suche.

    Beispiel für einen Prompt:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • Sie geben im Prompt keine URL an. Um eine geeignete Antwort zu generieren, verwendet das Modell das Tool für die Fundierung mit der Google Suche, um relevante URLs zu finden, und dann das Tool für den URL-Kontext, um deren Inhalt zu analysieren.

    Beispiel für einen Prompt:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

Das folgende Beispiel zeigt, wie Sie beide Tools aktivieren und verwenden: URL-Kontext und Fundierung mit der Google Suche:


import FirebaseAILogic

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
    modelName: "GEMINI_MODEL_NAME",
    // Enable both the URL context tool and Google Search tool.
    tools: [
      Tool.urlContex(),
      Tool.googleSearch()
    ]
)

// Specify one or more URLs for the tool to access.
let url = "YOUR_URL"

// Provide the URLs in the prompt sent in the request.
// If the model can't generate a response using its own knowledge or the content in the specified URL,
// then the model will use the grounding with Google Search tool.
let prompt = "Give me a three day event schedule based on \(url). Also what do I need to pack according to the weather?"

// Get and handle the model's response.
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Enable both the URL context tool and Google Search tool.
    tools = listOf(Tool.urlContext(), Tool.googleSearch())
)

// Specify one or more URLs for the tool to access.
val url = "YOUR_URL"

// Provide the URLs in the prompt sent in the request.
// If the model can't generate a response using its own knowledge or the content in the specified URL,
// then the model will use the grounding with Google Search tool.
val prompt = "Give me a three day event schedule based on $url. Also what do I need to pack according to the weather?"

// Get and handle the model's response.
val response = model.generateContent(prompt)
print(response.text)

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Enable both the URL context tool and Google Search tool.
                        List.of(Tool.urlContext(new UrlContext()), Tool.googleSearch(new GoogleSearch())));

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Specify one or more URLs for the tool to access.
String url = "YOUR_URL";

// Provide the URLs in the prompt sent in the request.
// If the model can't generate a response using its own knowledge or the content in the specified URL,
// then the model will use the grounding with Google Search tool.
String prompt = "Give me a three day event schedule based on " + url + ". Also what do I need to pack according to the weather?";

ListenableFuture response = model.generateContent(prompt);
  Futures.addCallback(response, new FutureCallback() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
          String resultText = result.getText();
          System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
          t.printStackTrace();
      }
  }, executor);

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Enable both the URL context tool and Google Search tool.
    tools: [{ urlContext: {} }, { googleSearch: {} }],
  }
);

// Specify one or more URLs for the tool to access.
const url = "YOUR_URL"

// Provide the URLs in the prompt sent in the request.
// If the model can't generate a response using its own knowledge or the content in the specified URL,
// then the model will use the grounding with Google Search tool.
const prompt = `Give me a three day event schedule based on ${url}. Also what do I need to pack according to the weather?`

// Get and handle the model's response.
const result = await model.generateContent(prompt);
console.log(result.response.text());

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ai/firebase_ai.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  // Enable both the URL context tool and Google Search tool.
  tools: [
    Tool.urlContext(),
    Tool.googleSearch(),
  ],
);

// Specify one or more URLs for the tool to access.
final url = "YOUR_URL";

// Provide the URLs in the prompt sent in the request.
// If the model can't generate a response using its own knowledge or the content in the specified URL,
// then the model will use the grounding with Google Search tool.
final prompt = "Give me a three day event schedule based on $url. Also what do I need to pack according to the weather?";

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Enable both the URL context tool and Google Search tool.
  tools: new[] { new Tool(new GoogleSearch()), new Tool(new UrlContext()) }
);

// Specify one or more URLs for the tool to access.
var url = "YOUR_URL";

// Provide the URLs in the prompt sent in the request.
// If the model can't generate a response using its own knowledge or the content in the specified URL,
// then the model will use the grounding with Google Search tool.
var prompt = $"Give me a three day event schedule based on {url}. Also what do I need to pack according to the weather?";

// Get and handle the model's response.
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

// Make sure to comply with the "Grounding with Google Search" usage requirements,
// which includes how you use and display the grounded result

Informationen zum Auswählen eines Modells , der für Ihren Anwendungsfall und Ihre App geeignet ist

Funktionsweise des Tools für den URL-Kontext

Das Tool für den URL-Kontext verwendet einen zweistufigen Abrufprozess, um Geschwindigkeit, Kosten und Zugriff auf aktuelle Daten in Einklang zu bringen.

Schritt 1: Wenn Sie eine bestimmte URL angeben, versucht das Tool zuerst, den Inhalt aus einem internen Index-Cache abzurufen. Dieser dient als hochoptimierter Cache.

Schritt 2: Wenn eine URL nicht im Index verfügbar ist (z. B. wenn es sich um eine sehr neue Seite handelt), führt das Tool automatisch einen Live-Abruf durch. Dabei wird direkt auf die URL zugegriffen, um den Inhalt in Echtzeit abzurufen.

Best Practices

  • Bestimmte URLs angeben: Die besten Ergebnisse erzielen Sie, wenn Sie direkte URLs zu den Inhalten angeben, die das Modell analysieren soll. Das Modell ruft nur Inhalte von den von Ihnen angegebenen URLs ab, nicht von verschachtelten Links.

  • Zugänglichkeit prüfen: Prüfen Sie, ob die von Ihnen angegebenen URLs nicht zu Seiten führen, für die eine Anmeldung erforderlich ist oder die sich hinter einer Paywall befinden.

  • Vollständige URL verwenden: Geben Sie die vollständige URL einschließlich des Protokolls an (z. B. https://www.example.com anstelle von nur example.com).

Antwort verstehen

Die Antwort des Modells basiert auf den Inhalten, die es von den URLs abgerufen hat.

Wenn das Modell Inhalte von URLs abgerufen hat, enthält die Antwort url_context_metadata. Eine solche Antwort könnte etwa so aussehen (Teile der Antwort wurden aus Gründen der Kürze weggelassen):

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "... \n"
          }
        ],
        "role": "model"
      },
      ...
      "url_context_metadata":
      {
          "url_metadata":
          [
            {
              "retrieved_url": "https://www.example.com",
              "url_retrieval_status": "URL_RETRIEVAL_STATUS_SUCCESS"
            },
            {
              "retrieved_url": "https://www.example.org",
              "url_retrieval_status": "URL_RETRIEVAL_STATUS_SUCCESS"
            },
          ]
        }
    }
  ]
}

Sicherheitsprüfungen

Das System führt eine Inhaltsmoderationsprüfung für die URL durch, um zu bestätigen, dass sie den Sicherheitsstandards entspricht. Wenn die von Ihnen angegebene URL diese Prüfung nicht besteht, erhalten Sie für url_retrieval_status den Wert URL_RETRIEVAL_STATUS_UNSAFE.

Beschränkungen

Im Folgenden sind einige Einschränkungen des Tools für den URL-Kontext aufgeführt:

  • Kombination mit Funktionsaufrufen: Das Tool für den URL-Kontext kann nicht in einer Anfrage verwendet werden, in der auch Funktionsaufrufe verwendet werden.

  • Limit für URLs pro Anfrage: Die maximale Anzahl von URLs pro Anfrage beträgt 20.

  • Limit für die Größe von URL-Inhalten: Die maximale Größe für Inhalte, die von einer einzelnen URL abgerufen werden, beträgt 34 MB.

  • Aktualität: Das Tool ruft keine Live-Versionen von Webseiten ab. Daher kann es Probleme mit der Aktualität oder potenziell veralteten Informationen geben.

  • Öffentliche Zugänglichkeit von URLs: Die angegebenen URLs müssen im Web öffentlich zugänglich sein. Folgende Inhalte werden nicht unterstützt: Inhalte hinter einer Paywall, Inhalte, für die eine Nutzeranmeldung erforderlich ist, private Netzwerke, Localhost-Adressen (z. B. localhost oder 127.0.0.1) und Tunneling-Dienste (z. B. ngrok oder pinggy).

Unterstützte und nicht unterstützte Inhaltstypen

Unterstützt: Das Tool kann Inhalte aus URLs mit den folgenden Inhaltstypen extrahieren:

  • Text (text/html, application/json, text/plain, text/xml, text/css, text/javascript, text/csv, text/rtf)

  • Bild (image/png, image/jpeg, image/bmp, image/webp)

  • PDF (application/pdf)

Nicht unterstützt: Das Tool unterstützt die folgenden Inhaltstypen nicht:

  • YouTube-Videos (siehe stattdessen Videos analysieren)

  • Video- und Audiodateien (siehe stattdessen Videos analysieren oder Audio analysieren)

  • Google Workspace-Dateien wie Google-Dokumente oder ‑Tabellen

  • (bei Verwendung der Vertex AI Gemini API) Cloud Storage URLs
    Diese Arten von URLs werden von der Gemini Developer API unabhängig davon, wie Sie darauf zugreifen.

  • Inhalte, die nicht öffentlich zugänglich sind. Folgende Inhalte werden nicht unterstützt: Inhalte hinter einer Paywall, Inhalte, für die eine Nutzeranmeldung erforderlich ist, private Netzwerke, Localhost-Adressen (z. B. localhost oder 127.0.0.1) und Tunneling-Dienste (z. B. ngrok oder pinggy).

Preise und Zählen von Tool-Tokens

Von URLs abgerufene Inhalte werden als Eingabetokens gezählt.

Die Anzahl der Tokens für Ihren Prompt und die Nutzung von Tools finden Sie im Objekt usage_metadata der Modellausgabe. Hier ist ein Beispiel für eine Ausgabe:

'usage_metadata': {
  'candidates_token_count': 45,
  'prompt_token_count': 27,
  'prompt_tokens_details': [{'modality': <MediaModality.TEXT: 'TEXT'>,
    'token_count': 27}],
  'thoughts_token_count': 31,
  'tool_use_prompt_token_count': 10309,
  'tool_use_prompt_tokens_details': [{'modality': <MediaModality.TEXT: 'TEXT'>,
    'token_count': 10309}],
  'total_token_count': 10412
  }

Das Ratenlimit und die Preise basieren auf dem verwendeten Modell. Weitere Informationen zu den Preisen für das Tool für den URL-Kontext finden Sie in der Dokumentation Ihres ausgewählten Gemini API Anbieters: Gemini Developer API | Vertex AI Gemini API.