Contexto de la URL

La herramienta de contexto de URL te permite proporcionar contexto adicional al modelo en forma de URLs. El modelo puede acceder al contenido de esas URLs para fundamentar y mejorar su respuesta.

El contexto de URL tiene los siguientes beneficios:

  • Extraer datos: Proporciona información específica, como precios, nombres o hallazgos clave de un artículo o varias URLs.

  • Comparar información: Analiza varios informes, artículos o PDFs para identificar diferencias y hacer un seguimiento de las tendencias.

  • Sintetiza y crea contenido: Combina información de varias URLs de origen para generar resúmenes, publicaciones de blog, informes o preguntas de prueba precisos.

  • Analizar código y contenido técnico: Proporciona URLs a un repositorio de GitHub o documentación técnica para explicar el código, generar instrucciones de configuración o responder preguntas.

Asegúrate de revisar las prácticas recomendadas y las limitaciones cuando uses la herramienta de contexto de URL.

Modelos compatibles

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

Idiomas compatibles

Consulta los idiomas admitidos para los modelos de Gemini.

Usa la herramienta de contexto de URL

Puedes usar la herramienta de contexto de URL de dos maneras principales:

Solo la herramienta de contexto de URL

Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página.

Cuando crees la instancia de GenerativeModel, proporciona UrlContext como herramienta. Luego, proporciona directamente en tu instrucción las URLs específicas a las que quieres que acceda y analice el modelo.

En el siguiente ejemplo, se muestra cómo comparar dos recetas de diferentes sitios web:

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.");

Aprende a elegir un modelo adecuados para tu caso de uso y tu app.

Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página.

Puedes habilitar el contexto de URL y la fundamentación con la Búsqueda de Google. Con esta configuración, puedes escribir instrucciones con o sin URLs específicas.

Cuando también se habilita la fundamentación con la Búsqueda de Google, el modelo puede usar primero la Búsqueda de Google para encontrar información pertinente y, luego, usar la herramienta de contexto de URL para leer el contenido de los resultados de la búsqueda y comprender mejor la información. Este enfoque es eficaz para las instrucciones que requieren una búsqueda amplia y un análisis profundo de páginas específicas.

A continuación, se indican algunos casos prácticos:

  • Proporcionas una URL en la instrucción para ayudar con parte de la respuesta generada. Sin embargo, para generar una respuesta adecuada, el modelo aún necesita más información sobre otros temas, por lo que usa la herramienta de fundamentación con la Búsqueda de Google.

    Ejemplo de instrucción:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • No proporcionas ninguna URL en la instrucción. Por lo tanto, para generar una respuesta adecuada, el modelo usa la herramienta de fundamentación con la Búsqueda de Google para encontrar URLs relevantes y, luego, usa la herramienta de contexto de URL para analizar su contenido.

    Ejemplo de instrucción:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

En el siguiente ejemplo, se muestra cómo habilitar y usar ambas herramientas: el contexto de URL y la fundamentación con la Búsqueda de 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

Aprende a elegir un modelo adecuados para tu caso de uso y tu app.

Cómo funciona la herramienta de contexto de URL

La herramienta de contexto de URL usa un proceso de recuperación de dos pasos para equilibrar la velocidad, el costo y el acceso a datos recientes.

Paso 1: Cuando proporcionas una URL específica, la herramienta primero intenta recuperar el contenido de una caché de índice interna. Esto actúa como una caché altamente optimizada.

Paso 2: Si una URL no está disponible en el índice (por ejemplo, si es una página muy nueva), la herramienta recurre automáticamente a una recuperación en tiempo real. Esto accede directamente a la URL para recuperar su contenido en tiempo real.

Prácticas recomendadas

  • Proporciona URLs específicas: Para obtener los mejores resultados, proporciona URLs directas al contenido que deseas que analice el modelo. El modelo solo recuperará contenido de las URLs que proporciones, no de los vínculos anidados.

  • Verifica la accesibilidad: Comprueba que las URLs que proporciones no dirijan a páginas que requieran un acceso o estén detrás de un muro de pago.

  • Usa la URL completa: Proporciona la URL completa, incluido el protocolo (por ejemplo, https://www.example.com en lugar de solo example.com).

Comprende la respuesta

La respuesta del modelo se basará en el contenido que recuperó de las URLs.

Si el modelo recuperó contenido de URLs, la respuesta incluirá url_context_metadata. Una respuesta de este tipo podría verse de la siguiente manera (se omitieron partes de la respuesta para mayor brevedad):

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

Verificaciones de seguridad

El sistema realiza una verificación de moderación de contenido en la URL para confirmar que cumple con los estándares de seguridad. Si la URL que proporcionaste no pasa esta verificación, recibirás un url_retrieval_status de URL_RETRIEVAL_STATUS_UNSAFE.

Limitaciones

Estas son algunas limitaciones de la herramienta de contexto de URL:

  • Combinación con llamadas a funciones: La herramienta de contexto de URL no se puede usar en una solicitud que también use llamadas a funciones.

  • Límite de URLs por solicitud: La cantidad máxima de URLs por solicitud es de 20.

  • Límite de tamaño del contenido de la URL: El tamaño máximo del contenido recuperado de una sola URL es de 34 MB.

  • Actualidad: La herramienta no recupera versiones en tiempo real de las páginas web, por lo que puede haber algunos problemas con la actualidad o información potencialmente desactualizada.

  • Accesibilidad pública de la URL: Las URLs proporcionadas deben ser de acceso público en la Web. No se admiten los siguientes elementos: contenido con muro de pago, contenido que requiere que el usuario acceda, redes privadas, direcciones de localhost (como localhost o 127.0.0.1) y servicios de tunneling (como ngrok o pinggy).

Tipos de contenido admitidos y no admitidos

Compatible: La herramienta puede extraer contenido de URLs con los siguientes tipos de contenido:

  • Texto (text/html, application/json, text/plain, text/xml, text/css, text/javascript, text/csv, text/rtf)

  • Imagen (image/png, image/jpeg, image/bmp, image/webp)

  • PDF (application/pdf)

No se admite: La herramienta no admite los siguientes tipos de contenido:

  • Videos de YouTube (en su lugar, consulta cómo analizar videos)

  • Archivos de audio y video (en su lugar, consulta Cómo analizar videos o Cómo analizar audio)

  • Archivos de Google Workspace, como documentos u hojas de cálculo de Google

  • (si usas Vertex AI Gemini API) URLs de Cloud Storage
    Estos tipos de URLs no son compatibles con Gemini Developer API, sin importar cómo accedas a él.

  • Contenido que no es de acceso público No se admiten los siguientes elementos: contenido con muro de pago, contenido que requiere que el usuario acceda, redes privadas, direcciones de localhost (como localhost o 127.0.0.1) y servicios de tunneling (como ngrok o pinggy).

Precios y conteo de tokens de herramientas

El contenido recuperado de las URLs se considera como tokens de entrada.

Puedes ver el recuento de tokens de tu instrucción y el uso de herramientas en el objeto usage_metadata del resultado del modelo. A continuación, se muestra un ejemplo del resultado:

'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
  }

El límite de frecuencia y los precios se basan en el modelo que se usa. Obtén más información sobre los precios de la herramienta de contexto de URL en la documentación del proveedor de Gemini API que elijas: Gemini Developer API | Vertex AI Gemini API.