Инструмент "Контекст 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) со специальными инструментами (вызовом функций). Подробнее о сочетаниях инструментов…
Обоснование с помощью поиска
Если включены и контекст 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 3.8 Flash | ✔️ |
| Gemini 3.6 Flash | ✔️ |
| Gemini 3.5 Flash-Lite | ✔️ |
| Gemini 3.5 Flash | ✔️ |
| Gemini 3.1 Pro (предварительная версия) | ✔️ |
| Gemini 3.1 Flash-Lite | ✔️ |
| Gemini 3 Flash (предварительная версия) | ✔️ |
| 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. Максимальный размер контента, полученного по одному 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.
- Видео- и аудиофайлы