A ferramenta de contexto de URL permite fornecer mais contexto ao modelo na forma de URLs. O modelo pode acessar o conteúdo desses URLs para informar e melhorar a resposta.
O contexto de URL tem os seguintes benefícios:
Extrair dados: forneça informações específicas, como preços, nomes ou principais descobertas de um artigo ou vários URLs.
Comparar informações: analise vários relatórios, artigos ou PDFs para identificar diferenças e acompanhar tendências.
Sintetizar e criar conteúdo: combine informações de vários URLs de origem para gerar resumos precisos, postagens de blog, relatórios ou perguntas de teste.
Analisar código e conteúdo técnico: forneça URLs para um repositório do GitHub ou documentação técnica para explicar o código, gerar instruções de configuração ou responder perguntas.
Revise as práticas recomendadas e as limitações ao usar a ferramenta de contexto de URL.
Modelos compatíveis
gemini-3.1-pro-previewgemini-3.6-flash(e ogemini-3.5-flashmais antigo)gemini-3.5-flash-lite(e ogemini-3.1-flash-litemais antigo)gemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
Idiomas compatíveis
Consulte os idiomas compatíveis com os Gemini modelos.
Usar a ferramenta de contexto de URL
Você pode usar a ferramenta de contexto de URL de duas maneiras principais:
Somente a ferramenta de contexto de URL
|
Clique no provedor Gemini API para conferir o conteúdo específico do provedor e o código nesta página. |
Ao criar a instância GenerativeModel, forneça UrlContext como uma ferramenta.
Em seguida, diretamente no comando, forneça os URLs específicos que você quer que o modelo acesse e analise.
O exemplo a seguir mostra como comparar duas receitas de sites diferentes:
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.");
Saiba como escolher um modelo adequado para seu caso de uso e app.
Contexto de URL combinado com o embasamento com Google Search
|
Clique no provedor Gemini API para conferir o conteúdo específico do provedor e o código nesta página. |
É possível ativar o contexto de URL e o
embasamento com
Quando o embasamento com
Veja alguns casos de uso:
Você fornece um URL no comando para ajudar com parte da resposta gerada. No entanto, para gerar uma resposta adequada, o modelo ainda precisa de mais informações sobre outros tópicos. Por isso, ele usa a ferramenta de embasamento com a
Google Search Exemplo de comando:
Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?Você não fornece um URL no comando. Portanto, para gerar uma resposta adequada , o modelo usa a ferramenta de embasamento com
Google Search ferramenta para encontrar URLs relevantes e, em seguida, usa a ferramenta de contexto de URL para analisar o conteúdo deles.Exemplo de comando:
Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.
O exemplo a seguir mostra como ativar e usar as duas ferramentas: contexto de URL e
embasamento com
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
Saiba como escolher um modelo adequado para seu caso de uso e app.
Como a ferramenta de contexto de URL funciona
A ferramenta de contexto de URL usa um processo de recuperação de duas etapas para equilibrar velocidade, custo e acesso a dados atualizados.
Etapa 1: quando você fornece um URL específico, a ferramenta primeiro tenta buscar o conteúdo de um cache de índice interno. Isso funciona como um cache altamente otimizado.
Etapa 2: se um URL não estiver disponível no índice (por exemplo, se for uma página muito nova), a ferramenta fará um retorno automático para fazer uma busca em tempo real. Isso acessa diretamente o URL para recuperar o conteúdo em tempo real.
Práticas recomendadas
Forneça URLs específicos: para melhores resultados, forneça URLs diretos para o conteúdo que você quer que o modelo analise. O modelo só vai recuperar conteúdo dos URLs fornecidos, não de links aninhados.
Verifique a acessibilidade: verifique se os URLs fornecidos não levam a páginas que exigem login ou estão atrás de um paywall.
Use o URL completo: forneça o URL completo, incluindo o protocolo (por exemplo,
https://www.example.comem vez de apenasexample.com).
Entender a resposta
A resposta do modelo será baseada no conteúdo recuperado dos URLs.
Se o modelo tiver recuperado conteúdo de URLs, a resposta vai incluir url_context_metadata. Uma resposta como essa pode ser semelhante à seguinte (partes da resposta foram omitidas para maior brevidade):
{
"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"
},
]
}
}
]
}
Verificações de segurança
O sistema realiza uma verificação de moderação de conteúdo no URL para confirmar se ele atende aos padrões de segurança. Se o URL fornecido falhar nessa verificação, você receberá um url_retrieval_status de URL_RETRIEVAL_STATUS_UNSAFE.
Limitações
Confira algumas limitações da ferramenta de contexto de URL:
Combinação com a chamada de função: a ferramenta de contexto de URL não pode ser usada em uma solicitação que também usa a chamada de função.
Limite de URLs por solicitação: o número máximo de URLs por solicitação é 20.
Limite de tamanho do conteúdo do URL: o tamanho máximo do conteúdo recuperado de um único URL é de 34 MB.
Atualização: a ferramenta não busca versões ativas de páginas da Web. Portanto, pode haver alguns problemas com informações atualizadas ou potencialmente desatualizadas.
Acessibilidade pública do URL: os URLs fornecidos precisam estar acessíveis publicamente na Web. Os seguintes não são aceitos: conteúdo com paywall, conteúdo que exige login do usuário, redes privadas, endereços de localhost (como
localhostou127.0.0.1) e serviços de tunelamento (como ngrok ou pinggy).
Tipos de conteúdo aceitos e não aceitos
Aceitos: a ferramenta pode extrair conteúdo de URLs com os seguintes tipos de conteúdo:
Texto (
text/html,application/json,text/plain,text/xml,text/css,text/javascript,text/csv,text/rtf)Imagem (
image/png,image/jpeg,image/bmp,image/webp)PDF (
application/pdf)
Não aceitos: a ferramenta não aceita os seguintes tipos de conteúdo:
Vídeos do YouTube (em vez disso, consulte Analisar vídeos)
Arquivos de vídeo e áudio (em vez disso, consulte Analisar vídeos ou Analisar áudio)
Arquivos do Google Workspace, como Documentos Google ou Planilhas Google
(se estiver usando a Vertex AI Gemini API) Cloud Storage URLs
Esses tipos de URLs não são aceitos pela Gemini Developer API não importa como você acesse.Conteúdo que não está acessível publicamente. Os seguintes não são aceitos: conteúdo com paywall, conteúdo que exige login do usuário, redes privadas, endereços de localhost (como
localhostou127.0.0.1) e serviços de tunelamento (como ngrok ou pinggy).
Preços e contagem de tokens de ferramentas
O conteúdo recuperado de URLs é contabilizado como tokens de entrada.
É possível conferir a contagem de tokens do comando e o uso de ferramentas no objeto usage_metadata da saída do modelo. Confira um exemplo de saída:
'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
}
O limite de taxa e os preços são baseados no modelo usado. Saiba mais sobre os preços da ferramenta de contexto de URL na documentação do provedor Gemini API escolhido: Gemini Developer API | Vertex AI Gemini API.