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 đó để cung cấp thông tin và cải thiện câu trả lời.
Bối cảnh URL mang lại 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 phát hiện chính 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 điểm 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ừ nhiều URL nguồn để tạo bản tóm tắt, bài đăng trên blog, báo cáo hoặc câu hỏi kiểm tra chính xác.
Phân tích mã và nội dung kỹ thuật: Cung cấp URL cho một kho lưu trữ trên 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.
Đảm bảo rằng bạn đã xem xét các phương pháp hay nhất và các hạn chế khi sử dụng công cụ bối cảnh URL.
Các mô hình được hỗ trợ
gemini-3-pro-previewgemini-3-flash-previewgemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
Ngôn ngữ được hỗ trợ
Xem các ngôn ngữ được hỗ trợ cho các mô hình Gemini.
Sử dụng công cụ bối cảnh URL
Bạn có thể sử dụng công cụ bối cảnh URL theo 2 cách chính:
Chỉ công cụ ngữ cảnh URL
|
Nhấp vào nhà cung cấp Gemini API để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này. |
Khi bạn tạo thực thể GenerativeModel, hãy cung cấp UrlContext làm công cụ.
Sau đó, hãy cung cấp trực tiếp vào câu lệnh của bạn những 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 hai công thức nấu ăn trên 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.
Ngữ cảnh URL kết hợp với thông tin cơ sở từ Google Tìm kiếm
|
Nhấp vào nhà cung cấp Gemini API để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể bật cả ngữ cảnh URL và căn cứ vào 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 bạn bật tính năng tiếp đất bằng Google Tìm kiếm, mô hình có thể dùng Google Tìm kiếm để tìm thông tin liên quan, sau đó 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 hiệu quả đối với những câu lệnh yêu cầu cả tìm kiếm trên diện rộng và phân tích chuyên sâu các trang cụ thể.
Sau đâ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 ra 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ụ tiếp đất bằng 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 trong câu lệnh. Vì vậy, để tạo ra một câu trả lời phù hợp, mô hình này sử dụng công cụ cơ sở kiến thức với 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ả hai công cụ này – ngữ cảnh URL và cơ sở kiến thức với Google Tìm kiếm:
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 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
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 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
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 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
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 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
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 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
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 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 hai 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 trước tiên 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ụ sẽ tự động quay lại để thực hiện quy trình tìm nạp trực tiếp. Thao tác này truy cập trực tiếp vào URL để truy xuất nội dung 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 này sẽ chỉ truy xuất nội dung từ những URL mà bạn cung cấp, chứ không phải nội dung từ các đường liên kết lồng nhau.
Kiểm tra khả năng tiếp cận: Xác minh rằng các URL bạn cung cấp không dẫn đến những trang yêu cầu đăng nhập hoặc nằm sau tường phí.
Sử dụng URL đầy đủ: Cung cấp URL đầy đủ, bao gồm cả giao thức (ví dụ:
https://www.example.comthay vì chỉexample.com).
Hiểu rõ 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 được từ các URL.
Nếu mô hình truy xuất nội dung từ URL, thì phản hồi sẽ bao gồm url_context_metadata. Phản hồi như vậy có thể có dạng như sau (một số phần của phản hồi đã bị bỏ qua để cho 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 sẽ kiểm tra nội dung của URL để xác nhận rằng các URL đó đáp ứng các tiêu chuẩn an toàn. Nếu URL bạn cung cấp không vượt qua bước kiểm tra này, bạn sẽ nhận được url_retrieval_status là URL_RETRIEVAL_STATUS_UNSAFE.
Hạn chế
Sau đây là một số hạn chế của công cụ bối 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ụ bối 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 duy nhất là 34 MB.
Độ mới: Công cụ này không tìm nạp phiên bản hiện tại của trang web, vì vậy có thể có một số vấn đề về độ mới hoặc thông tin có thể đã lỗi thời.
Khả năng truy cập công khai vào URL: Các URL bạn cung cấp phải có thể truy cập công khai trên web. Những nội dung không được hỗ trợ bao gồm: 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ộ (chẳng hạn như
localhosthoặc127.0.0.1) và dịch vụ đường hầm (chẳng hạn 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ó 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 phần phân tích video)
Tệp video và âm thanh (thay vào đó, hãy xem phần phân tích video hoặc phân tích âm thanh)
Các tệp trên 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) URL Cloud Storage
Gemini Developer API không hỗ trợ các loại URL này, bất kể bạn truy cập bằng cách nào.Nội dung không truy cập được công khai. Sau đây là những nội dung 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ộ (chẳng hạn như
localhosthoặc127.0.0.1) và dịch vụ đường hầm (chẳng hạn như ngrok hoặc pinggy).
Mã thông báo công cụ định giá và đếm
Nội dung được truy xuất từ URL được tính là mã thông báo đầu vào.
Bạn có thể xem số lượng mã thông báo cho câu lệnh và mức sử dụng công cụ trong đối tượng usage_metadata của đầu ra mô hình. Sau đây là một ví dụ về kết quả đầu ra:
'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
}
Hạn mức và giá cả dựa trên mô hình được sử dụng. Tìm hiểu thêm về giá của công cụ ngữ cảnh URL trong tài liệu về nhà cung cấp Gemini API mà bạn chọn: Gemini Developer API | Vertex AI Gemini API.