Konteks URL

Alat konteks URL memungkinkan Anda memberikan konteks tambahan ke model dalam bentuk URL. Model dapat mengakses konten dari URL tersebut untuk menginformasikan dan meningkatkan kualitas responsnya.

Konteks URL memiliki manfaat berikut:

  • Mengekstrak data: Memberikan informasi spesifik seperti harga, nama, atau temuan utama dari artikel atau beberapa URL.

  • Membandingkan informasi: Menganalisis beberapa laporan, artikel, atau PDF untuk mengidentifikasi perbedaan dan melacak tren.

  • Menyintesis dan membuat konten: Menggabungkan informasi dari beberapa URL sumber untuk membuat ringkasan, postingan blog, laporan, atau soal ujian yang akurat.

  • Menganalisis kode dan konten teknis: Berikan URL ke repositori GitHub atau dokumentasi teknis untuk menjelaskan kode, membuat petunjuk penyiapan, atau menjawab pertanyaan.

Pastikan Anda meninjau praktik terbaik dan batasan saat menggunakan alat konteks URL.

Model yang didukung

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

Bahasa yang didukung

Lihat bahasa yang didukung untuk model Gemini.

Menggunakan alat konteks URL

Anda dapat menggunakan alat konteks URL dengan dua cara utama:

Hanya alat konteks URL

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Saat Anda membuat instance GenerativeModel, berikan UrlContext sebagai alat. Kemudian, langsung ke perintah Anda, berikan URL spesifik yang Anda inginkan untuk diakses dan dianalisis oleh model.

Contoh berikut menunjukkan cara membandingkan dua resep dari situs yang berbeda:

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

Pelajari cara memilih model yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Anda dapat mengaktifkan konteks URL dan penggalian informasi dengan Google Penelusuran. Dengan konfigurasi ini, Anda dapat menulis perintah dengan atau tanpa URL tertentu.

Jika fitur perujukan dengan Google Penelusuran juga diaktifkan, model mungkin terlebih dahulu menggunakan Google Penelusuran untuk menemukan informasi yang relevan, lalu menggunakan alat konteks URL untuk membaca konten hasil penelusuran agar lebih memahami informasi tersebut. Pendekatan ini sangat efektif untuk perintah yang memerlukan penelusuran luas dan analisis mendalam halaman tertentu.

Berikut ini beberapa kasus penggunaan:

  • Anda memberikan URL dalam perintah untuk membantu beberapa respons yang dihasilkan. Namun, untuk menghasilkan respons yang tepat, model masih memerlukan lebih banyak informasi tentang topik lain, sehingga model menggunakan alat perujukan dengan Google Penelusuran.

    Contoh perintah:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • Anda tidak memberikan URL dalam perintah sama sekali. Jadi, untuk menghasilkan respons yang tepat, model menggunakan alat perujukan dengan Google Penelusuran untuk menemukan URL yang relevan, lalu menggunakan alat konteks URL untuk menganalisis kontennya.

    Contoh perintah:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

Contoh berikut menunjukkan cara mengaktifkan dan menggunakan kedua alat — konteks URL dan perujukan dengan Google Penelusuran:


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

Pelajari cara memilih model yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Cara kerja alat konteks URL

Alat konteks URL menggunakan proses pengambilan dua langkah untuk menyeimbangkan kecepatan, biaya, dan akses ke data baru.

Langkah 1: Saat Anda memberikan URL tertentu, alat ini akan mencoba mengambil konten dari cache indeks internal terlebih dahulu. Cache ini berfungsi sebagai cache yang sangat dioptimalkan.

Langkah 2: Jika URL tidak tersedia di indeks (misalnya, jika URL tersebut adalah halaman yang sangat baru), alat otomatis akan melakukan pengambilan langsung. Alat ini mengakses URL secara langsung untuk mengambil kontennya secara real time.

Praktik terbaik

  • Berikan URL spesifik: Untuk mendapatkan hasil terbaik, berikan URL langsung ke konten yang Anda ingin untuk dianalisis oleh model. Model hanya akan mengambil konten dari URL yang Anda berikan, bukan konten dari link bertingkat.

  • Periksa aksesibilitas: Pastikan URL yang Anda berikan tidak mengarah ke halaman yang memerlukan login atau berada di balik penghalang konten berbayar.

  • Gunakan URL lengkap: Berikan URL lengkap, termasuk protokolnya (misalnya, https://www.example.com, bukan hanya example.com).

Memahami respons

Respons model akan didasarkan pada konten yang diambilnya dari URL.

Jika model mengambil konten dari URL, respons akan menyertakan url_context_metadata. Respons tersebut mungkin terlihat seperti berikut (bagian respons telah dihilangkan agar lebih singkat):

{
  "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"
            },
          ]
        }
    }
  ]
}

Pemeriksaan keamanan

Sistem melakukan pemeriksaan moderasi konten pada URL untuk mengonfirmasi bahwa URL tersebut memenuhi standar keamanan. Jika URL yang Anda berikan gagal dalam pemeriksaan ini, Anda akan mendapatkan url_retrieval_status sebesar URL_RETRIEVAL_STATUS_UNSAFE.

Keterbatasan

Berikut beberapa batasan alat konteks URL:

  • Dikombinasikan dengan panggilan fungsi: Alat konteks URL tidak dapat digunakan dalam permintaan yang juga menggunakan panggilan fungsi.

  • Batas URL per permintaan: Jumlah maksimum URL per permintaan adalah 20 URL.

  • Batas ukuran konten URL: Ukuran maksimum untuk konten yang diambil dari satu URL adalah 34 MB.

  • Keaktualan: Alat ini tidak mengambil versi langsung halaman web, sehingga mungkin ada beberapa masalah terkait keaktualan atau informasi yang berpotensi sudah tidak berlaku.

  • Aksesibilitas publik URL: URL yang diberikan harus dapat diakses secara publik di web. Berikut adalah konten yang tidak didukung: konten berbayar, konten yang memerlukan login pengguna, jaringan pribadi, alamat localhost (seperti localhost atau 127.0.0.1), dan layanan tunneling (seperti ngrok atau pinggy).

Jenis konten yang didukung dan tidak didukung

Didukung: Alat ini dapat mengekstrak konten dari URL dengan jenis konten berikut:

  • Teks (text/html, application/json, text/plain, text/xml, text/css, text/javascript, text/csv, text/rtf)

  • Gambar (image/png, image/jpeg, image/bmp, image/webp)

  • PDF (application/pdf)

Tidak didukung: Alat tidak mendukung jenis konten berikut:

  • Video YouTube (sebaliknya, lihat menganalisis video)

  • File video dan audio (sebaliknya, lihat menganalisis video atau menganalisis audio)

  • File Google Workspace, seperti dokumen atau spreadsheet Google

  • (jika menggunakan Vertex AI Gemini API) URL Cloud Storage
    Jenis URL ini tidak didukung oleh Gemini Developer API terlepas dari cara Anda mengaksesnya.

  • Konten yang tidak dapat diakses secara publik. Berikut adalah konten yang tidak didukung: konten berbayar, konten yang memerlukan login pengguna, jaringan pribadi, alamat localhost (seperti localhost atau 127.0.0.1), dan layanan tunneling (seperti ngrok atau pinggy).

Harga dan token alat penghitungan

Konten yang diambil dari URL dihitung sebagai token input.

Anda dapat melihat jumlah token untuk perintah dan penggunaan alat di objek usage_metadata dari output model. Berikut adalah contoh output:

'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
  }

Batas laju dan harga didasarkan pada model yang digunakan. Pelajari lebih lanjut harga untuk alat konteks URL dalam dokumentasi penyedia Gemini API yang Anda pilih: Gemini Developer API | Vertex AI Gemini API.