|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from typing import TYPE_CHECKING |
| 18 | + |
| 19 | +from google.genai import types |
| 20 | +from typing_extensions import override |
| 21 | + |
| 22 | +from .base_tool import BaseTool |
| 23 | +from .tool_context import ToolContext |
| 24 | + |
| 25 | +if TYPE_CHECKING: |
| 26 | + from ..models import LlmRequest |
| 27 | + |
| 28 | + |
| 29 | +class UrlContextTool(BaseTool): |
| 30 | + """A built-in tool that is automatically invoked by Gemini 2 models to retrieve content from the URLs and use that content to inform and shape its response. |
| 31 | +
|
| 32 | + This tool operates internally within the model and does not require or perform |
| 33 | + local code execution. |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__(self): |
| 37 | + # Name and description are not used because this is a model built-in tool. |
| 38 | + super().__init__(name='url_context', description='url_context') |
| 39 | + |
| 40 | + @override |
| 41 | + async def process_llm_request( |
| 42 | + self, |
| 43 | + *, |
| 44 | + tool_context: ToolContext, |
| 45 | + llm_request: LlmRequest, |
| 46 | + ) -> None: |
| 47 | + llm_request.config = llm_request.config or types.GenerateContentConfig() |
| 48 | + llm_request.config.tools = llm_request.config.tools or [] |
| 49 | + if llm_request.model and 'gemini-1' in llm_request.model: |
| 50 | + raise ValueError('Url context tool can not be used in Gemini 1.x.') |
| 51 | + elif llm_request.model and 'gemini-2' in llm_request.model: |
| 52 | + llm_request.config.tools.append( |
| 53 | + types.Tool(url_context=types.UrlContext()) |
| 54 | + ) |
| 55 | + else: |
| 56 | + raise ValueError( |
| 57 | + f'Url context tool is not supported for model {llm_request.model}' |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +url_context = UrlContextTool() |
0 commit comments