網址背景資訊

您可以使用網址背景資訊工具,以網址形式提供額外脈絡資訊給模型。模型可以存取這些網址的內容,做為回覆的參考依據,並提升回覆品質。

網址背景資訊有下列優點:

  • 擷取資料:提供特定資訊,例如價格、名稱,或來自文章或多個網址的重要發現。

  • 比較資訊:分析多份報表、文章或 PDF,找出差異並追蹤趨勢。

  • 統整及建立內容:整合多個來源網址的資訊,生成準確的摘要、網誌文章、報告或測驗問題。

  • 分析程式碼和技術內容:提供 GitHub 存放區或技術文件的網址,說明程式碼、產生設定操作說明或回答問題。

使用網址內容工具時,請務必詳閱最佳做法和限制。

支援的模型

  • gemini-3.1-pro-preview
  • gemini-3.8-flash (以及舊版 gemini-3.7-flash、gemini-3.6-flash 和 gemini-3.5-flash)
  • gemini-3.5-flash-lite (和舊版 gemini-3.1-flash-lite)

一般用途 Gemini 2.5 模型支援這項功能,但都已淘汰。

支援的語言

如要瞭解 Gemini 模型支援的語言,請參閱這篇文章。

使用網址背景資訊工具

您主要可以透過兩種方式使用網址背景資訊工具:

僅限網址背景資訊工具

按一下 Gemini API 供應商,即可在這個頁面查看供應商專屬內容和程式碼。

建立 GenerativeModel 例項時,請提供 UrlContext 做為工具。 然後直接在提示中提供您要模型存取和分析的特定網址。

以下範例說明如何比較不同網站的兩份食譜:

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 供應商,即可在這個頁面查看供應商專屬內容和程式碼。

您可以同時啟用網址脈絡和以 Google Search 為基礎的。完成這項設定後,您就能撰寫含有或不含特定網址的提示。

如果同時啟用「以 Google Search 建立基準」,模型可能會先使用 Google Search 尋找相關資訊,然後使用網址背景資訊工具讀取搜尋結果的內容,以便更深入瞭解資訊。如果提示需要廣泛搜尋和深入分析特定網頁,這個方法就非常實用。

以下列舉一些用途:

  • 在提示中提供網址,有助於生成部分回覆。 不過,模型仍需要其他主題的資訊,才能生成適當的回覆,因此會使用「以 Parallel Web Search 建立基準」Google Search工具。

    提示詞範例:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • 您完全未在提示中提供網址。因此,為了生成適當的回覆,模型會使用「Grounding with Google Search」工具尋找相關網址,然後使用網址脈絡工具分析網址內容。

    提示詞範例:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

以下範例說明如何啟用及使用這兩項工具 (網址背景資訊和 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

瞭解如何選擇適合應用程式和用途的模型, 。

網址背景資訊工具的運作方式

網址內容工具採用兩階段的擷取程序,兼顧速度、成本和最新資料存取權。

步驟 1:提供特定網址後,工具會先嘗試從內部索引快取擷取內容。這可做為經過高度最佳化的快取。

步驟 2:如果網址不在索引中 (例如網頁剛發布),工具會自動改為即時擷取。這項工具會直接存取網址,即時擷取內容。

最佳做法

  • 提供具體網址:為獲得最佳結果,請提供您希望模型分析的內容的直接網址。模型只會從您提供的網址擷取內容,不會從巢狀連結擷取任何內容。

  • 檢查存取方式:確認提供的網址不會導向需要登入或位於付費牆後的網頁。

  • 使用完整網址:提供完整網址,包括通訊協定 (例如 https://www.example.com,而非只有 example.com)。

瞭解回覆內容

模型會根據從網址擷取的內容生成回覆。

如果模型從網址擷取內容,回覆中會包含 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_retrieval_statusURL_RETRIEVAL_STATUS_UNSAFE。

限制

網址情境工具的限制如下:

  • 與函式呼叫功能搭配使用:網址內容工具無法在同時使用函式呼叫的請求中使用。

  • 每項要求最多可包含的網址數:每項要求最多可包含 20 個網址。

  • 網址內容大小限制:從單一網址擷取的內容大小上限為 34 MB。

  • 即時性:這項工具不會擷取網頁的即時版本,因此可能會有即時性問題,或提供過時資訊。

  • 網址公開存取權:提供的網址必須可在網路上公開存取。系統不支援下列項目:付費牆內容、需要使用者登入的內容、私人網路、本機位址 (如 localhost 或 127.0.0.1) 和通道服務 (如 ngrok 或 pinggy)。

支援及不支援的內容類型

支援:這項工具可從下列內容類型的網址中擷取內容:

  • 文字 (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 文件或試算表

  • (如果使用 Agent Platform Gemini API (formerly Vertex AI)) Cloud Storage 網址
    無論您如何存取,Gemini Developer API 都不支援這類網址。

  • 無法公開存取的內容。不支援的內容包括:付費牆內容、需要登入才能觀看的內容、私人網路、本機位址 (例如 localhost 或 127.0.0.1) 和通道服務 (例如 ngrok 或 pinggy)。

定價和計算工具權杖

從網址擷取的內容會計為輸入權杖。

您可以在模型輸出的 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 | Agent Platform Gemini API (formerly Vertex AI)。