Contexto do URL

Com a ferramenta de contexto de URL, você pode 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, postagens de blog, relatórios ou perguntas de teste precisos.

  • 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 a perguntas.

Confira as práticas recomendadas e as limitações ao usar a ferramenta de contexto de URL.

Modelos compatíveis

  • gemini-3-pro-preview
  • gemini-3-flash-preview
  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite

Idiomas compatíveis

Consulte os idiomas disponíveis para modelos Gemini.

Usar a ferramenta de contexto de URL

Você pode usar a ferramenta de contexto de URL de duas maneiras principais:

Somente ferramenta de contexto de URL

Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página.

Ao criar a instância GenerativeModel, forneça UrlContext como uma ferramenta. Em seguida, 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.

Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página.

É possível ativar o contexto de URL e o embasamento com a Pesquisa Google. Com essa configuração, é possível escrever comandos com ou sem URLs específicos.

Quando o embasamento com a Pesquisa Google também está ativado, o modelo pode primeiro usar a Pesquisa Google para encontrar informações relevantes e depois usar a ferramenta de contexto de URL para ler o conteúdo dos resultados da pesquisa e entender melhor as informações. Essa abordagem é útil para comandos que exigem pesquisa ampla e análise detalhada de páginas específicas.

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 temas. Por isso, ele usa a ferramenta de embasamento com a Pesquisa Google.

    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. Para gerar uma resposta adequada, o modelo usa o embasamento com a ferramenta da Pesquisa Google 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 a Pesquisa Google:


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


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

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á uma busca em tempo real automaticamente. Isso acessa diretamente o URL para recuperar o conteúdo em tempo real.

Práticas recomendadas

  • Forneça URLs específicos: para ter os melhores resultados, forneça URLs diretos para o conteúdo que você quer que o modelo analise. O modelo só vai extrair conteúdo dos URLs fornecidos, não de links aninhados.

  • Verifique a acessibilidade: confira 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: informe o URL completo, incluindo o protocolo (por exemplo, https://www.example.com em vez de apenas example.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 desse tipo pode ser semelhante a esta (partes da resposta foram omitidas para facilitar a leitura):

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

Confirmações de segurança

O sistema faz 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 não passar nessa verificação, você vai 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 chamada de função: a ferramenta de contexto de URL não pode ser usada em uma solicitação que também usa 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. Por isso, pode haver problemas com a atualização ou informações desatualizadas.

  • Acessibilidade pública do URL: os URLs fornecidos precisam ser acessíveis publicamente na Web. Os seguintes itens não são compatíveis: conteúdo pago, conteúdo que exige login do usuário, redes particulares, endereços localhost (como localhost ou 127.0.0.1) e serviços de tunelamento (como ngrok ou pinggy).

Tipos de conteúdo compatíveis e incompatíveis

Compatível: 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 compatível: a ferramenta não oferece suporte aos 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 ou planilhas Google

  • (se estiver usando o Vertex AI Gemini API) URLs Cloud Storage
    Esses tipos de URLs não são compatíveis com o Gemini Developer API independente da forma como você acessa.

  • Conteúdo que não está acessível ao público. Os seguintes itens não são compatíveis: conteúdo pago, conteúdo que exige login do usuário, redes particulares, endereços localhost (como localhost ou 127.0.0.1) e serviços de tunelamento (como ngrok ou pinggy).

Tokens de ferramentas de preços e contagem

O conteúdo recuperado de URLs conta como tokens de entrada.

É possível conferir a contagem de tokens do seu 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 o preço 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.