Contexto do URL

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 de 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.

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

Modelos compatíveis

  • gemini-4-hydrogen
  • gemini-4-argon
  • gemini-4-carbon
  • gemini-3.8-flash
  • gemini-3.5-flash-lite (e o gemini-3.1-flash-lite mais antigo)

Os modelos Gemini 3.x Flash de uso geral mais antigos são compatíveis com esse recurso, mas não são mais recomendados para uso devido às próximas datas de desativação e/ou ao roteamento automático para modelos mais recentes.

Idiomas compatíveis

Confira os idiomas disponíveis para os 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, informe diretamente no comando 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: [.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 Google Search. Com essa configuração, é possível escrever comandos com ou sem URLs específicos.

Quando o embasamento com Google Search também está ativado, o modelo pode primeiro usar Google Search para encontrar informações relevantes e, em seguida, usar a ferramenta de contexto de URL para ler o conteúdo dos resultados da pesquisa e entender melhor as informações. Essa abordagem é eficiente para comandos que exigem pesquisa ampla e análise profunda 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 tópicos. Por isso, ele usa a ferramenta de embasamento com o 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 o Google Search 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 Google Search:


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


// 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 funciona a ferramenta de contexto de URL

A ferramenta de contexto de URL usa um processo de recuperação em duas etapas para equilibrar velocidade, custo e acesso a dados recentes.

Etapa 1: quando você fornece um URL específico, a ferramenta tenta buscar o conteúdo em um cache de índice interno. Ele 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 vai fazer 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 melhores resultados, forneça URLs diretos para o conteúdo que você quer que o modelo analise. O modelo só vai recuperar o conteúdo dos URLs fornecidos, não o conteúdo de links aninhados.

  • Verifique a acessibilidade: confirme se os URLs fornecidos não levam a páginas que exigem login ou estão protegidas por paywall.

  • Use o URL completo: forneça 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 recuperou conteúdo de URLs, a resposta vai incluir url_context_metadata. Uma resposta como essa pode ser semelhante a esta (partes da resposta foram omitidas para fins de 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 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 em tempo real de páginas da Web. Por isso, pode haver alguns problemas com a atualização ou informações possivelmente desatualizadas.

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

Tipos de conteúdo aceitos e não aceitos

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 aceita os seguintes tipos de conteúdo:

  • Vídeos do YouTube (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 Agent Platform Gemini API (formerly Vertex AI)) Cloud Storage URLs
    Esses tipos de URLs não são compatíveis com o Gemini Developer API, não importa como você os acessa.

  • Conteúdo que não está acessível ao público. Os seguintes itens não são compatíveis: conteúdo com paywall, conteúdo que exige login do usuário, redes privadas, endereços de host local (como localhost ou 127.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 conta como tokens de entrada.

É possível ver 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
  }

A limitação 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 | Agent Platform Gemini API (formerly Vertex AI).