URL context

Khi sử dụng công cụ ngữ cảnh URL, bạn có thể cung cấp cho Gemini các URL làm ngữ cảnh bổ sung cho câu lệnh của mình. Sau đó, mô hình có thể truy xuất nội dung từ các URL và sử dụng nội dung đó để thông báo và định hình phản hồi.

Công cụ này hữu ích cho các tác vụ như sau:

  • Trích xuất các điểm dữ liệu chính hoặc điểm cần đề cập trong bài viết
  • So sánh thông tin trên nhiều đường liên kết
  • Tổng hợp dữ liệu từ nhiều nguồn
  • Trả lời câu hỏi dựa trên nội dung của một hoặc nhiều trang cụ thể
  • Phân tích nội dung cho các mục đích cụ thể (chẳng hạn như viết nội dung mô tả công việc hoặc tạo câu hỏi kiểm tra)

Hướng dẫn này giải thích cách sử dụng công cụ ngữ cảnh URL trong API Gemini.

Sử dụng ngữ cảnh URL

Bạn có thể sử dụng công cụ ngữ cảnh URL theo hai cách chính, riêng lẻ hoặc kết hợp với tính năng Lấy thông tin cơ bản từ Google Tìm kiếm.

Chỉ ngữ cảnh URL

Bạn cung cấp các URL cụ thể mà bạn muốn mô hình phân tích trực tiếp trong câu lệnh.

Câu lệnh mẫu:

Summarize this document: YOUR_URLs

Extract the key features from the product description on this page: YOUR_URLs

Tìm hiểu thông tin cơ bản bằng Google Tìm kiếm + ngữ cảnh URL

Bạn cũng có thể bật cả ngữ cảnh URL và tính năng Liên kết với Google Tìm kiếm cùng một lúc. Bạn có thể nhập câu lệnh có hoặc không có URL. Trước tiên, mô hình có thể tìm kiế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.

Câu lệnh mẫu:

Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute.

Recommend 3 books for beginners to read to learn more about the latest YOUR_subject.

Ví dụ về mã chỉ có ngữ cảnh URL

Python

from google import genai
from google.genai.types import Tool, GenerateContentConfig, GoogleSearch

client = genai.Client()
model_id = "gemini-2.5-flash-preview-05-20"

url_context_tool = Tool(
    url_context = types.UrlContext
)

response = client.models.generate_content(
    model=model_id,
    contents="Compare recipes from YOUR_URL1 and YOUR_URL2",
    config=GenerateContentConfig(
        tools=[url_context_tool],
        response_modalities=["TEXT"],
    )
)

for each in response.candidates[0].content.parts:
    print(each.text)
# get URLs retrieved for context
print(response.candidates[0].url_context_metadata)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash-preview-05-20",
    contents: [
        "Compare recipes from YOUR_URL1 and YOUR_URL2",
    ],
    config: {
      tools: [{urlContext: {}}],
    },
  });
  console.log(response.text);
  // To get URLs retrieved for context
  console.log(response.candidates[0].urlContextMetadata)
}

await main();

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=$GOOGLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "contents": [
          {
              "parts": [
                  {"text": "Compare recipes from YOUR_URL1 and YOUR_URL2"}
              ]
          }
      ],
      "tools": [
          {
              "url_context": {}
          }
      ]
  }' > result.json

cat result.json

Python

from google import genai
from google.genai.types import Tool, GenerateContentConfig, GoogleSearch

client = genai.Client()
model_id = "gemini-2.5-flash-preview-05-20"

tools = []
tools.append(Tool(url_context=types.UrlContext))
tools.append(Tool(google_search=types.GoogleSearch))

response = client.models.generate_content(
    model=model_id,
    contents="Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute.",
    config=GenerateContentConfig(
        tools=tools,
        response_modalities=["TEXT"],
    )
)

for each in response.candidates[0].content.parts:
    print(each.text)
# get URLs retrieved for context
print(response.candidates[0].url_context_metadata)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash-preview-05-20",
    contents: [
        "Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute.",
    ],
    config: {
      tools: [{urlContext: {}}, {googleSearch: {}}],
    },
  });
  console.log(response.text);
  // To get URLs retrieved for context
  console.log(response.candidates[0].urlContextMetadata)
}

await main();

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=$GOOGLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "contents": [
          {
              "parts": [
                  {"text": "Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute."}
              ]
          }
      ],
      "tools": [
          {
              "url_context": {}
          },
          {
              "google_search": {}
          }
      ]
  }' > result.json

cat result.json

Để biết thêm thông tin chi tiết về tính năng Làm dịu căng thẳng bằng Google Tìm kiếm, hãy xem trang tổng quan.

Phản hồi theo ngữ cảnh

Phản hồ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, phản hồi sẽ bao gồm url_context_metadata. Câu trả lời như vậy có thể có dạng như sau (để ngắn gọn, chúng tôi đã bỏ qua một số phần của câu trả lời):

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "... \n"
          }
        ],
        "role": "model"
      },
      ...
      "url_context_metadata":
      {
          "url_metadata":
          [
            {
              "retrieved_url": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/1234567890abcdef",
              "url_retrieval_status": <UrlRetrievalStatus.URL_RETRIEVAL_STATUS_SUCCESS: "URL_RETRIEVAL_STATUS_SUCCESS">
            },
            {
              "retrieved_url": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/abcdef1234567890",
              "url_retrieval_status": <UrlRetrievalStatus.URL_RETRIEVAL_STATUS_SUCCESS: "URL_RETRIEVAL_STATUS_SUCCESS">
            },
            {
              "retrieved_url": "YOUR_URL",
              "url_retrieval_status": <UrlRetrievalStatus.URL_RETRIEVAL_STATUS_SUCCESS: "URL_RETRIEVAL_STATUS_SUCCESS">
            },
            {
              "retrieved_url": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/fedcba0987654321",
              "url_retrieval_status": <UrlRetrievalStatus.URL_RETRIEVAL_STATUS_SUCCESS: "URL_RETRIEVAL_STATUS_SUCCESS">
            }
          ]
        }
    }
}

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

Các điểm hạn chế

  • Công cụ này sẽ sử dụng tối đa 20 URL cho mỗi yêu cầu phân tích.
  • Để có kết quả tốt nhất trong giai đoạn thử nghiệm, hãy sử dụng công cụ này trên các trang web tiêu chuẩn thay vì nội dung đa phương tiện như video trên YouTube.
  • Trong giai đoạn thử nghiệm, bạn có thể sử dụng công cụ này mà không mất phí. Hệ thống sẽ tính phí sau.
  • Bản phát hành thử nghiệm có các hạn mức sau:

    • 1.500 truy vấn mỗi ngày cho mỗi dự án đối với các yêu cầu được thực hiện thông qua Gemini API
    • 100 lượt truy vấn mỗi ngày trên mỗi người dùng trong Google AI Studio