URL-контекст

Инструмент "URL-контекст" позволяет предоставлять модели дополнительный контекст в виде URL. Модель может использовать контент по этим URL, чтобы улучшать свои ответы.

Преимущества URL-контекста:

  • Извлечение данных. Предоставление конкретной информации, например цен, названий или ключевых выводов из статьи или нескольких URL.

  • Сравнивать информацию. Анализируйте несколько отчетов, статей или PDF-файлов, чтобы выявлять различия и отслеживать тенденции.

  • Обобщение и создание контента. Объединяйте информацию из нескольких источников, чтобы создавать точные сводки, записи в блогах, отчеты или вопросы для тестов.

  • Анализировать код и технический контент. Предоставьте URL хранилища GitHub или технической документации, чтобы получить объяснение кода, инструкции по настройке или ответы на вопросы.

Обязательно ознакомьтесь с рекомендациями и ограничениями по использованию инструмента "URL-контекст".

Поддерживаемые модели

  • gemini-4-argon
  • gemini-3.8-flash (и более старые версии gemini-3.7-flash, gemini-3.6-flash и gemini-3.5-flash)
  • gemini-3.5-flash-lite (и более старый gemini-3.1-flash-lite)

Модели gemini-3.1-pro-preview и Gemini 2.5 общего назначения (которые больше не поддерживаются) также поддерживают эту возможность.

Поддерживаемые языки

Ознакомьтесь со списком поддерживаемых языков для моделей Gemini.

Как использовать инструмент "URL-контекст"

Инструмент "URL-контекст" можно использовать двумя основными способами:

Только инструмент "URL-контекст"

Нажмите на название своего поставщика Gemini API, чтобы посмотреть контент и код, относящиеся к нему.

При создании экземпляра GenerativeModel укажите UrlContext в качестве инструмента. Затем прямо в запросе укажите URL, к которым модели нужно получить доступ для анализа.

В примере ниже показано, как сравнить два рецепта с разных сайтов.

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

Узнайте, как выбрать модель в зависимости от вашего приложения и целей.

Нажмите на название своего поставщика Gemini API, чтобы посмотреть контент и код, относящиеся к нему.

Вы можете включить и URL-контекст, и обоснование с помощью Google Search. При такой конфигурации вы можете писать запросы с URL или без них.

Если также включено заземление с помощью Google Search, модель может сначала использовать Google Search, чтобы найти нужную информацию, а затем – инструмент контекста URL, чтобы прочитать контент результатов поиска и лучше понять информацию. Этот подход эффективен для запросов, требующих как широкого поиска, так и глубокого анализа конкретных страниц.

Например:

  • Вы указываете в запросе URL, чтобы помочь ИИ сгенерировать ответ. Однако, чтобы сгенерировать подходящий ответ, модели все равно нужно больше информации по другим темам, поэтому она использует инструмент "Обоснование с помощью Google Search".

    Пример запроса:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • Вы не указываете URL в запросе. Чтобы сгенерировать правильный ответ, модель использует инструмент "Обоснование с помощью Google Search" для поиска релевантных URL, а затем анализирует их контент с помощью инструмента "URL-контекст".

    Пример запроса:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

В примере ниже показано, как включить и использовать оба инструмента – URL-контекст и заземление с помощью 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

Узнайте, как выбрать модель в зависимости от вашего приложения и целей.

Как работает инструмент "URL-контекст"

Инструмент URL-контекста использует двухэтапный процесс извлечения, чтобы сбалансировать скорость, стоимость и доступ к актуальным данным.

Шаг 1. Когда вы указываете URL, инструмент сначала пытается получить контент из кеша индекса. Это позволяет оптимизировать кеш.

Шаг 2. Если URL нет в индексе (например, если страница создана совсем недавно), инструмент автоматически выполняет сканирование опубликованной страницы. Это позволяет получить доступ к URL и извлечь его контент в режиме реального времени.

Рекомендации

  • Указывайте точные URL. Чтобы получить наилучшие результаты, указывайте прямые URL контента, который должна проанализировать модель. Модель будет извлекать контент только из указанных вами URL, а не из вложенных ссылок.

  • Проверьте доступность. Убедитесь, что указанные вами URL не ведут на страницы, для просмотра которых необходимо войти в систему или заплатить.

  • Используйте полный URL. Укажите полный URL, включая протокол (например, https://www.example.com вместо example.com).

Как интерпретировать ответ

Ответ модели будет основан на контенте, полученном по URL.

Если модель извлекла контент из URL, ответ будет включать url_context_metadata. Ответ может выглядеть примерно так (некоторые части ответа опущены для краткости):

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

Проверки безопасности

Система проверяет контент по URL, чтобы убедиться, что он соответствует стандартам безопасности. Если URL не пройдет проверку, вы получите сообщение об ошибке url_retrieval_status со значением URL_RETRIEVAL_STATUS_UNSAFE.

Ограничения

Вот некоторые ограничения инструмента "URL-контекст":

  • Сочетание с вызовом функций. Инструмент URL-контекста нельзя использовать в запросе, в котором также используется вызов функций.

  • Ограничение на количество URL в запросе. В одном запросе может быть не более 20 URL.

  • Ограничение на размер контента по URL. Максимальный размер контента, полученного по одному URL, составляет 34 МБ.

  • Актуальность. Инструмент не извлекает текущие версии веб-страниц, поэтому могут возникнуть проблемы с актуальностью или потенциально устаревшей информацией.

  • Общедоступность URL. Указанные URL должны быть общедоступными. Не поддерживаются: платный контент, контент, требующий входа в аккаунт, частные сети, адреса localhost (например, localhost или 127.0.0.1) и сервисы туннелирования (например, ngrok или pinggy).

Поддерживаемые и неподдерживаемые типы контента

Поддерживается. Инструмент может извлекать контент из URL со следующими типами контента:

  • Текст (text/html, application/json, text/plain, text/xml, text/css, text/javascript, text/csv, text/rtf)

  • Изображение (image/png, image/jpeg, image/bmp, image/webp)

  • PDF (application/pdf)

Не поддерживается. Инструмент не поддерживает следующие типы контента:

  • видео YouTube (вместо этого ознакомьтесь с информацией о том, как анализировать видео);

  • Видео- и аудиофайлы (вместо этого см. Анализ видео или Анализ аудио).

  • файлы Google Workspace, например Google Документы или таблицы;

  • (если используется Agent Platform Gemini API (formerly Vertex AI)) Cloud Storage URL
    Эти типы URL не поддерживаются Gemini Developer API независимо от того, как вы получаете к ним доступ.

  • Контент, который недоступен широкой аудитории. Не поддерживаются: платный контент, контент, требующий входа в аккаунт, частные сети, адреса localhost (например, localhost или 127.0.0.1) и сервисы туннелирования (например, ngrok или pinggy).

Цены и подсчет токенов инструментов

Контент, полученный по URL, учитывается как входные токены.

Количество токенов в запросе и использование инструментов можно посмотреть в объекте usage_metadata выходных данных модели. Пример выходных данных:

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

Ограничение частоты запросов и цена зависят от используемой модели. Подробнее о ценах на инструмент URL-контекста можно узнать в документации выбранного поставщика Gemini API: Gemini Developer API | Agent Platform Gemini API (formerly Vertex AI).

.