URLs de contexte

L'outil de contexte d'URL vous permet de fournir au modèle un contexte supplémentaire sous la forme d'URL. Le modèle peut accéder au contenu de ces URL pour informer et améliorer sa réponse.

Le contexte d'URL présente les avantages suivants :

  • Extraire des données : fournissez des informations spécifiques, comme des prix, des noms ou des conclusions clés d'un article ou de plusieurs URL.

  • Comparer des informations : analysez plusieurs rapports, articles ou PDF pour identifier les différences et suivre les tendances.

  • Synthétiser et créer du contenu : combinez des informations provenant de plusieurs URL sources pour générer des résumés, des articles de blog, des rapports ou des questions de test précis.

  • Analyser du code et du contenu technique : fournissez les URL d'un dépôt GitHub ou d'une documentation technique pour expliquer du code, générer des instructions de configuration ou répondre à des questions.

Lorsque vous utilisez l'outil de contexte d'URL, veillez à consulter les bonnes pratiques et les limites.

Modèles compatibles

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

Langues disponibles

Consultez les langues acceptées pour les modèles Gemini.

Utiliser l'outil de contexte d'URL

Vous pouvez utiliser l'outil de contexte d'URL de deux manières principales :

Outil de contexte d'URL uniquement

Cliquez sur votre fournisseur Gemini API pour afficher le contenu et le code spécifiques à ce fournisseur sur cette page.

Lorsque vous créez l'instance GenerativeModel, fournissez UrlContext comme outil. Ensuite, indiquez directement dans votre requête les URL spécifiques auxquelles vous souhaitez que le modèle accède et qu'il analyse.

L'exemple suivant montre comment comparer deux recettes provenant de sites Web différents :

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

Découvrez comment choisir un modèle adaptés à votre cas d'utilisation et à votre application.

Cliquez sur votre fournisseur Gemini API pour afficher le contenu et le code spécifiques à ce fournisseur sur cette page.

Vous pouvez activer à la fois le contexte d'URL et l'ancrage avec la recherche Google. Avec cette configuration, vous pouvez rédiger des requêtes avec ou sans URL spécifiques.

Lorsque l'ancrage avec la recherche Google est également activé, le modèle peut d'abord utiliser la recherche Google pour trouver des informations pertinentes, puis utiliser l'outil de contexte d'URL pour lire le contenu des résultats de recherche et mieux comprendre les informations. Cette approche est efficace pour les requêtes qui nécessitent à la fois une recherche large et une analyse approfondie de pages spécifiques.

Voici quelques cas d'utilisation :

  • Vous fournissez une URL dans la requête pour aider à générer une partie de la réponse. Toutefois, pour générer une réponse appropriée, le modèle a encore besoin d'informations sur d'autres sujets. Il utilise donc l'outil d'ancrage avec la recherche Google.

    Exemple de requête :
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • Vous ne fournissez aucune URL dans la requête. Pour générer une réponse appropriée, le modèle utilise l'outil d'ancrage avec la recherche Google afin de trouver des URL pertinentes, puis l'outil de contexte d'URL pour analyser leur contenu.

    Exemple de requête :
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

L'exemple suivant montre comment activer et utiliser les deux outils : le contexte d'URL et l'ancrage avec la recherche 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

Découvrez comment choisir un modèle adaptés à votre cas d'utilisation et à votre application.

Fonctionnement de l'outil de contexte d'URL

L'outil de contexte d'URL utilise un processus de récupération en deux étapes pour équilibrer la vitesse, le coût et l'accès aux données récentes.

Étape 1 : Lorsque vous fournissez une URL spécifique, l'outil tente d'abord de récupérer le contenu à partir d'un cache d'index interne. Il s'agit d'un cache hautement optimisé.

Étape 2 : Si une URL n'est pas disponible dans l'index (par exemple, s'il s'agit d'une page très récente), l'outil effectue automatiquement une récupération en ligne. Il accède directement à l'URL pour récupérer son contenu en temps réel.

Bonnes pratiques

  • Fournissez des URL spécifiques : pour obtenir les meilleurs résultats, fournissez des URL directes vers le contenu que vous souhaitez que le modèle analyse. Le modèle ne récupérera que le contenu des URL que vous fournissez, et non celui des liens imbriqués.

  • Vérifiez l'accessibilité : assurez-vous que les URL que vous fournissez ne redirigent pas vers des pages qui nécessitent une connexion ou sont soumises à un paywall.

  • Utilisez l'URL complète : fournissez l'URL complète, y compris le protocole (par exemple, https://www.example.com au lieu de example.com).

Comprendre la réponse

La réponse du modèle sera basée sur le contenu qu'il a récupéré à partir des URL.

Si le modèle a récupéré du contenu à partir d'URL, la réponse inclura url_context_metadata. Une telle réponse peut ressembler à ce qui suit (certaines parties de la réponse ont été omises par souci de concision) :

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

Contrôles de sécurité

Le système effectue une vérification de modération du contenu sur l'URL pour confirmer qu'elle respecte les normes de sécurité. Si l'URL que vous avez fournie échoue à ce test, vous recevrez un url_retrieval_status de URL_RETRIEVAL_STATUS_UNSAFE.

Limites

Voici quelques limites de l'outil de contexte d'URL :

  • Combinaison avec l'appel de fonction : l'outil de contexte d'URL ne peut pas être utilisé dans une requête qui utilise également l'appel de fonction.

  • Limite d'URL par requête : le nombre maximal d'URL par requête est de 20.

  • Limite de taille du contenu d'URL : la taille maximale du contenu récupéré à partir d'une seule URL est de 34 Mo.

  • Fraîcheur : l'outil ne récupère pas les versions en direct des pages Web. Il peut donc y avoir des problèmes de fraîcheur ou des informations potentiellement obsolètes.

  • Accessibilité publique des URL : les URL fournies doivent être accessibles publiquement sur le Web. Les éléments suivants ne sont pas acceptés : contenu payant, contenu nécessitant une connexion utilisateur, réseaux privés, adresses localhost (comme localhost ou 127.0.0.1) et services de tunneling (comme ngrok ou pinggy).

Types de contenus compatibles et non compatibles

Compatible : l'outil peut extraire du contenu à partir d'URL avec les types de contenu suivants :

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

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

  • PDF (application/pdf)

Non pris en charge : l'outil n'est pas compatible avec les types de contenus suivants :

  • Vidéos YouTube (consultez plutôt Analyser des vidéos).

  • Fichiers vidéo et audio (consultez plutôt Analyser des vidéos ou Analyser des fichiers audio).

  • Fichiers Google Workspace, comme des documents ou des feuilles de calcul Google

  • (si vous utilisez Vertex AI Gemini API) URL Cloud Storage
    Ces types d'URL ne sont pas compatibles avec Gemini Developer API, quelle que soit la façon dont vous y accédez.

  • Contenus non accessibles au public Les éléments suivants ne sont pas acceptés : contenu payant, contenu nécessitant une connexion de l'utilisateur, réseaux privés, adresses localhost (comme localhost ou 127.0.0.1) et services de tunneling (comme ngrok ou pinggy).

Tarification et comptabilisation des jetons

Le contenu récupéré à partir d'URL est comptabilisé comme jetons d'entrée.

Vous pouvez consulter le nombre de jetons pour votre requête et l'utilisation des outils dans l'objet usage_metadata de la sortie du modèle. Voici un exemple de résultat :

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

La limite de débit et la tarification dépendent du modèle utilisé. Pour en savoir plus sur les tarifs de l'outil de contexte d'URL, consultez la documentation du fournisseur Gemini API de votre choix : Gemini Developer API | Vertex AI Gemini API.