Kontekst adresu URL

Narzędzie do kontekstu adresu URL umożliwia dostarczanie modelowi dodatkowego kontekstu w postaci adresów URL. Model może uzyskiwać dostęp do treści z tych adresów URL, aby ulepszać swoje odpowiedzi.

Kontekst adresu URL ma te zalety:

  • Wyodrębnianie danych: podaj konkretne informacje, takie jak ceny, nazwy lub kluczowe wnioski z artykułu lub kilku adresów URL.

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

  • Syntetyzowanie 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: podaj adresy URL repozytorium GitHub lub dokumentacji technicznej, aby wyjaśnić kod, wygenerować instrukcje konfiguracji lub odpowiedzieć na pytania.

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

Obsługiwane modele

  • gemini-4-argon
  • gemini-3.8-flash (oraz starsze modele gemini-3.7-flash, gemini-3.6-flash i gemini-3.5-flash)
  • gemini-3.5-flash-lite (oraz starsze wersje gemini-3.1-flash-lite)

Tę funkcję obsługują też modele gemini-3.1-pro-preview i ogólnego zastosowania Gemini 2.5 (które zostały wycofane).

Obsługiwane języki

Sprawdź obsługiwane języki modeli Gemini.

Korzystanie z narzędzia do sprawdzania kontekstu adresu URL

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

Tylko narzędzie do sprawdzania kontekstu adresu URL

Kliknij dostawcę Gemini API, aby wyświetlić na tej stronie treści i kod dotyczące tego 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 uzyskać dostęp i które ma przeanalizować.

Ten 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: [.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 dostawcę Gemini API, aby wyświetlić na tej stronie treści i kod dotyczące tego dostawcy.

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

Gdy włączone jest również Grounding with Google Search, model może najpierw użyć Google Search, aby znaleźć odpowiednie informacje, a następnie narzędzia kontekstowego URL, aby odczytać treść wyników wyszukiwania i lepiej zrozumieć informacje. To podejście jest skuteczne w przypadku promptów, które wymagają zarówno szerokiego wyszukiwania, jak i szczegółowej analizy konkretnych stron.

Oto kilka przykładów:

  • W promptie podajesz adres URL, aby pomóc w wygenerowaniu odpowiedzi. Jednak aby wygenerować prawidłową odpowiedź, model 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?

  • Nie podajesz w prompcie żadnego adresu URL. Aby wygenerować prawidłową odpowiedź, model używa narzędzia Grounding with Google Search do znalezienia odpowiednich adresów URL, a następnie narzędzia URL context do przeanalizowania ich zawartości.

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

Ten przykład pokazuje, jak włączyć i używać obu narzędzi – kontekstu adresu URL i groundingu z 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: [
      .urlContext(),
      .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 do sprawdzania kontekstu adresu URL

Narzędzie do kontekstu adresu URL korzysta z dwuetapowego procesu pobierania, aby zrównoważyć szybkość, koszty 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 jak 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łącza się na pobieranie wersji opublikowanej. Umożliwia to bezpośredni dostęp do adresu URL w celu pobrania jego zawartości w czasie rzeczywistym.

Sprawdzone metody

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

  • Sprawdź ułatwienia dostępu: upewnij się, że podane adresy URL nie prowadzą do stron, które wymagają logowania lub są umieszczone za systemem płatnego dostępu do treści.

  • Użyj 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ściach pobranych z adresów URL.

Jeśli model pobrał treści z adresów URL, odpowiedź będzie zawierać url_context_metadata. Odpowiedź może wyglądać mniej więcej tak (części odpowiedzi zostały pominięte dla uproszczenia):

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

Kontrole bezpieczeństwa

System sprawdza adres URL pod kątem moderowania treści, aby potwierdzić, że spełnia on standardy bezpieczeństwa. Jeśli podany przez Ciebie adres URL nie przejdzie tej weryfikacji, otrzymasz błąd url_retrieval_status o kodzie URL_RETRIEVAL_STATUS_UNSAFE.

Ograniczenia

Oto kilka ograniczeń narzędzia do sprawdzania kontekstu adresu URL:

  • Łączenie z wywoływaniem funkcji: narzędzia kontekstu adresu URL nie można używać w żądaniu, które korzysta również 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 pobranych z jednego adresu URL to 34 MB.

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

  • Dostępność publiczna adresu URL: podane adresy URL muszą być publicznie dostępne w internecie. Nie są obsługiwane: treści płatne, treści wymagające logowania użytkownika, sieci prywatne, adresy hosta lokalnego (takie jak localhost lub 127.0.0.1) i usługi tunelowania (takie jak 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 czy arkusze kalkulacyjne;

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

  • Treści, które nie są dostępne publicznie. Nie są obsługiwane: treści płatne, treści wymagające logowania użytkownika, sieci prywatne, adresy localhost (takie jak localhost lub 127.0.0.1) i usługi tunelowania (takie jak ngrok lub pinggy).

Ceny i liczenie tokenów narzędzi

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

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