URL コンテキスト ツールを使用すると、URL の形式でモデルに追加のコンテキストを提供できます。モデルは、これらの URL からコンテンツにアクセスして、レスポンスを形成し、強化できます。
URL コンテキストには次のようなメリットがあります。
データを抽出する: 記事や複数の URL から、価格、名前、重要な調査結果などの具体的な情報を提供します。
情報を比較する: 複数のレポート、記事、PDF を分析して、違いを特定し、傾向を追跡します。
コンテンツを合成して作成する: 複数のソース URL からの情報を組み合わせて、正確な要約、ブログ投稿、レポート、テストの質問を生成します。
コードと技術コンテンツを分析する: GitHub リポジトリまたは技術ドキュメントの URL を指定して、コードの説明、設定手順の生成、質問への回答を行います。
URL コンテキスト ツールを使用する際は、ベスト プラクティスと制限事項を必ずご確認ください。
サポートされているモデル
gemini-3-pro-previewgemini-3-flash-previewgemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
サポートされている言語
Gemini モデルについては、サポートされている言語をご覧ください。
URL コンテキスト ツールを使用する
URL コンテキスト ツールは、次の 2 つの主な方法で使用できます。
URL コンテキスト ツールのみ
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
GenerativeModel インスタンスを作成するときに、ツールとして UrlContext を指定します。次に、モデルでアクセスして分析する特定の URL をプロンプトで直接指定します。
次の例は、異なるウェブサイトの 2 つのレシピを比較する方法を示しています。
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.");
ユースケースとアプリに適したモデル を選択する方法について説明します。
URL コンテキストと Google 検索によるグラウンディングの組み合わせ
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
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 検索によるグラウンディングの両方のツールを有効にして使用する方法を示しています。
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 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
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 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
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 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
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 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
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 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
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 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 コンテキスト ツールは、速度、コスト、最新データへのアクセスのバランスを取るために、2 段階の取得プロセスを使用します。
ステップ 1: 特定の URL を指定すると、ツールはまず内部インデックス キャッシュからコンテンツを取得しようとします。これは高度に最適化されたキャッシュとして機能します。
ステップ 2: URL がインデックス登録されていない場合(たとえば、ページが新しく、まだインデックス登録されていない場合)、このツールは自動的にライブ取得にフォールバックします。これにより、URL に直接アクセスしてコンテンツをリアルタイムで取得します。
ベスト プラクティス
特定の URL を指定する: 最良の結果を得るには、モデルで分析するコンテンツの直接 URL を指定します。モデルは、指定した URL のコンテンツのみを取得し、ネストされたリンクのコンテンツは取得しません。
アクセシビリティを確認する: 指定した URL が、ログインが必要なページやペイウォールの背後にあるページにリンクされていないことを確認します。
完全な URL を使用する: プロトコルを含む完全な URL を指定します(
example.comだけでなくhttps://www.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 がこのチェックに失敗すると、url_retrieval_status は URL_RETRIEVAL_STATUS_UNSAFE になります。
制限事項
URL コンテキスト ツールには次のような制限があります。
関数呼び出しとの組み合わせ: URL コンテキスト ツールは、関数呼び出しも使用するリクエストでは使用できません。
リクエストあたりの URL の上限: リクエストあたりの URL の最大数は 20 個です。
URL コンテンツのサイズ上限: 単一の URL から取得されるコンテンツの最大サイズは 34 MB です。
鮮度: このツールはウェブページのライブ バージョンを取得しないため、鮮度に問題があるか、情報が古くなっている可能性があります。
URL の一般公開: 提供された URL は、ウェブ上で一般公開されている必要があります。ペイウォールで保護されたコンテンツ、ユーザーのログインが必要なコンテンツ、プライベート ネットワーク、ローカルホスト アドレス(
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 ドキュメントやスプレッドシートなど)
(Vertex AI Gemini API を使用している場合) Cloud Storage URL
このタイプの URL は、アクセス方法に関係なく Gemini Developer API ではサポートされていません。一般公開されていないコンテンツ。次のものはサポートされていません。ペイウォール コンテンツ、ユーザーのログインが必要なコンテンツ、プライベート ネットワーク、ローカルホスト アドレス(
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
}
レート制限と料金は、使用するモデルに基づきます。選択した Gemini API プロバイダのドキュメント(Gemini Developer API | Vertex AI Gemini API)で、URL コンテキスト ツールの料金についてご確認ください。
を使用する場合、ツール使用トークンはまだダッシュボードに表示されません。