URL コンテキスト

URL コンテキスト ツールを使用すると、URL の形式で追加のコンテキストをモデルに提供できます。モデルは、これらの URL からコンテンツにアクセスして、レスポンスを形成し、強化できます。

URL コンテキストには次の利点があります。

  • データの抽出: 記事や複数の URL から、価格、名前、 主な調査結果などの特定の情報を提供します。

  • 情報の比較: 複数のレポート、記事、PDF を分析して 違いを特定し、トレンドを追跡します。

  • コンテンツの合成と作成: 複数の ソース URL の情報を組み合わせて、正確な要約、ブログ投稿、レポート、テスト 問題を作成します。

  • コードと技術コンテンツの分析: GitHub リポジトリまたは 技術ドキュメントの URL を提供して、コードの説明、設定手順の生成、質問への回答を行います。

URL コンテキスト ツールを使用する際は、ベスト プラクティス制限事項を確認してください。

サポートされているモデル

  • gemini-3.1-pro-preview
  • gemini-3.5-flash
  • gemini-3.1-flash-lite
  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-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.");

ユースケースとアプリに適したモデル を選択する方法をご覧ください。

Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。

URL コンテキストと グラウンディングの両方を有効にできますGoogle Search。 この構成では、特定の URL を含むプロンプトと含まないプロンプトを作成できます。

Google Search によるグラウンディングも有効になっている場合、モデルはまず Google Search を使用して関連情報を検索し、URL コンテキスト ツールを使用して検索結果の内容を読み取り、情報をより深く 理解します。このアプローチは、広範な検索と特定のページの詳細な分析の両方を必要とするプロンプトに有効です。

たとえば次のような方法で使用できます。

  • プロンプトで URL を指定して、生成されたレスポンスの一部を生成します。 ただし、適切なレスポンスを生成するには、モデルは他のトピックに関する詳細情報も必要とするため、グラウンディング 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 を指定しません。そのため、適切な レスポンスを生成するために、モデルは Google Search ツール を使用して関連する URL を検索し、URL コンテキスト ツールを使用してその コンテンツを分析します。

    プロンプト例:
    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 コンテキスト ツールは、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_statusURL_RETRIEVAL_STATUS_UNSAFE になります。

制限事項

URL コンテキスト ツールには次の制限があります。

  • 関数呼び出しとの組み合わせ: URL コンテキスト ツールは、関数呼び出しも使用する リクエストでは 使用できません

  • リクエストあたりの URL の上限: リクエストあたりの URL の最大数は 20 個です。

  • URL コンテンツのサイズ上限: 1 つの URL から取得できるコンテンツの最大サイズは 34 MB です。

  • 鮮度: このツールはウェブページのライブ バージョンを取得しないため、 鮮度に問題があるか、情報が古くなっている可能性があります。

  • URL の公開アクセシビリティ: 指定した URL は、 ウェブ上で一般公開されている必要があります。ペイウォール コンテンツ、ユーザーのログインが必要なコンテンツ、プライベート ネットワーク、localhost アドレス(localhost127.0.0.1 など)、トンネリング サービス(ngrok や pinggy など)はサポートされていません

サポートされているコンテンツ タイプとサポートされていないコンテンツ タイプ

**サポートされているコンテンツ タイプ** : このツールは、次のコンテンツ タイプの URL からコンテンツを抽出できます。

  • テキスト(text/htmlapplication/jsontext/plaintext/xmltext/csstext/javascripttext/csvtext/rtf

  • 画像(image/pngimage/jpegimage/bmpimage/webp

  • PDF(application/pdf

**対象外** : このツールは、次のコンテンツ タイプをサポートしていません__。

  • YouTube 動画(代わりに、動画を分析するをご覧ください)

  • 動画ファイルと音声ファイル(代わりに、 動画を分析するまたは 音声を分析するをご覧ください)

  • Google Workspace ファイル(Google ドキュメントやスプレッドシートなど)

  • Vertex AI Gemini API を使用している場合) Cloud Storage の URL
    これらのタイプの URL は、アクセス方法に関係なく、Gemini Developer API ではサポートされていません。

  • 一般公開されていないコンテンツ。以下はサポートされていません。 ペイウォール コンテンツ、ユーザーのログインが必要なコンテンツ、プライベート ネットワーク、 localhost アドレス(localhost127.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 コンテキスト ツールの料金についてご確認ください。

Firebase