URL context

URL context

URL context 도구는 모델에 URL 형태의 추가 컨텍스트를 제공해요. 요청에 URL을 포함하면 모델이 해당 페이지의 콘텐츠(limitations 섹션에 나열된 URL 유형이 아니라면)에 접근해 응답을 풍부하게 만들 수 있어요.

URL context 도구는 다음과 같은 작업에 유용해요.

  • 데이터 추출: 여러 URL에서 가격·이름·핵심 결과 같은 특정 정보를 뽑아요.
  • 문서 비교: 여러 보고서·기사·PDF를 분석해 차이를 식별하고 추세를 추적해요.
  • 종합·콘텐츠 생성: 여러 소스 URL의 정보를 결합해 정확한 요약·블로그 포스트·보고서를 생성해요.
  • 코드·문서 분석: GitHub 저장소나 기술 문서를 가리켜 코드를 설명하고 설정 지침을 생성하거나 질문에 답해요.

다음 예제는 서로 다른 웹사이트의 레시피 두 개를 비교하는 방법을 보여줘요.

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

client = genai.Client()
model_id = "gemini-3.8-flash"

tools = [
  {"url_context": {}},
]

url1 = "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592"
url2 = "https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/"

response = client.models.generate_content(
    model=model_id,
    contents=f"Compare the ingredients and cooking times from the recipes at {url1} and {url2}",
    config=GenerateContentConfig(
        tools=tools,
    )
)

for each in response.candidates[0].content.parts:
    print(each.text)

# For verification, you can inspect the metadata to see which URLs the model retrieved
print(response.candidates[0].url_context_metadata)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-3.8-flash",
    contents: [
        "Compare the ingredients and cooking times from the recipes at https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592 and https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/",
    ],
    config: {
      tools: [{urlContext: {}}],
    },
  });
  console.log(response.text);

  // For verification, you can inspect the metadata to see which URLs the model retrieved
  console.log(response.candidates[0].urlContextMetadata)
}

await main();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "contents": [
          {
              "parts": [
                  {"text": "Compare the ingredients and cooking times from the recipes at https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592 and https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/"}
              ]
          }
      ],
      "tools": [
          {
              "url_context": {}
          }
      ]
  }' > result.json

cat result.json

출처: 원문

본문

작동 방식

URL Context 도구는 속도·비용·최신 데이터 접근의 균형을 맞추는 2단계 검색 과정을 사용해요. URL을 제공하면 도구는 먼저 내부 인덱스 캐시에서 콘텐츠를 가져오려고 해요. 이는 고도로 최적화된 캐시 역할을 해요. URL이 인덱스에 없으면(예: 아주 새로운 페이지), 도구는 자동으로 라이브 fetch로 폴백해 실시간으로 URL에 직접 접근해 콘텐츠를 가져와요.

다른 도구와 결합하기

URL context 도구를 다른 도구와 결합해 더 강력한 워크플로를 만들 수 있어요.

Gemini 3 모델은 내장 도구(URL Context 같은)와 커스텀 도구(함수 호출)의 결합을 지원해요. tool combinations 페이지에서 자세히 알아보세요.

검색과 접지

URL context와 Google Search 접지가 모두 활성화되면 모델은 검색 능력으로 온라인에서 관련 정보를 찾은 뒤, URL context 도구로 찾은 페이지를 더 깊이 이해할 수 있어요. 넓은 검색과 특정 페이지의 심층 분석이 모두 필요한 프롬프트에 강력한 접근이에요.

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

client = genai.Client()
model_id = "gemini-3.8-flash"

tools = [
      {"url_context": {}},
      {"google_search": {}}
  ]

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,
    )
)

for each in response.candidates[0].content.parts:
    print(each.text)
# get URLs retrieved for context
print(response.candidates[0].url_context_metadata)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-3.8-flash",
    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();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: YOUR_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

응답 이해하기

모델이 URL context 도구를 사용하면 응답에 url_context_metadata 객체가 포함돼요. 이 객체는 모델이 콘텐츠를 가져온 URL과 각 가져오기 시도의 상태를 나열해, 검증과 디버깅에 유용해요.

응답의 그 부분 예시는 다음과 같아요(간결성을 위해 일부 생략).

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "... \n"
          }
        ],
        "role": "model"
      },
      ...
      "url_context_metadata": {
        "url_metadata": [
          {
            "retrieved_url": "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592",
            "url_retrieval_status": "URL_RETRIEVAL_STATUS_SUCCESS"
          },
          {
            "retrieved_url": "https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/",
            "url_retrieval_status": "URL_RETRIEVAL_STATUS_SUCCESS"
          }
        ]
      }
    }
  ]
}

이 객체에 대한 완전한 세부 사항은 UrlContextMetadata API reference를 참고하세요.

안전 검사

시스템은 URL에 콘텐츠 조정(moderation) 검사를 수행해 안전 기준을 충족하는지 확인해요. 제공한 URL이 이 검사를 통과하지 못하면 url_retrieval_status가 URL_RETRIEVAL_STATUS_UNSAFE로 나와요.

토큰 수

프롬프트에서 지정한 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
  }

토큰당 가격은 사용 모델에 따라 다르며, 자세한 내용은 pricing 페이지를 참고하세요.

지원 모델

모델 URL Context
Gemini 3.8 Flash ✔️
Gemini 3.7 Flash ✔️
Gemini 3.6 Flash ✔️
Gemini 3.5 Flash-Lite ✔️
Gemini 3.5 Flash ✔️
Gemini 3.1 Pro Preview ✔️
Gemini 3.1 Flash-Lite ✔️
Gemini 3 Flash Preview ✔️
Gemini 2.5 Pro ✔️
Gemini 2.5 Flash ✔️
Gemini 2.5 Flash-Lite ✔️

모범 사례

  • 구체적인 URL 제공: 최상의 결과를 위해 모델이 분석할 콘텐츠의 직접 URL을 제공해요. 모델은 중첩 링크의 콘텐츠가 아닌, 제공한 URL의 콘텐츠만 가져와요.
  • 접근성 확인: 제공한 URL이 로그인이 필요하거나 페이월 뒤에 있는 페이지로 이어지지 않는지 확인하세요.
  • 완전한 URL 사용: 프로토콜을 포함한 전체 URL을 제공해요(예: google.com이 아닌 https://www.google.com).

한계

  • 함수 호출: 함수 호출과 함께하는 도구 사용(URL Context, Google Search 접지 등)은 현재 지원되지 않아요.
  • 요청 한도: 도구는 요청당 최대 20개 URL을 처리할 수 있어요.
  • URL 콘텐츠 크기: 단일 URL에서 가져오는 콘텐츠의 최대 크기는 34MB예요.
  • 공개 접근성: URL은 웹에서 공개적으로 접근 가능해야 해요. localhost 주소(예: localhost, 127.0.0.1), 사설 네트워크, 터널링 서비스(예: ngrok, pinggy)는 지원되지 않아요.

지원 및 미지원 콘텐츠 유형

도구는 다음 콘텐츠 유형의 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)

다음 콘텐츠 유형은 미지원이에요.

  • 페이월 콘텐츠
  • YouTube 비디오(video understanding에서 YouTube URL 처리 방법 학습)
  • Google docs나 스프레드시트 같은 Google Workspace 파일
  • 비디오·오디오 파일

다음 단계

더 알아보기 (Learn more)