Ngữ cảnh URL

Công cụ ngữ cảnh URL cho phép bạn cung cấp thêm ngữ cảnh cho mô hình dưới dạng URL. Mô hình có thể truy cập vào nội dung từ những URL đó để thông báo và nâng cao câu trả lời.

Ngữ cảnh URL có những lợi ích sau:

  • Trích xuất dữ liệu: Cung cấp thông tin cụ thể như giá, tên hoặc những phát hiện quan trọng từ một bài viết hoặc nhiều URL.

  • So sánh thông tin: Phân tích nhiều báo cáo, bài viết hoặc tệp PDF để xác định sự khác biệt và theo dõi xu hướng.

  • Tổng hợp và tạo nội dung: Kết hợp thông tin từ một số URL nguồn để tạo bản tóm tắt chính xác, bài đăng trên blog, báo cáo hoặc câu hỏi kiểm tra.

  • Phân tích mã và nội dung kỹ thuật: Cung cấp URL cho kho lưu trữ GitHub hoặc tài liệu kỹ thuật để giải thích mã, tạo hướng dẫn thiết lập hoặc trả lời câu hỏi.

Hãy nhớ xem các phương pháp hay nhấthạn chế khi sử dụng công cụ ngữ cảnh URL.

Mô hình được hỗ trợ

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

Ngôn ngữ được hỗ trợ

Xem các ngôn ngữ được hỗ trợ cho Gemini mô hình.

Sử dụng công cụ ngữ cảnh URL

Bạn có thể sử dụng công cụ ngữ cảnh URL theo 2 cách chính:

Chỉ công cụ ngữ cảnh URL

Nhấp vào nhà cung định Gemini API để xem nội dung dành riêng cho nhà cung cấp và mã trên trang này.

Khi tạo thực thể GenerativeModel, hãy cung cấp UrlContext dưới dạng một công cụ. Sau đó, trực tiếp vào câu lệnh, hãy cung cấp các URL cụ thể mà bạn muốn mô hình truy cập và phân tích.

Ví dụ sau đây cho thấy cách so sánh 2 công thức từ các trang web khác nhau:

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

Tìm hiểu cách chọn một mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.

Nhấp vào nhà cung định Gemini API để xem nội dung dành riêng cho nhà cung cấp và mã trên trang này.

Bạn có thể bật cả ngữ cảnh URL và tính năng dựa trên kết quả của Google Tìm kiếm. Với cấu hình này, bạn có thể viết câu lệnh có hoặc không có URL cụ thể.

Khi tính năng Dựa trên kết quả của Google Tìm kiếm cũng được bật, mô hình có thể sử dụng Google Tìm kiếm trước tiên để tìm thông tin có liên quan, sau đó sử dụng công cụ ngữ cảnh URL để đọc nội dung của kết quả tìm kiếm nhằm hiểu rõ hơn về thông tin. Phương pháp này rất hữu ích cho những câu lệnh yêu cầu cả tìm kiếm rộng và phân tích sâu các trang cụ thể.

Dưới đây là một số trường hợp sử dụng:

  • Bạn cung cấp một URL trong câu lệnh để hỗ trợ một số câu trả lời được tạo. Tuy nhiên, để tạo câu trả lời phù hợp, mô hình vẫn cần thêm thông tin về các chủ đề khác, vì vậy, mô hình sử dụng công cụ dựa trên kết quả của Google Tìm kiếm.

    Câu lệnh mẫu:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • Bạn không cung cấp URL nào trong câu lệnh. Vì vậy, để tạo câu trả lời phù hợp, mô hình sử dụng công cụ dựa trên kết quả của Google Tìm kiếm để tìm các URL có liên quan, sau đó sử dụng công cụ ngữ cảnh URL để phân tích nội dung của các URL đó.

    Câu lệnh mẫu:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

Ví dụ sau đây cho thấy cách bật và sử dụng cả 2 công cụ – ngữ cảnh URL và tính năng dựa trên kết quả của Google Tìm kiếm:


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

Tìm hiểu cách chọn một mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.

Cách hoạt động của công cụ ngữ cảnh URL

Công cụ ngữ cảnh URL sử dụng quy trình truy xuất gồm 2 bước để cân bằng tốc độ, chi phí và quyền truy cập vào dữ liệu mới.

Bước 1: Khi bạn cung cấp một URL cụ thể, công cụ này sẽ cố gắng tìm nạp nội dung từ bộ nhớ đệm chỉ mục nội bộ. Đây là một bộ nhớ đệm được tối ưu hoá cao.

Bước 2: Nếu một URL không có trong chỉ mục (ví dụ: nếu đó là một trang rất mới), công cụ này sẽ tự động quay lại để tìm nạp phiên bản hoạt động. Thao tác này sẽ truy cập trực tiếp vào URL để truy xuất nội dung của URL đó theo thời gian thực.

Các phương pháp hay nhất

  • Cung cấp URL cụ thể: Để có kết quả tốt nhất, hãy cung cấp URL trực tiếp đến nội dung mà bạn muốn mô hình phân tích. Mô hình sẽ chỉ truy xuất nội dung từ các URL mà bạn cung cấp, chứ không phải bất kỳ nội dung nào từ các đường liên kết lồng ghép.

  • Kiểm tra khả năng truy cập: Xác minh rằng các URL mà bạn cung cấp không dẫn đến các trang yêu cầu đăng nhập hoặc nằm sau tường phí.

  • Sử dụng URL hoàn chỉnh: Cung cấp URL đầy đủ, bao gồm cả giao thức (ví dụ: https://www.example.com thay vì chỉ example.com).

Tìm hiểu về câu trả lời

Câu trả lời của mô hình sẽ dựa trên nội dung mà mô hình truy xuất từ các URL.

Nếu mô hình truy xuất nội dung từ các URL, câu trả lời sẽ bao gồm url_context_metadata. Một câu trả lời như vậy có thể có dạng như sau (một số phần của câu trả lời đã bị bỏ qua để ngắn gọn):

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

Kiểm tra an toàn

Hệ thống thực hiện quy trình kiểm tra kiểm duyệt nội dung trên URL để xác nhận rằng các URL đó đáp ứng các tiêu chuẩn an toàn. Nếu URL mà bạn cung cấp không vượt qua quy trình kiểm tra này, bạn sẽ nhận được url_retrieval_statusURL_RETRIEVAL_STATUS_UNSAFE.

Hạn chế

Dưới đây là một số hạn chế của công cụ ngữ cảnh URL:

  • Kết hợp với tính năng gọi hàm: Bạn không thể sử dụng công cụ ngữ cảnh URL trong một yêu cầu cũng sử dụng tính năng gọi hàm.

  • Giới hạn số lượng URL trên mỗi yêu cầu: Số lượng URL tối đa trên mỗi yêu cầu là 20 URL.

  • Giới hạn kích thước nội dung URL: Kích thước tối đa cho nội dung được truy xuất từ một URL là 34 MB.

  • Độ mới: Công cụ này không tìm nạp các phiên bản hoạt động của trang web, vì vậy, có thể có một số vấn đề về độ mới hoặc thông tin có khả năng đã lỗi thời.

  • Khả năng truy cập công khai của URL: Các URL được cung cấp phải có thể truy cập công khai trên web. Những URL sau đây không được hỗ trợ: nội dung có tường phí, nội dung yêu cầu người dùng đăng nhập, mạng riêng tư, địa chỉ máy chủ cục bộ (như localhost hoặc 127.0.0.1) và dịch vụ tạo đường hầm (như ngrok hoặc pinggy).

Các loại nội dung được hỗ trợ và không được hỗ trợ

Được hỗ trợ: Công cụ này có thể trích xuất nội dung từ các URL có các loại nội dung sau:

  • Văn bản (text/html, application/json, text/plain, text/xml, text/css, text/javascript, text/csv, text/rtf)

  • Hình ảnh (image/png, image/jpeg, image/bmp, image/webp)

  • PDF (application/pdf)

Không được hỗ trợ: Công cụ này không hỗ trợ các loại nội dung sau:

  • Video trên YouTube (thay vào đó, hãy xem bài viết phân tích video)

  • Tệp video và âm thanh (thay vào đó, hãy xem bài viết phân tích video hoặc phân tích âm thanh)

  • Tệp Google Workspace, chẳng hạn như tài liệu hoặc bảng tính trên Google

  • (nếu sử dụng Vertex AI Gemini API) Cloud Storage URL
    Các loại URL này không được Gemini Developer API hỗ trợ, bất kể bạn truy cập vào API đó bằng cách nào.

  • Nội dung không được cung cấp công khai. Những URL sau đây không được hỗ trợ: nội dung có tường phí, nội dung yêu cầu người dùng đăng nhập, mạng riêng tư, địa chỉ máy chủ cục bộ (như localhost hoặc 127.0.0.1) và dịch vụ tạo đường hầm (như ngrok hoặc pinggy).

Giá và cách tính mã thông báo công cụ

Nội dung được truy xuất từ các URL được tính là mã thông báo đầu vào.

Bạn có thể xem số lượng token cho câu lệnh và mức sử dụng công cụ trong đối tượng usage_metadata của đầu ra của mô hình. Sau đây là một kết quả mẫu:

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

Giới hạn về tỷ lệ và giá dựa trên mô hình được sử dụng. Tìm hiểu thêm về giá cho công cụ ngữ cảnh URL trong tài liệu về nhà cung cấp Gemini APImà bạn chọn: Gemini Developer API | Vertex AI Gemini API.