Kontekst adresu URL

Narzędzie kontekstu adresu URL umożliwia dostarczanie modelowi dodatkowego kontekstu w postaci adresów URL. Model może uzyskać dostęp do treści z tych adresów URL, aby ulepszyć swoją odpowiedź.

Kontekst adresu URL ma te zalety:

  • Wyodrębnianie danych: podawanie konkretnych informacji, takich jak ceny, nazwy lub kluczowe wnioski z artykułu lub wielu adresów URL.

  • Porównywanie informacji: analizuj wiele raportów, artykułów lub plików PDF, aby identyfikować różnice i śledzić trendy.

  • Syntezowanie i tworzenie treści: łączenie informacji z kilku adresów URL, aby generować dokładne podsumowania, posty na blogu, raporty lub pytania testowe.

  • Analizowanie kodu i treści technicznych: podaj adresy URL repozytorium GitHub lub dokumentacji technicznej, aby wyjaśnić kod, wygenerować instrukcje konfiguracji lub odpowiedzieć na pytania.

Korzystając z narzędzia Kontekst adresu URL, zapoznaj się ze sprawdzonymi metodami i ograniczeniami.

Obsługiwane modele

  • gemini-3.1-pro-preview
  • gemini-3.8-flash (oraz starsze wersje gemini-3.7-flash, gemini-3.6-flash i gemini-3.5-flash)
  • gemini-3.5-flash-lite (i starszy gemini-3.1-flash-lite)

Ogólne modele Gemini 2.5 obsługują tę funkcję, ale wszystkie zostały wycofane.

Obsługiwane języki

Zobacz obsługiwane języki w przypadku Gemini modeli.

Korzystanie z narzędzia kontekstu adresu URL

Narzędzia kontekstu adresu URL możesz używać na 2 główne sposoby:

Tylko narzędzie kontekstu adresu URL

Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod dostawcy.

Podczas tworzenia instancji GenerativeModel podaj UrlContext jako narzędzie. Następnie w prompcie podaj konkretne adresy URL, do których model ma uzyskać dostęp i które ma przeanalizować.

Poniższy przykład pokazuje, jak porównać 2 przepisy z różnych witryn:

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

Unity


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

Dowiedz się, jak wybrać model odpowiednie do Twojego przypadku użycia i aplikacji.

Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod dostawcy.

Możesz włączyć zarówno kontekst adresu URL, jak i oparcia na faktach za pomocą Google Search. W tej konfiguracji możesz pisać prompty z konkretnymi adresami URL lub bez nich.

Jeśli włączona jest też funkcja Grounding with Google Search, model może najpierw użyć Google Search do znalezienia odpowiednich informacji, a potem użyć narzędzia kontekstowego URL, aby odczytać zawartość wyników wyszukiwania i dokładniej zrozumieć informacje. To podejście jest przydatne w przypadku promptów, które wymagają zarówno szerokiego wyszukiwania, jak i dogłębnej analizy konkretnych stron.

Oto kilka przykładów zastosowań:

  • W prompcie podajesz adres URL, aby pomóc w wygenerowaniu odpowiedzi. Aby jednak wygenerować odpowiednią odpowiedź, model nadal potrzebuje więcej informacji na inne tematy, dlatego korzysta z narzędzia Grounding with Google Search.

    Przykładowy prompt:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • W prompcie nie podajesz adresu URL. Aby wygenerować prawidłową odpowiedź, model korzysta z narzędzia Grounding with Google Search do znajdowania odpowiednich adresów URL, a następnie z narzędzia URL context do analizowania ich zawartości.

    Przykładowy prompt:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

Poniższy przykład pokazuje, jak włączyć i używać obu narzędzi – kontekstu adresu URL i Google Search:


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

Dowiedz się, jak wybrać model odpowiednie do Twojego przypadku użycia i aplikacji.

Jak działa narzędzie kontekstu adresu URL

Narzędzie kontekstu adresu URL korzysta z dwuetapowego procesu pobierania, aby zachować równowagę między szybkością, kosztem i dostępem do aktualnych danych.

Krok 1. Gdy podasz konkretny adres URL, narzędzie najpierw spróbuje pobrać treść z wewnętrznej pamięci podręcznej indeksu. Działa ona jak wysoce zoptymalizowana pamięć podręczna.

Krok 2. Jeśli adres URL nie jest dostępny w indeksie (np. jest to bardzo nowa strona), narzędzie automatycznie przełącza się na pobieranie wersji opublikowanej. Bezpośrednio uzyskuje dostęp do adresu URL, aby pobrać jego zawartość w czasie rzeczywistym.

Sprawdzone metody

  • Podaj konkretne adresy URL: aby uzyskać najlepsze wyniki, podaj bezpośrednie adresy URL treści, które mają być analizowane przez model. Model będzie pobierać treści tylko z podanych przez Ciebie adresów URL, a nie z linków zagnieżdżonych.

  • Sprawdź dostępność: upewnij się, że podane adresy URL nie prowadzą do stron, które wymagają logowania lub są umieszczone w sekcji płatnej.

  • Używaj pełnego adresu URL: podaj pełny adres URL, w tym protokół (np. https://www.example.com zamiast tylko example.com).

Interpretowanie odpowiedzi

Odpowiedź modelu będzie oparta na treściach pobranych z tych adresów URL.

Jeśli model pobrał treści z adresów URL, odpowiedź będzie zawierać element url_context_metadata. Odpowiedź może wyglądać mniej więcej tak (dla zwięzłości pominięto niektóre jej części):

{
  "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"
            },
          ]
        }
    }
  ]
}

Sprawdzanie bezpieczeństwa

System przeprowadza weryfikację treści pod kątem zgodności z zasadami, aby potwierdzić, że adresy URL spełniają standardy bezpieczeństwa. Jeśli podany przez Ciebie adres URL nie przejdzie tego testu, otrzymasz url_retrieval_status URL_RETRIEVAL_STATUS_UNSAFE.

Ograniczenia

Oto niektóre ograniczenia narzędzia kontekstu adresu URL:

  • Łączenie z wywoływaniem funkcji: narzędzia kontekstu adresu URL nie można używać w żądaniu, które korzysta też z wywoływania funkcji.

  • Limit adresów URL na żądanie: maksymalna liczba adresów URL na żądanie to 20.

  • Limit rozmiaru treści URL: maksymalny rozmiar treści pobranych z jednego adresu URL to 34 MB.

  • Aktualność: narzędzie nie pobiera aktualnych wersji stron internetowych, więc mogą występować problemy z aktualnością lub potencjalnie nieaktualne informacje.

  • Publiczna dostępność adresu URL: podane adresy URL muszą być publicznie dostępne w internecie. Nie są obsługiwane: treści za paywallem, treści wymagające zalogowania się użytkownika, sieci prywatne, adresy localhost (np. localhost lub 127.0.0.1) oraz usługi tunelowania (np. ngrok lub pinggy).

Obsługiwane i nieobsługiwane typy treści

Obsługiwane: narzędzie może wyodrębniać treści z adresów URL o tych typach treści:

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

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

  • PDF (application/pdf)

Nieobsługiwane: narzędzie nie obsługuje tych typów treści:

  • filmy na YouTube (zamiast tego zobacz analizowanie filmów)

  • Pliki wideo i audio (zamiast tego zobacz analizowanie filmów lub analizowanie dźwięku)

  • pliki Google Workspace, takie jak Dokumenty Google lub arkusze kalkulacyjne;

  • (jeśli używasz Agent Platform Gemini API (formerly Vertex AI)) Cloud Storageadresy URL
    Te typy adresów URL nie są obsługiwane przez Gemini Developer API, niezależnie od tego, jak uzyskujesz do niego dostęp.

  • treści, które nie są dostępne publicznie; Nie są obsługiwane: treści za paywallem, treści wymagające zalogowania się użytkownika, sieci prywatne, adresy localhost (np. localhost lub 127.0.0.1) oraz usługi tunelowania (np. ngrok lub pinggy).

Tokeny narzędzia do określania cen i liczenia

Treści pobrane z adresów URL są liczone jako tokeny wejściowe.

Liczbę tokenów w prompcie i użycie narzędzi możesz sprawdzić w obiekcie usage_metadata danych wyjściowych modelu. Oto przykładowe dane wyjściowe:

'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
  }

Limit liczby żądań i cena zależą od używanego modelu. Więcej informacji o cenach narzędzia do sprawdzania kontekstu adresu URL znajdziesz w dokumentacji wybranego dostawcy Gemini API:Gemini Developer API | Agent Platform Gemini API (formerly Vertex AI).