URL 컨텍스트

URL 컨텍스트 도구를 사용하면 URL 형식으로 모델에 추가 컨텍스트를 제공할 수 있습니다. 모델은 이러한 URL의 콘텐츠에 액세스하여 대답을 알리고 개선할 수 있습니다.

URL 컨텍스트에는 다음과 같은 이점이 있습니다.

  • 데이터 추출: 기사 또는 여러 URL에서 가격, 이름, 주요 결과와 같은 구체적인 정보를 제공합니다.

  • 정보 비교: 여러 보고서, 기사 또는 PDF를 분석하여 차이점을 파악하고 추세를 추적합니다.

  • 콘텐츠 합성 및 생성: 여러 소스 URL의 정보를 결합하여 정확한 요약, 블로그 게시물, 보고서 또는 테스트 질문을 생성합니다.

  • 코드 및 기술 콘텐츠 분석: GitHub 저장소 또는 기술 문서의 URL을 제공하여 코드를 설명하거나, 설정 안내를 생성하거나, 질문에 답변합니다.

URL 컨텍스트 도구를 사용할 때는 권장사항제한사항을 검토해야 합니다.

지원되는 모델

  • 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

지원 언어

Gemini 모델의 경우 지원되는 언어를 참고하세요.

URL 컨텍스트 도구 사용

URL 컨텍스트 도구는 다음 두 가지 주요 방법으로 사용할 수 있습니다.

URL 컨텍스트 도구만

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

GenerativeModel 인스턴스를 만들 때 UrlContext을 도구로 제공합니다. 그런 다음 프롬프트에 모델이 액세스하고 분석할 특정 URL을 직접 제공합니다.

다음 예에서는 서로 다른 웹사이트의 두 레시피를 비교하는 방법을 보여줍니다.

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

사용 사례 및 앱에 적합한 모델과 선택적으로 모델 위치를 선택하는 방법을 알아보세요.

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

URL 컨텍스트와 Google 검색으로 그라운딩을 모두 사용 설정할 수 있습니다. 이 구성을 사용하면 특정 URL을 포함하거나 포함하지 않고 프롬프트를 작성할 수 있습니다.

Google 검색으로 그라운딩도 사용 설정된 경우 모델은 먼저 Google 검색을 사용하여 관련 정보를 찾은 다음 URL 컨텍스트 도구를 사용하여 정보에 대해 더 심도 있게 이해할 수 있도록 검색 결과 콘텐츠를 읽습니다. 이 접근 방식은 광범위한 검색과 특정 페이지의 심층 분석이 모두 필요한 프롬프트에 유용합니다.

다음은 몇 가지 사용 사례입니다.

  • 생성된 대답의 일부에 도움이 되도록 프롬프트에 URL을 제공합니다. 하지만 적절한 대답을 생성하려면 모델에 다른 주제에 관한 정보가 더 필요하므로 Google 검색을 사용한 그라운딩 도구를 사용합니다.

    프롬프트 예시:
    Give me a three day event schedule based on YOUR_URL. Also what do I need to pack according to the weather?

  • 프롬프트에 URL을 전혀 제공하지 않습니다. 따라서 적절한 대답을 생성하기 위해 모델은 Google 검색으로 그라운딩 도구를 사용하여 관련 URL을 찾은 다음 URL 컨텍스트 도구를 사용하여 콘텐츠를 분석합니다.

    프롬프트 예시:
    Recommend 3 beginner-level books to learn about the latest YOUR_SUBJECT.

다음 예시에서는 URL 컨텍스트와 Google 검색을 통한 그라운딩이라는 두 도구를 모두 사용 설정하고 사용하는 방법을 보여줍니다.


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

사용 사례 및 앱에 적합한 모델과 선택적으로 모델 위치를 선택하는 방법을 알아보세요.

URL 컨텍스트 도구의 작동 방식

URL 컨텍스트 도구는 2단계 검색 프로세스를 사용하여 속도, 비용, 최신 데이터 액세스의 균형을 맞춥니다.

1단계: 특정 URL을 제공하면 도구에서 먼저 내부 색인 캐시에서 콘텐츠를 가져오려고 시도합니다. 이는 고도로 최적화된 캐시 역할을 합니다.

2단계: URL이 색인에서 제공되지 않는 경우 (예: 페이지가 최근에 만들어진 경우) 도구에서 자동으로 실시간 가져오기로 대체됩니다. 이렇게 하면 URL에 직접 액세스하여 콘텐츠를 실시간으로 가져옵니다.

권장사항

  • 구체적인 URL 제공: 최상의 결과를 얻으려면 모델이 분석할 콘텐츠의 직접 URL을 제공하세요. 모델은 중첩된 링크의 콘텐츠가 아닌 사용자가 제공한 URL의 콘텐츠만 가져옵니다.

  • 접근성 확인: 제공한 URL이 로그인해야 하거나 페이월 뒤에 있는 페이지로 연결되지 않는지 확인합니다.

  • 전체 URL 사용: 프로토콜을 포함한 전체 URL을 제공합니다(예: example.com 대신 https://www.example.com).

응답 이해

모델 대답은 URL에서 검색한 콘텐츠를 기반으로 합니다.

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

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

안전 확인

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

제한사항

URL 컨텍스트 도구에는 다음과 같은 제한사항이 있습니다.

  • 함수 호출과 결합: URL 컨텍스트 도구는 함수 호출도 사용하는 요청에서 사용할 수 없습니다.

  • 요청당 URL 한도: 요청당 최대 URL 수는 20개입니다.

  • URL 콘텐츠 크기 제한: 단일 URL에서 가져온 콘텐츠의 최대 크기는 34MB입니다.

  • 최신성: 이 도구는 웹페이지의 실시간 버전을 가져오지 않으므로 최신 정보가 아니거나 오래된 정보가 있을 수 있습니다.

  • URL 공개 액세스 가능 여부: 제공된 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 동영상 (대신 동영상 분석 참고)

  • 동영상 및 오디오 파일 (대신 동영상 분석 또는 오디오 분석 참고)

  • Google Workspace 파일(예: Google Docs 또는 스프레드시트)

  • (Vertex AI Gemini API 사용 시) Cloud Storage URL
    이러한 유형의 URL은 액세스 방식과 관계없이 Gemini Developer API에서 지원되지 않습니다.

  • 공개적으로 액세스할 수 없는 콘텐츠 다음은 지원되지 않습니다. 페이월 콘텐츠, 사용자 로그인이 필요한 콘텐츠, 비공개 네트워크, localhost 주소 (예: localhost 또는 127.0.0.1), 터널링 서비스(예: ngrok 또는 pinggy)

가격 책정 및 토큰 수 계산 도구

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
  }

비율 제한 및 가격은 사용된 모델을 기반으로 합니다. 선택한 Gemini API 제공업체 문서(Gemini Developer API, Vertex AI Gemini API)에서 URL 컨텍스트 도구의 가격을 자세히 알아보세요.