Lo strumento Contesto URL ti consente di fornire un contesto aggiuntivo al modello sotto forma di URL. Il modello può accedere ai contenuti di questi URL per informare e migliorare la sua risposta.
Il contesto dell'URL offre i seguenti vantaggi:
Estrai dati: fornisci informazioni specifiche come prezzi, nomi o risultati chiave di un articolo o di più URL.
Confrontare informazioni: analizza più report, articoli o PDF per identificare le differenze e monitorare le tendenze.
Sintetizza e crea contenuti: combina le informazioni di diversi URL di origine per generare riepiloghi, blog post, report o domande di test accurati.
Analizza il codice e i contenuti tecnici: fornisci gli URL di un repository GitHub o della documentazione tecnica per spiegare il codice, generare istruzioni di configurazione o rispondere alle domande.
Assicurati di consultare le best practice e le limitazioni quando utilizzi lo strumento Contesto URL.
Modelli supportati
gemini-4-argongemini-3.8-flash(e i modelli precedentigemini-3.7-flash,gemini-3.6-flashegemini-3.5-flash)gemini-3.5-flash-lite(e il precedentegemini-3.1-flash-lite)
Anche i modelli gemini-3.1-pro-preview e Gemini 2.5 per uso generico (deprecati) supportano questa funzionalità.
Lingue supportate
Consulta le lingue supportate per i modelli Gemini.
Utilizza lo strumento Contesto URL
Puoi utilizzare lo strumento Contesto URL in due modi principali:
In combinazione con Grounding con
Google Search
Solo strumento Contesto URL
|
Fai clic sul tuo provider Gemini API per visualizzare i contenuti e il codice specifici del provider 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.
L'esempio seguente 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: [.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 adatta al tuo caso d'uso e alla tua app.
Contesto URL combinato con Grounding con Google Search
|
Fai clic sul tuo provider Gemini API per visualizzare i contenuti e il codice specifici del provider in questa pagina. |
Puoi attivare sia il contesto dell'URL sia il grounding con
Quando è abilitato anche il grounding con
Ecco alcuni casi d'uso:
Fornisci un URL nel prompt per facilitare la generazione della risposta. Tuttavia, per generare una risposta adeguata, il modello ha ancora bisogno di ulteriori informazioni su altri argomenti, quindi utilizza lo strumento Grounding con
Google Search .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. Quindi, per generare una risposta adeguata, il modello utilizza lo strumento Grounding con
Google Search per trovare gli URL pertinenti e poi lo strumento di contesto degli 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
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: [
.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
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 adatta al tuo caso d'uso e alla tua app.
Come funziona lo strumento Contesto URL
Lo strumento di contesto degli 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 degli indici interna. Questa funge da cache altamente ottimizzata.
Passaggio 2: se un URL non è disponibile nell'indice (ad esempio, se si tratta di una pagina molto nuova), lo strumento esegue automaticamente un recupero in tempo reale. In questo modo, 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à i contenuti solo dagli URL forniti, non dai link nidificati.
Verifica l'accessibilità: assicurati che gli URL forniti non rimandino a pagine che richiedono l'accesso o che sono protette da paywall.
Utilizza l'URL completo: fornisci l'URL completo, incluso il protocollo (ad esempio,
https://www.example.comanziché soloexample.com).
Comprendi 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 di moderazione dei contenuti sull'URL per verificare che soddisfi gli standard di sicurezza. Se l'URL fornito non supera questo controllo, riceverai un url_retrieval_status di URL_RETRIEVAL_STATUS_UNSAFE.
Limitazioni
Ecco alcune limitazioni dello strumento di contesto degli URL:
Combinazione con la chiamata di funzione: lo strumento Contesto 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 dimensioni dei contenuti dell'URL: la dimensione massima dei contenuti recuperati da un singolo URL è 34 MB.
Aggiornamento: lo strumento non recupera le versioni pubblicate delle pagine web, pertanto potrebbero esserci alcuni problemi di aggiornamento o informazioni potenzialmente obsolete.
Accessibilità pubblica degli URL: gli URL forniti devono essere accessibili pubblicamente sul web. I seguenti elementi non sono supportati: contenuti protetti da 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
Supportati: lo strumento può estrarre i contenuti dagli 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 supportati: lo strumento non supporta i seguenti tipi di contenuti:
Video di YouTube (consulta invece Analizza i video)
File video e audio (consulta invece Analizza i video o Analizza l'audio)
File di Google Workspace, come Documenti Google o Fogli Google
(se utilizzi Agent Platform Gemini API (formerly Vertex AI)) URL Cloud Storage
Questi tipi di URL non sono supportati da Gemini Developer API, indipendentemente da come accedi.Contenuti non accessibili pubblicamente. I seguenti elementi non sono supportati: contenuti protetti da 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).
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 esempio di output:
'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 i prezzi si basano sul modello utilizzato. Scopri di più sui prezzi dello strumento Contesto URL nella documentazione del provider Gemini API scelto: Gemini Developer API | Agent Platform Gemini API (formerly Vertex AI).