Lo strumento di contesto URL ti consente di fornire al modello un contesto aggiuntivo sotto forma di URL. Il modello può accedere ai contenuti di questi URL per informare e migliorare la sua risposta.
Il contesto URL offre i seguenti vantaggi:
Estrai dati: fornisci informazioni specifiche come prezzi, nomi o risultati chiave di un articolo o di più URL.
Confronta le informazioni: analizza più report, articoli o PDF per identificare le differenze e monitorare le tendenze.
Sintetizzare e creare contenuti: combina le informazioni di diversi URL di origine per generare riepiloghi, post del blog, report o domande del test accurati.
Analizza codice e contenuti tecnici: fornisci URL a un repository GitHub o documentazione tecnica per spiegare il codice, generare istruzioni di configurazione o rispondere a domande.
Assicurati di esaminare le best practice e le limitazioni quando utilizzi lo strumento Contesto URL.
Modelli supportati
gemini-3-pro-previewgemini-3-flash-previewgemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
Lingue supportate
Consulta le lingue supportate per i modelli Gemini.
Utilizzare lo strumento Contesto URL
Puoi utilizzare lo strumento di contesto URL in due modi principali:
In combinazione con il grounding con la Ricerca Google
Solo strumento di contesto dell'URL
|
Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina. |
Quando crei l'istanza GenerativeModel, fornisci UrlContext come strumento.
Poi, direttamente nel prompt, fornisci gli URL specifici a cui vuoi che il modello acceda e che analizzi.
Il seguente esempio mostra come confrontare due ricette di siti web diversi:
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.");
Scopri come scegliere un modello adatti al tuo caso d'uso e alla tua app.
Contesto dell'URL combinato con il grounding con la Ricerca Google
|
Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina. |
Puoi attivare sia il contesto dell'URL sia il grounding con la Ricerca Google. Con questa configurazione, puoi scrivere prompt con o senza URL specifici.
Se è attivata anche la fondatezza con la Ricerca Google, il modello potrebbe prima utilizzare la Ricerca Google per trovare informazioni pertinenti e poi utilizzare lo strumento di contesto URL per leggere i contenuti dei risultati di ricerca e comprendere meglio le informazioni. Questo approccio è efficace per i prompt che richiedono sia una ricerca ampia sia un'analisi approfondita di pagine specifiche.
Ecco alcuni casi d'uso:
Fornisci un URL nel prompt per facilitare la generazione di una parte della risposta. Tuttavia, per generare una risposta corretta, il modello ha ancora bisogno di maggiori informazioni su altri argomenti, quindi utilizza lo strumento di grounding con la Ricerca Google.
Prompt di esempio:
Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?Non fornisci alcun URL nel prompt. Pertanto, per generare una risposta appropriata, il modello utilizza lo strumento di grounding con la Ricerca Google per trovare URL pertinenti e poi lo strumento di contesto dell'URL per analizzarne i contenuti.
Prompt di esempio:
Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.
L'esempio seguente mostra come attivare e utilizzare entrambi gli strumenti: contesto URL e grounding con la Ricerca Google:
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
Scopri come scegliere un modello adatti al tuo caso d'uso e alla tua app.
Come funziona lo strumento di contesto URL
Lo strumento di contesto URL utilizza un processo di recupero in due passaggi per bilanciare velocità, costi e accesso a dati aggiornati.
Passaggio 1: quando fornisci un URL specifico, lo strumento tenta innanzitutto di recuperare i contenuti da una cache dell'indice interno. che funge da cache altamente ottimizzata.
Passaggio 2: se un URL non è disponibile nell'indice (ad esempio, se si tratta di una pagina molto recente), lo strumento esegue automaticamente un recupero in tempo reale. Accede direttamente all'URL per recuperare i contenuti in tempo reale.
Best practice
Fornisci URL specifici: per ottenere risultati ottimali, fornisci URL diretti ai contenuti che vuoi che il modello analizzi. Il modello recupererà solo i contenuti dagli URL che fornisci, non i contenuti dei link nidificati.
Verifica l'accessibilità: verifica che gli URL forniti non indirizzino a pagine che richiedono l'accesso o che siano protette da paywall.
Utilizza l'URL completo: fornisci l'URL completo, incluso il protocollo (ad esempio,
https://www.example.comanziché soloexample.com).
Comprendere la risposta
La risposta del modello si baserà sui contenuti recuperati dagli URL.
Se il modello ha recuperato contenuti dagli URL, la risposta includerà
url_context_metadata. Una risposta di questo tipo potrebbe essere simile alla seguente
(alcune parti della risposta sono state omesse per brevità):
{
"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"
},
]
}
}
]
}
Controlli di sicurezza
Il sistema esegue un controllo della moderazione dei contenuti sull'URL per verificare che soddisfino
gli standard di sicurezza. Se l'URL che hai fornito non supera questo controllo, riceverai un
url_retrieval_status di URL_RETRIEVAL_STATUS_UNSAFE.
Limitazioni
Di seguito sono riportate alcune limitazioni dello strumento di contesto dell'URL:
Combinazione con la chiamata di funzione: lo strumento di contesto dell'URL non può essere utilizzato in una richiesta che utilizza anche la chiamata di funzione.
Limite di URL per richiesta: il numero massimo di URL per richiesta è 20.
Limite di dimensione dei contenuti URL: la dimensione massima per i contenuti recuperati da un singolo URL è 34 MB.
Aggiornamento: lo strumento non recupera le versioni live delle pagine web, quindi potrebbero esserci problemi di aggiornamento o informazioni potenzialmente obsolete.
Accessibilità pubblica degli URL: gli URL forniti devono essere accessibili pubblicamente sul web. Non sono supportati: contenuti con paywall, contenuti che richiedono l'accesso dell'utente, reti private, indirizzi localhost (come
localhosto127.0.0.1) e servizi di tunneling (come ngrok o pinggy).
Tipi di contenuti supportati e non supportati
Supportato: lo strumento può estrarre contenuti da URL con i seguenti tipi di contenuti:
Testo (
text/html,application/json,text/plain,text/xml,text/css,text/javascript,text/csv,text/rtf)Immagine (
image/png,image/jpeg,image/bmp,image/webp)PDF (
application/pdf)
Non supportato: lo strumento non supporta i seguenti tipi di contenuti:
Video di YouTube (consulta invece la sezione Analizzare i video)
File video e audio (consulta invece analizzare i video o analizzare l'audio)
File di Google Workspace, come documenti o fogli di lavoro Google
(se utilizzi Vertex AI Gemini API) URL Cloud Storage
Questi tipi di URL non sono supportati da Gemini Developer API indipendentemente dalla modalità di accesso.Contenuti non accessibili pubblicamente. Non sono supportati: contenuti a pagamento, contenuti che richiedono l'accesso dell'utente, reti private, indirizzi localhost (come
localhosto127.0.0.1) e servizi di tunneling (come ngrok o pinggy).
Prezzi e token dello strumento di conteggio
I contenuti recuperati dagli URL vengono conteggiati come token di input.
Puoi visualizzare il conteggio dei token per il prompt e l'utilizzo degli strumenti nell'oggetto usage_metadata dell'output del modello. Di seguito è riportato un output di esempio:
'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
}
Il limite di frequenza e il prezzo si basano sul modello utilizzato. Scopri di più sui prezzi dello strumento Contesto URL nella documentazione del fornitore Gemini API che hai scelto: Gemini Developer API | Vertex AI Gemini API.