URL-контекст

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

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

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

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

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

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

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

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

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

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

Список поддерживаемых языков для моделей Gemini см . в соответствующем разделе.

Воспользуйтесь инструментом контекста URL-адреса.

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

Инструмент контекста URL-адреса (только для контекста)

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

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

Следующий пример показывает, как сравнить два рецепта с разных сайтов:

Быстрый


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

Единство


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

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

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

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

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

Вот несколько примеров использования:

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

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

  • В запросе вы вообще не указываете URL-адрес. Поэтому, чтобы сгенерировать корректный ответ, модель использует инструмент поиска Google для поиска релевантных URL-адресов, а затем использует инструмент анализа контекста URL-адресов для анализа их содержимого.

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

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

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

Как работает инструмент определения контекста 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-адресов в одном запросе : максимальное количество 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, такие как документы Google или электронные таблицы Google.

  • (при использовании API Vertex AI Gemini ) URL-адреса Cloud Storage
    API для разработчиков Gemini не поддерживает такие типы URL-адресов, независимо от способа доступа к ним.

  • Контент, недоступный для публичного доступа. Не поддерживаются следующие типы контента: контент с платным доступом, контент, требующий авторизации пользователя, частные сети, адреса 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-адреса можно узнать в документации выбранного вами поставщика API Gemini : Gemini Developer API |Vertex AI Gemini API .