Инструмент "Контекст URL" позволяет предоставлять моделям дополнительный контекст в виде URL. Если вы добавите URL в запрос, модель получит доступ к контенту на этих страницах (если это не URL, указанный в разделе ограничений) и сможет использовать его для улучшения ответа.
Инструмент "URL-контекст" полезен для следующих задач:
- Извлечение данных. Получайте определенную информацию, например цены, имена или ключевые выводы, из нескольких URL.
- Сравнивать документы. Анализируйте несколько отчетов, статей или PDF-файлов, чтобы выявлять различия и отслеживать тенденции.
- Обобщение и создание контента. Объединяйте информацию из нескольких URL-адресов источников, чтобы создавать точные сводки, записи в блогах или отчеты.
- Анализ кода и документов. Укажите хранилище GitHub или техническую документацию, чтобы получить объяснение кода, инструкции по настройке или ответы на вопросы.
В примере ниже показано, как сравнить два рецепта с разных сайтов.
Python
# This will only work for SDK newer than 2.0.0
from google import genai
client = genai.Client()
url1 = "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592"
url2 = "https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/"
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=f"Compare the ingredients and cooking times from the recipes at {url1} and {url2}",
tools=[{"type": "url_context"}]
)
# Print the model's text response and its source annotations
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
if content_block.annotations:
print("\nSources:")
for annotation in content_block.annotations:
if annotation.type == "url_citation":
print(f" - {annotation.title}: {annotation.url}")
JavaScript
// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
async function main() {
const interaction = await client.interactions.create({
model: "gemini-3.8-flash",
input: "Compare the ingredients and cooking times from the recipes at https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592 and https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/",
tools: [{ type: "url_context" }]
});
// Print the model's text response and its source annotations
for (const step of interaction.steps) {
if (step.type === 'model_output') {
for (const contentBlock of step.content) {
if (contentBlock.type === 'text') {
console.log(contentBlock.text);
if (contentBlock.annotations) {
console.log("\nSources:");
for (const annotation of contentBlock.annotations) {
if (annotation.type === 'url_citation') {
console.log(` - ${annotation.title}: ${annotation.url}`);
}
}
}
}
}
}
}
}
await main();
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
url1 := "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592"
url2 := "https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/"
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput(
fmt.Sprintf("Compare the ingredients and cooking times from the recipes at %s and %s", url1, url2),
),
Tools: []interactions.Tool{
interactions.NewTool(interactions.URLContext{}),
},
}),
})
if err != nil {
log.Fatal(err)
}
// Print the model's text response and its source annotations
for _, step := range res.Interaction.Steps {
if step.ModelOutputStep != nil {
for _, contentBlock := range step.ModelOutputStep.Content {
if contentBlock.TextContent != nil {
fmt.Println(contentBlock.TextContent.Text)
if len(contentBlock.TextContent.Annotations) > 0 {
fmt.Println("\nSources:")
for _, annotation := range contentBlock.TextContent.Annotations {
if annotation.URLCitation != nil {
fmt.Printf(" - %s: %s\n", annotation.URLCitation.GetTitle(), annotation.URLCitation.GetURL())
}
}
}
}
}
}
}
}
REST
# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Compare the ingredients and cooking times from the recipes at https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592 and https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/",
"tools": [{"type": "url_context"}]
}'
Принцип работы
Инструмент "Контекст URL" использует двухэтапный процесс получения данных, чтобы обеспечить баланс между скоростью, стоимостью и доступом к актуальным данным. Когда вы указываете URL, инструмент сначала пытается получить контент из внутреннего кеша индекса. Это высокооптимизированный кеш. Если URL отсутствует в индексе (например, если страница была создана совсем недавно), инструмент автоматически выполняет сканирование опубликованной страницы. Это позволяет получить доступ к URL и его контенту в режиме реального времени.
Сочетание с другими инструментами
Вы можете комбинировать инструмент URL-контекста с другими инструментами, чтобы создавать более мощные рабочие процессы.
Модели Gemini 3 поддерживают сочетание встроенных инструментов (например, контекста URL) со специальными инструментами (вызовом функций). Подробнее о сочетаниях инструментов…
Обоснование с Google Поиском
Если включены и URL-контекст, и обоснование с Google Поиском, модель может использовать возможности Поиска, чтобы находить нужную информацию в интернете, а затем применять URL-контекст, чтобы лучше понимать найденные страницы. Этот подход эффективен для запросов, которые требуют как широкого поиска, так и глубокого анализа определенных страниц.
Python
# This will only work for SDK newer than 2.0.0
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute.",
tools=[
{"type": "url_context"},
{"type": "google_search"}
]
)
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
JavaScript
// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
async function main() {
const interaction = await client.interactions.create({
model: "gemini-3.8-flash",
input: "Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute.",
tools: [
{ type: "url_context" },
{ type: "google_search" }
]
});
for (const step of interaction.steps) {
if (step.type === 'model_output') {
for (const contentBlock of step.content) {
if (contentBlock.type === 'text') console.log(contentBlock.text);
}
}
}
}
await main();
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
Model: interactions.Model("gemini-3.8-flash"),
Input: interactions.NewInteractionsInput("Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute."),
Tools: []interactions.Tool{
interactions.NewTool(interactions.URLContext{}),
interactions.NewTool(interactions.GoogleSearch{}),
},
}),
})
if err != nil {
log.Fatal(err)
}
for _, step := range res.Interaction.Steps {
if step.ModelOutputStep != nil {
for _, contentBlock := range step.ModelOutputStep.Content {
if contentBlock.TextContent != nil {
fmt.Println(contentBlock.TextContent.Text)
}
}
}
}
}
REST
# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute.",
"tools": [
{"type": "url_context"},
{"type": "google_search"}
]
}'
Как понять ответ
Когда модель использует инструмент URL-контекста, ее текстовый ответ включает встроенные аннотации url_citation в блоке текстового контента. Каждая аннотация связывает фрагмент текста ответа (с помощью start_index и end_index) с URL источника, из которого он был получен. Это основной способ показать цитаты в приложении. О том, как их извлечь, рассказывается в основном примере выше.
В ответе также содержится объект url_context_result с метаданными о каждой попытке получения URL (статус, полученный URL). Это в основном полезно для отладки.
Проверки безопасности
Система проверяет URL на соответствие стандартам безопасности. Если URL не проходит проверку, на соответствующем шаге url_context_result будет показан статус status из "unsafe".
Количество токенов
Контент, полученный по URL, которые вы указываете в запросе, учитывается как часть входных токенов. Количество токенов можно посмотреть в объекте usage взаимодействия. Пример:
'usage': {
'output_tokens': 45,
'input_tokens': 27,
'input_tokens_details': [{'modality': 'TEXT', 'token_count': 27}],
'thoughts_tokens': 31,
'tool_use_input_tokens': 10309,
'tool_use_input_tokens_details': [{'modality': 'TEXT', 'token_count': 10309}],
'total_tokens': 10412
}
Цена за токен зависит от используемой модели. Подробную информацию можно найти на странице Цены.
Поддерживаемые модели
| Модель | URL-контекст |
|---|---|
| Gemini 4 Argon | ✔️ |
| Gemini 3.8 Flash | ✔️ |
| Gemini 3.6 Flash | ✔️ |
| Gemini 3.5 Flash-Lite | ✔️ |
| Gemini 3.1 Pro (предварительная версия) | ✔️ |
| Gemini 3.1 Flash-Lite | ✔️ |
| Gemini 3 Flash Preview | ✔️ |
| Gemini 2.5 Pro | ✔️ |
| Gemini 2.5 Flash | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ |
Рекомендации
- Указывайте точные URL. Чтобы получить наилучшие результаты, указывайте прямые URL контента, который должна проанализировать модель. Модель будет извлекать контент только из указанных вами URL, а не из вложенных ссылок.
- Проверьте доступность. Убедитесь, что URL, которые вы указали, не ведут на страницы, требующие входа в систему или платного доступа.
- Укажите полный URL. Включите в него протокол (например, https://www.google.com, а не google.com).
Ограничения
- Ограничение на количество запросов. Инструмент может обработать до 20 URL за один запрос.
- Размер контента, полученного по одному URL, не должен превышать 34 МБ.
- Общедоступность. 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 (о том, как обрабатывать URL YouTube, читайте в разделе Распознавание видео).
- файлы Google Workspace, например документы или таблицы Google;
- Видео- и аудиофайлы