URL-контекст

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

Контекст URL имеет следующие преимущества:

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

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

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

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

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

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

  • gemini-3.1-pro-preview
  • 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 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: [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.");

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

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

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

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

Например:

  • Вы указали в запросе URL, чтобы помочь сгенерировать ответ. Однако, чтобы сгенерировать подходящий ответ, модели требуется больше информации по другим темам, поэтому она использует инструмент Grounding with 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 в запросе. Чтобы сгенерировать правильный ответ, модель использует инструмент Grounding with Google Search для поиска релевантных URL, а затем инструмент URL context для анализа их содержимого.

    Пример запроса:
    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: [
      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

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

Как работает инструмент контекста 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)) URL Cloud Storage
    Эти типы 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).