URL bağlamı

URL bağlamı aracı, URL'ler şeklinde modele ek bağlam sağlamanıza olanak tanır. Model, yanıtını bilgilendirmek ve geliştirmek için bu URL'lerdeki içeriğe erişebilir.

URL bağlamı aşağıdaki avantajları sunar:

  • Veri ayıklama: Fiyatlar, adlar veya bir makaledeki ya da birden fazla URL'deki temel bulgular gibi belirli bilgileri sağlayın.

  • Bilgileri karşılaştırma: Farklılıkları belirlemek ve trendleri takip etmek için birden fazla raporu, makaleyi veya PDF'yi analiz edin.

  • İçerik sentezleme ve oluşturma: Doğru özetler, blog yayınları, raporlar veya test soruları oluşturmak için birkaç kaynak URL'den gelen bilgileri birleştirin.

  • Kodu ve teknik içeriği analiz etme: Kodu açıklamak, kurulum talimatları oluşturmak veya soruları yanıtlamak için GitHub deposunun ya da teknik dokümanların URL'lerini girin.

URL bağlam aracını kullanırken en iyi uygulamaları ve sınırlamaları incelediğinizden emin olun.

Desteklenen modeller

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

Desteklenen diller

Gemini modelleri için desteklenen dilleri inceleyin.

URL bağlamı aracını kullanma

URL bağlam aracını iki şekilde kullanabilirsiniz:

Yalnızca URL bağlam aracı

Bu sayfada sağlayıcıya özel içerikleri ve kodu görüntülemek için Gemini API sağlayıcınızı tıklayın.

GenerativeModel örneğini oluştururken araç olarak UrlContext'ı sağlayın. Ardından, isteminize doğrudan modelin erişmesini ve analiz etmesini istediğiniz URL'leri girin.

Aşağıdaki örnekte, farklı web sitelerindeki iki tarifin nasıl karşılaştırılacağı gösterilmektedir:

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

Kullanım alanınıza ve uygulamanıza uygun bir model nasıl seçeceğinizi öğrenin.

Bu sayfada sağlayıcıya özel içerikleri ve kodu görüntülemek için Gemini API sağlayıcınızı tıklayın.

Hem URL bağlamını hem de Google Arama ile temellendirme'yi etkinleştirebilirsiniz. Bu yapılandırmayla, belirli URL'ler içeren veya içermeyen istemler yazabilirsiniz.

Google Arama ile temellendirme de etkinleştirildiğinde model, önce alakalı bilgileri bulmak için Google Arama'yı kullanabilir, ardından bilgileri daha ayrıntılı bir şekilde anlamak için arama sonuçlarının içeriğini okumak üzere URL bağlam aracını kullanabilir. Bu yaklaşım, hem geniş kapsamlı arama hem de belirli sayfaların ayrıntılı analizini gerektiren istemler için idealdir.

Aşağıda bazı kullanım alanları verilmiştir:

  • Oluşturulan yanıtın bir kısmına yardımcı olması için istemde bir URL sağlarsınız. Ancak modelin uygun bir yanıt oluşturabilmesi için diğer konular hakkında daha fazla bilgiye ihtiyacı vardır. Bu nedenle, Google Arama ile temellendirme aracını kullanır.

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

  • İstemde hiç URL sağlamıyorsunuz. Bu nedenle, uygun bir yanıt oluşturmak için model, alakalı URL'leri bulmak üzere Google Arama ile temellendirme aracını, ardından içeriklerini analiz etmek için URL bağlamı aracını kullanır.

    Örnek istem:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

Aşağıdaki örnekte, hem URL bağlamı hem de Google Arama ile temellendirme araçlarının nasıl etkinleştirileceği ve kullanılacağı gösterilmektedir:


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

Kullanım alanınıza ve uygulamanıza uygun bir model nasıl seçeceğinizi öğrenin.

URL bağlamı aracının işleyiş şekli

URL bağlamı aracı, hız, maliyet ve güncel verilere erişim arasında denge kurmak için iki adımlı bir alma süreci kullanır.

1. adım: Belirli bir URL sağladığınızda araç, önce içeriği dahili bir dizin önbelleğinden getirmeye çalışır. Bu, son derece optimize edilmiş bir önbellek görevi görür.

2. adım: Bir URL dizinde yoksa (örneğin, çok yeni bir sayfaysa) araç otomatik olarak canlı getirme işlemine geri döner. Bu araç, içeriğini gerçek zamanlı olarak almak için doğrudan URL'ye erişir.

En iyi uygulamalar

  • Belirli URL'ler sağlama: En iyi sonuçları elde etmek için modelin analiz etmesini istediğiniz içeriğe doğrudan giden URL'ler sağlayın. Model yalnızca sağladığınız URL'lerden içerik alır, iç içe yerleştirilmiş bağlantılardaki içerikleri almaz.

  • Erişilebilirliği kontrol edin: Sağladığınız URL'lerin, giriş yapılması gereken veya ödeme duvarının arkasında olan sayfalara yönlendirmediğini doğrulayın.

  • Tam URL'yi kullanın: Protokolü de dahil ederek tam URL'yi sağlayın (örneğin, yalnızca example.com yerine https://www.example.com).

Yanıtı anlama

Modelin yanıtı, URL'lerden aldığı içeriğe göre belirlenir.

Model, URL'lerden içerik aldıysa yanıtta url_context_metadata yer alır. Bu tür bir yanıt aşağıdaki gibi görünebilir (yanıtın bazı bölümleri kısa olması için çıkarılmıştır):

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

Güvenlik kontrolleri

Sistem, URL'de içerik denetimi yaparak güvenlik standartlarına uygun olup olmadığını kontrol eder. Sağladığınız URL bu kontrolü geçemezse url_retrieval_status URL_RETRIEVAL_STATUS_UNSAFE alırsınız.

Sınırlamalar

URL bağlamı aracının bazı sınırlamaları şunlardır:

  • İşlev çağrısıyla birleştirme: URL bağlamı aracı, işlev çağrısının da kullanıldığı bir istekte kullanılamaz.

  • İstek başına URL sınırı: İstek başına maksimum URL sayısı 20'dir.

  • URL içerik boyutu sınırı: Tek bir URL'den alınan içeriklerin maksimum boyutu 34 MB'tır.

  • Güncellik: Araç, web sayfalarının canlı sürümlerini getirmez. Bu nedenle, güncellik veya güncelliğini yitirmiş bilgilerle ilgili sorunlar olabilir.

  • URL'nin herkese açık erişimi: Sağlanan URL'lere web'de herkes erişebilmelidir. Aşağıdakiler desteklenmez: ödeme duvarı olan içerikler, kullanıcı girişi gerektiren içerikler, özel ağlar, localhost adresleri (ör. localhost veya 127.0.0.1) ve tünel hizmetleri (ör. ngrok veya pinggy).

Desteklenen ve desteklenmeyen içerik türleri

Desteklenir: Araç, aşağıdaki içerik türlerine sahip URL'lerden içerik ayıklayabilir:

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

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

  • PDF (application/pdf)

Desteklenmiyor: Araç, aşağıdaki içerik türlerini desteklemez:

  • YouTube videoları (Bunun yerine videoları analiz etme başlıklı makaleyi inceleyin.)

  • Video ve ses dosyaları (Bunun yerine videoları analiz etme veya sesi analiz etme başlıklı makalelere bakın.)

  • Google Dokümanları veya e-tablolar gibi Google Workspace dosyaları

  • (Vertex AI Gemini API kullanılıyorsa) Cloud Storage URL'leri
    Bu tür URL'ler, Gemini Developer API'a nasıl eriştiğinizden bağımsız olarak desteklenmez.

  • Herkese açık olarak erişilemeyen içerikler Aşağıdakiler desteklenmez: Ödeme duvarı olan içerikler, kullanıcı girişi gerektiren içerikler, özel ağlar, localhost adresleri (ör. localhost veya 127.0.0.1) ve tünel oluşturma hizmetleri (ör. ngrok veya pinggy).

Fiyatlandırma ve araç jetonlarını sayma

URL'lerden alınan içerikler, giriş jetonu olarak sayılır.

İsteminizdeki jeton sayısını ve araç kullanımını usage_metadata model çıkışının nesnesinde görebilirsiniz. Aşağıda örnek bir çıkış verilmiştir:

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

Sıklık sınırı ve fiyatlandırma, kullanılan modele göre belirlenir. Seçtiğiniz Gemini API sağlayıcının dokümanlarında URL bağlamı aracının fiyatlandırması hakkında daha fazla bilgi edinin: Gemini Developer API | Vertex AI Gemini API.