Kontekst adresu URL

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

Kontekst adresu URL ma te zalety:

  • Wyodrębnianie danych: podawaj konkretne informacje, takie 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.

  • Synteza i tworzenie treści: łącz informacje z kilku źródłowych adresów URL, aby generować dokładne podsumowania, posty na blogu, raporty lub pytania testowe.

  • Analizowanie kodu i treści technicznych: podawaj adresy URL repozytorium GitHub lub dokumentacji technicznej, aby wyjaśniać kod, generować instrukcje konfiguracji lub odpowiadać na pytania.

Podczas korzystania z narzędzia kontekstu adresu URL zapoznaj się ze sprawdzonymi metodami i ograniczeniami.

Obsługiwane modele

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

Obsługiwane języki

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

Korzystanie z narzędzia kontekstu adresu URL

Z narzędzia kontekstu adresu URL możesz korzystać na 2 główne sposoby:

Tylko narzędzie kontekstu adresu URL

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

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

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

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 odpowiednią dla Twojego przypadku użycia i aplikacji.

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

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

Gdy włączona jest też funkcja Grounding with Google Search, model może najpierw użyć Google Search, aby znaleźć odpowiednie informacje, a następnie użyć narzędzia kontekstu adresu URL , aby odczytać zawartość wyników wyszukiwania i uzyskać bardziej szczegółowe informacje. To podejście jest przydatne w przypadku promptów, które wymagają zarówno szerokiego wyszukiwania, jak i dogłębnej analizy konkretnych stron.

Przykładowe zastosowania:

  • W prompcie podajesz adres URL, aby ułatwić wygenerowanie odpowiedzi. Aby jednak wygenerować prawidłową odpowiedź, model nadal potrzebuje więcej informacji na inne tematy, dlatego używa 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 żadnego adresu URL. Aby wygenerować prawidłową odpowiedź, model używa narzędzia Grounding with Google Search tool do znalezienia odpowiednich adresów URL, a następnie narzędzia kontekstu adresu URL do analizy 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 Grounding with 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 odpowiednią dla Twojego przypadku użycia i aplikacji.

Jak działa narzędzie kontekstu adresu URL

Narzędzie kontekstu adresu URL używa 2-etapowego procesu pobierania, aby zrównoważyć szybkość, koszt i dostęp 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 jako wysoce zoptymalizowana pamięć podręczna.

Krok 2: jeśli adres URL nie jest dostępny w indeksie (np. jeśli jest to bardzo nowa strona), narzędzie automatycznie przełączy się na pobieranie na żywo. Dzięki temu bezpośrednio uzyskuje dostęp do adresu URL, aby pobrać jego zawartość w czasie rzeczywistym.

Sprawdzone metody

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

  • Sprawdzaj dostępność: upewnij się, że podane adresy URL nie prowadzą do stron, które wymagają logowania lub są chronione paywallem.

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

Interpretowanie odpowiedzi

Odpowiedź modelu będzie oparta na treści pobranej z adresów URL.

Jeśli model pobrał treści z adresów URL, odpowiedź będzie zawierać url_context_metadata. Taka odpowiedź może wyglądać mniej więcej tak (części odpowiedzi zostały pominięte dla zwięzłoś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"
            },
          ]
        }
    }
  ]
}

Testy zabezpieczeń

System przeprowadza kontrolę moderacji treści pod kątem adresu URL, aby potwierdzić, że spełnia on standardy bezpieczeństwa. Jeśli podany adres URL nie przejdzie tej kontroli, otrzymasz url_retrieval_status o wartości 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 adresu URL: maksymalny rozmiar treści pobranej z jednego adresu URL to 34 MB.

  • Aktualność: narzędzie nie pobiera wersji stron internetowych na żywo, dlatego mogą występować problemy z aktualnością lub potencjalnie nieaktualnymi informacjami.

  • Publiczna dostępność adresu URL: podane adresy URL muszą być publicznie dostępne w internecie. Te adresy nie są obsługiwane: treści chronione paywallem, treści wymagające logowania 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:

  • 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 w 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 i Arkusze Google

  • (jeśli używasz Vertex AI Gemini API) Cloud Storage adresy URL
    Te typy adresów URL nie są obsługiwane przez Gemini Developer API niezależnie od sposobu dostępu.

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

Ceny i zliczanie tokenów narzędzia

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

Liczbę tokenów w prompcie i wykorzystanie narzędzi możesz sprawdzić w obiekcie usage_metadata w 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 ceny zależą od używanego modelu. Więcej informacji o cenach narzędzia kontekstu adresu URL znajdziesz w dokumentacji wybranego Gemini API dostawcy: Gemini Developer API | Vertex AI Gemini API.