URL 컨텍스트

URL 컨텍스트 도구를 사용하여 프롬프트의 추가 컨텍스트로 Gemini에 URL을 제공할 수 있습니다. 그러면 모델이 URL에서 콘텐츠를 검색하고 해당 콘텐츠를 사용하여 대답을 알리고 만들 수 있습니다.

이 도구는 다음과 같은 태스크에 유용합니다.

  • 문서에서 주요 데이터 포인트 추출 또는 요점 사용
  • 여러 링크의 정보 비교
  • 여러 소스의 데이터 합성
  • 특정 페이지의 콘텐츠를 기반으로 질문에 답변
  • 특정 목적(예: 직무 설명 작성 또는 테스트 문제 만들기)으로 콘텐츠 분석

데이터를 가져오는 데 사용된 색인이 최신 상태가 아닐 수 있으므로 일부 정보가 오래되었을 수 있습니다.

이 가이드에서는 Vertex AI의 Gemini API에서 URL 컨텍스트 도구를 사용하는 방법을 설명합니다.

지원되는 모델

다음 모델에서 URL 컨텍스트를 지원합니다.

URL 컨텍스트 사용

URL 컨텍스트 도구를 단독으로 또는 Google 검색으로 그라운딩과 함께 등 두 가지 주요 방법으로 사용할 수 있습니다.

URL 컨텍스트 전용

프롬프트에서 모델이 분석할 특정 URL을 직접 제공할 수 있습니다.

Summarize this document: YOUR_URLs

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

Python

from google import genai
from google.genai.types import Tool, GenerateContentConfig, HttpOptions, UrlContext

client = genai.Client(http_options=HttpOptions(api_version="v1"))
model_id = "gemini-2.5-flash"

url_context_tool = Tool(
    url_context = 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)

자바스크립트

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
  vertexai: true,
  project: process.env.GOOGLE_CLOUD_PROJECT,
  location: process.env.GOOGLE_CLOUD_LOCATION,
  apiVersion: 'v1',
});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    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 -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://aiplatform.googleapis.com/v1beta1/projects/GOOGLE_CLOUD_PROJECT/locations/global/publishers/google/models/gemini-2.5-flash:generateContent \
  -d '{
      "contents": [
          {
              "role": "user",
              "parts": [
                  {"text": "Compare recipes from YOUR_URL1 and YOUR_URL2"}
              ]
          }
      ],
      "tools": [
          {
              "url_context": {}
          }
      ]
  }' > result.json

cat result.json

URL 컨텍스트가 있는 Google 검색으로 그라운딩

URL이 포함되거나 포함되지 않은 프롬프트를 사용하여 URL 컨텍스트와 Google 검색으로 그라운딩을 모두 사용 설정할 수도 있습니다. 모델은 먼저 관련 정보를 검색한 후 심도 있게 이해할 수 있도록 URL 컨텍스트 도구를 사용하여 검색 결과 콘텐츠를 읽습니다.

이 기능은 실험용이며 API 버전 v1beta1에서 사용 가능합니다.

프롬프트 예시:

Give me a three day event 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.

Python

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

client = genai.Client(http_options=HttpOptions(api_version="v1beta1"))
model_id = "gemini-2.5-flash"

tools = []
tools.append(Tool(url_context=UrlContext))
tools.append(Tool(google_search=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)

자바스크립트

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
  vertexai: true,
  project: process.env.GOOGLE_CLOUD_PROJECT,
  location: process.env.GOOGLE_CLOUD_LOCATION,
  apiVersion: 'v1beta1',
});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents: [
        "Give me a three day event 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 -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://aiplatform.googleapis.com/v1beta1/projects/GOOGLE_CLOUD_PROJECT/locations/global/publishers/google/models/gemini-2.5-flash:generateContent \
  -d '{
      "contents": [
          {
              "role": "user",
              "parts": [
                  {"text": "Give me a three day event 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

Google 검색으로 그라운딩에 대한 자세한 내용은 개요 페이지를 참조하세요.

URL 컨텍스트가 있는 엔터프라이즈용 웹 그라운딩

특정 규제 준수 니즈가 있거나 의료, 금융 또는 공공 부문과 같은 규제 대상 업종에 종사하는 경우 URL 컨텍스트와 엔터프라이즈용 웹 그라운딩을 모두 사용 설정할 수 있습니다. 엔터프라이즈용 웹 그라운딩에 사용되는 웹 색인은 Google 검색에서 사용할 수 있는 항목의 하위 집합을 사용하므로 표준 Google 검색으로 그라운딩 보다 더 제한적입니다.

Enterprise용 웹 그라운딩에 대한 자세한 내용은 Enterprise용 웹 그라운딩 페이지를 참조하세요.

맥락에 맞는 대답

모델 대답은 URL에서 검색한 콘텐츠를 기반으로 합니다. 모델이 URL에서 콘텐츠를 검색하면 대답에 url_context_metadata가 포함됩니다. 이러한 대답은 다음과 같이 표시될 수 있습니다(간결성을 위해 대답 일부가 생략됨).

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "... \n"
          }
        ],
        "role": "model"
      },
      ...
      "url_context_metadata":
      {
          "url_metadata":
          [
            {
              "retrieved_url": "https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/code-execution",
              "url_retrieval_status": <UrlRetrievalStatus.URL_RETRIEVAL_STATUS_SUCCESS: "URL_RETRIEVAL_STATUS_SUCCESS">
            },
            {
              "retrieved_url": "https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-search",
              "url_retrieval_status": <UrlRetrievalStatus.URL_RETRIEVAL_STATUS_SUCCESS: "URL_RETRIEVAL_STATUS_SUCCESS">
            },
          ]
        }
    }
  ]
}

이 객체에 대한 자세한 내용은 UrlContextMetadata API 참조를 확인하세요.

실시간 가져오기

URL 컨텍스트 도구는 웹페이지의 라이브 버전을 가져와 정보를 최신 상태로 유지합니다.

웹페이지 콘텐츠를 효율적으로 가져오기 위해 URL 컨텍스트 도구는 속도, 비용, 최신 정보 액세스의 균형을 맞추도록 설계된 2단계 프로세스를 사용합니다.

  1. 색인 콘텐츠 검색: 첫 번째 단계입니다. URL을 제공하면 도구는 먼저 Google의 광범위하고 고도로 최적화된 웹 색인에서 콘텐츠를 가져오려고 시도합니다. 이 방법을 사용하면 크롤링된 방대한 웹페이지 모음에 빠르게 액세스할 수 있습니다.

  2. 실시간 가져오기 대체: 두 번째 단계입니다. 특정 URL의 콘텐츠가 색인에서 제공되지 않는 경우(예: 페이지가 최근에 만들어져 아직 색인이 생성되지 않은 경우) 도구에서 자동으로 실시간 가져오기를 수행합니다. 이 대체 메커니즘으로 URL에 직접 액세스하여 최신 버전의 콘텐츠를 실시간으로 가져올 수 있습니다.

안전 확인

시스템은 URL이 안전 표준을 충족하는지 확인하기 위해 URL에 대한 콘텐츠 검토를 수행합니다. 제공한 URL이 이 검사를 통과하지 못하면 URL_RETRIEVAL_STATUS_UNSAFEurl_retrieval_status가 표시됩니다.

토큰 수

입력 토큰 수에는 프롬프트에 지정한 URL에서 가져온 콘텐츠가 포함됩니다. 모델 출력에서 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
  }

토큰당 가격은 사용하는 모델에 따라 다릅니다. 자세한 정보는 Vertex AI에서 AI 모델을 빌드하고 배포하는 데 드는 비용을 참조하세요.

지원되는 콘텐츠 유형과 지원되지 않는 콘텐츠 유형

URL 컨텍스트 도구는 다음 콘텐츠 유형의 URL에서 콘텐츠를 추출할 수 있습니다.

콘텐츠 유형
텍스트 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

URL 컨텍스트 도구는 다음 콘텐츠 유형을 지원하지 않습니다.

  • 페이월 콘텐츠
  • YouTube 동영상(자세한 내용은 동영상 이해 참조)
  • Google Docs 또는 Google Sheets와 같은 Google Workspace 파일
  • 동영상 및 오디오 파일

제한사항

  • URL 컨텍스트 도구는 분석에 URL을 요청당 최대 20개까지 사용합니다.
  • 실험용 단계에서 최상의 결과를 얻으려면 YouTube 동영상과 같은 멀티미디어 콘텐츠가 아닌 표준 웹페이지에서 도구를 사용합니다.