URL-Kontext

Mit dem Tool „URL-Kontext“ können Sie dem Modell zusätzlichen Kontext in Form von URLs bereitstellen. 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: Geben Sie spezifische Informationen wie Preise, Namen oder wichtige Erkenntnisse aus einem Artikel oder mehreren URLs an.

  • Informationen vergleichen: Analysieren Sie mehrere Berichte, Artikel oder PDFs, um Unterschiede zu erkennen und Trends zu verfolgen.

  • Inhalte zusammenfassen und erstellen: Informationen aus mehreren Quell-URLs kombinieren, um genaue Zusammenfassungen, Blogbeiträge, Berichte oder Testfragen zu erstellen.

  • Code und technische Inhalte analysieren: Geben Sie URLs zu einem GitHub-Repository oder einer technischen Dokumentation an, um Code zu erläutern, Einrichtungsanleitungen zu generieren oder Fragen zu beantworten.

Lesen Sie sich die Best Practices und die Einschränkungen für das Tool „URL-Kontext“ durch.

Unterstützte Modelle

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

Unterstützte Sprachen

Unterstützte Sprachen für Gemini-Modelle

URL-Kontexttool verwenden

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

Nur URL-Kontexttool

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

Wenn Sie die Instanz GenerativeModel 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.

Im folgenden Beispiel wird gezeigt, wie Sie zwei Rezepte von verschiedenen Websites vergleichen:

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.");

Hier erfahren Sie, wie Sie ein Modell auswählen, 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 die Fundierung mit der Google Suche ebenfalls aktiviert ist, kann das Modell zuerst die Google Suche verwenden, 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 besonders nützlich für Prompts, die sowohl eine breite Suche als auch eine detaillierte Analyse bestimmter Seiten erfordern.

Hier einige Anwendungsfälle:

  • Sie geben im Prompt eine URL an, um die generierte Antwort zu ergänzen. Um eine angemessene Antwort zu generieren, benötigt das Modell jedoch noch weitere Informationen zu anderen Themen. Daher wird das Tool zur Fundierung mit der Google Suche verwendet.

    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 überhaupt keine URL an. Um eine passende Antwort zu generieren, verwendet das Modell also das Tool zum Verankern mit der Google Suche, um relevante URLs zu finden, und analysiert dann deren Inhalt mit dem Tool für den URL-Kontext.

    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

Hier erfahren Sie, wie Sie ein Modell auswählen, der für Ihren Anwendungsfall und Ihre App geeignet ist.

Funktionsweise des Tools „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, die Inhalte aus einem internen Indexcache abzurufen. Dies dient als hochgradig optimierter Cache.

Schritt 2: Wenn eine URL nicht im Index verfügbar ist (z. B. bei einer sehr neuen Seite), wird automatisch ein Live-Abruf durchgeführt. Dadurch wird direkt auf die URL zugegriffen, um die Inhalte in Echtzeit abzurufen.

Best Practices

  • Geben Sie bestimmte URLs an: 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 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 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 in etwa so aussehen (aus Gründen der Übersichtlichkeit wurden Teile der Antwort 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"
            },
          ]
        }
    }
  ]
}

Sicherheitschecks

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

Beschränkungen

Hier sind einige Einschränkungen des Tools für den URL-Kontext:

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

  • Beschränkung der URLs pro Anfrage: Die maximale Anzahl von URLs pro Anfrage beträgt 20.

  • Größenbeschränkung für URL-Inhalte: 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 zu Problemen mit der Aktualität oder zu veralteten Informationen kommen.

  • Öffentliche Zugänglichkeit der URL: Die angegebenen URLs müssen im Web öffentlich zugänglich sein. Die folgenden 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 (Videos analysieren)

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

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

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

  • Inhalte, die nicht öffentlich zugänglich sind. Die folgenden 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

Inhalte, die über URLs abgerufen werden, werden als Eingabetokens gezählt.

Die Anzahl der Tokens für Ihren Prompt und die Nutzung von Tools finden Sie im usage_metadata-Objekt der Modellausgabe. Hier ein Beispiel für die 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
  }

Ratenbegrenzung und Preise richten sich nach dem verwendeten Modell. Weitere Informationen zur Preisgestaltung für das URL-Kontexttool finden Sie in der Dokumentation Ihres Gemini API-Anbieters: Gemini Developer API | Vertex AI Gemini API.