Narzędzie kontekstu URL umożliwia przekazywanie dodatkowego kontekstu do modelu w postaci adresów URL. Model może uzyskać dostęp do treści z tych adresów URL, aby wzbogacić 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 do sprawdzania kontekstu adresu URL, zapoznaj się ze sprawdzonymi metodami i ograniczeniami.
Obsługiwane modele
gemini-3.1-pro-previewgemini-3.5-flashgemini-3.1-flash-litegemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
Obsługiwane języki
Zobacz obsługiwane języki w przypadku modeli Gemini.
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 specyficzne dla tego dostawcy. |
Podczas tworzenia GenerativeModel instancji 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ć.
Przykład poniżej 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.
Kontekst adresu URL połączony z uzasadnieniem za pomocą Google Search
|
Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod specyficzne dla tego dostawcy. |
Możesz włączyć zarówno kontekst adresu URL, jak i uzasadnienie za pomocą
Jeśli włączone jest też powiązanie ze źródłem informacji przy użyciu
Przykładowe zastosowania:
W prompcie podajesz adres URL, aby ułatwić generowanie odpowiedzi. Jednak aby wygenerować prawidłową odpowiedź, model nadal potrzebuje więcej informacji na inne tematy, dlatego korzysta z narzędzia
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 z
Google Search do znajdowania odpowiednich adresów URL, a następnie narzędzia kontekstu adresu URL 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 uzasadnienia za pomocą
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 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
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 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
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 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
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 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
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 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
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 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 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. Pełni ona funkcję wysoce zoptymalizowanej pamięci podręcznej.
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. 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ą zostać przeanalizowane przez model. Model pobierze tylko treści z podanych 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żyj pełnego adresu URL: podaj pełny adres URL, w tym protokół (np.
https://www.example.comzamiast tylkoexample.com).
Interpretowanie odpowiedzi
Odpowiedź modelu będzie oparta na treściach pobranych z adresów URL.
Jeśli model pobrał treść z adresów URL, odpowiedź będzie zawierać url_context_metadata. Taka 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"
},
]
}
}
]
}
Kontrole bezpieczeństwa
System przeprowadza weryfikację treści pod kątem zgodności z zasadami, aby potwierdzić, że adres URL spełnia standardy bezpieczeństwa. Jeśli podany przez Ciebie adres URL nie przejdzie tego testu, otrzymasz url_retrieval_statusURL_RETRIEVAL_STATUS_UNSAFE.
Ograniczenia
Oto niektóre ograniczenia narzędzia kontekstu adresu URL:
Łączenie z wywoływaniem funkcji: narzędzia kontekstowego 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 wersji stron internetowych na żywo, 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.
localhostlub127.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 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 lub arkusze kalkulacyjne Google;
(jeśli używasz Vertex AI Gemini API) Cloud Storageadresy 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ą dostępne publicznie; Nie są obsługiwane: treści za paywallem, treści wymagające zalogowania się użytkownika, sieci prywatne, adresy localhost (np.
localhostlub127.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 usage_metadata obiektu 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 żądań i ceny zależą od używanego modelu. Więcej informacji o cenach narzędzia do kontekstu URL znajdziesz w dokumentacji wybranego dostawcy Gemini API:Gemini Developer API | Vertex AI Gemini API.