The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
added gemini url context support (#11351)
Shaa301ef873e26
diff --git a/docs/my-website/docs/providers/gemini.md b/docs/my-website/docs/providers/gemini.mdindex 80f68679105..1803c3afac8 100644--- a/docs/my-website/docs/providers/gemini.md+++ b/docs/my-website/docs/providers/gemini.md@@ -643,6 +643,66 @@ curl -X POST 'http://0.0.0.0:4000/chat/completions' \</TabItem></Tabs>+### URL Context++<Tabs>+<TabItem value="sdk" label="SDK">++```python+from litellm import completion+import os++os.environ["GEMINI_API_KEY"] = ".."++# 👇 ADD URL CONTEXT+tools = [{"urlContext": {}}]++response = completion(+ model="gemini/gemini-2.0-flash",+ messages=[{"role": "user", "content": "Summarize this document: https://ai.google.dev/gemini-api/docs/models"}],+ tools=tools,+)++print(response)++# Access URL context metadata+url_context_metadata = response.model_extra['vertex_ai_url_context_metadata']+urlMetadata = url_context_metadata[0]['urlMetadata'][0]+print(f"Retrieved URL: {urlMetadata['retrievedUrl']}")+print(f"Retrieval Status: {urlMetadata['urlRetrievalStatus']}")+```++</TabItem>+<TabItem value="proxy" label="PROXY">++1. Setup config.yaml+```yaml+model_list:+ - model_name: gemini-2.0-flash+ litellm_params:+ model: gemini/gemini-2.0-flash+ api_key: os.environ/GEMINI_API_KEY+```++2. Start Proxy+```bash+$ litellm --config /path/to/config.yaml+```++3. Make Request!+```bash+curl -X POST 'http://0.0.0.0:4000/chat/completions' \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer <YOUR-LITELLM-KEY>" \+ -d '{+ "model": "gemini-2.0-flash",+ "messages": [{"role": "user", "content": "Summarize this document: https://ai.google.dev/gemini-api/docs/models"}],+ "tools": [{"urlContext": {}}]+ }'+```+</TabItem>+</Tabs>+### Google Search Retrievaldiff --git a/docs/my-website/docs/providers/vertex.md b/docs/my-website/docs/providers/vertex.mdindex dae68f4fc25..df9049675a0 100644--- a/docs/my-website/docs/providers/vertex.md+++ b/docs/my-website/docs/providers/vertex.md@@ -424,6 +424,71 @@ curl http://localhost:4000/v1/chat/completions \</TabItem></Tabs>+#### **Url Context**+Using the URL context tool, you can provide Gemini with URLs as additional context for your prompt. The model can then retrieve content from the URLs and use that content to inform and shape its response.++[**Relevant Docs**](https://ai.google.dev/gemini-api/docs/url-context)++See the grounding metadata with `response_obj._hidden_params["vertex_ai_url_context_metadata"]`++<Tabs>+<TabItem value="sdk" label="SDK">++```python showLineNumbers+from litellm import completion+import os++os.environ["GEMINI_API_KEY"] = ".."++# 👇 ADD URL CONTEXT+tools = [{"urlContext": {}}]++response = completion(+ model="gemini/gemini-2.0-flash",+ messages=[{"role": "user", "content": "Summarize this document: https://ai.google.dev/gemini-api/docs/models"}],+ tools=tools,+)++print(response)++# Access URL context metadata+url_context_metadata = response.model_extra['vertex_ai_url_context_metadata']+urlMetadata = url_context_metadata[0]['urlMetadata'][0]+print(f"Retrieved URL: {urlMetadata['retrievedUrl']}")+print(f"Retrieval Status: {urlMetadata['urlRetrievalStatus']}")+```++</TabItem>+<TabItem value="proxy" label="PROXY">++1. Setup config.yaml+```yaml+model_list:+ - model_name: gemini-2.0-flash+ litellm_params:+ model: gemini/gemini-2.0-flash+ api_key: os.environ/GEMINI_API_KEY+```++2. Start Proxy+```bash+$ litellm --config /path/to/config.yaml+```++3. Make Request!+```bash+curl -X POST 'http://0.0.0.0:4000/chat/completions' \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer <YOUR-LITELLM-KEY>" \+ -d '{+ "model": "gemini-2.0-flash",+ "messages": [{"role": "user", "content": "Summarize this document: https://ai.google.dev/gemini-api/docs/models"}],+ "tools": [{"urlContext": {}}]+ }'+```+</TabItem>+</Tabs>+#### **Enterprise Web Search**You can also use the `enterpriseWebSearch` tool for an [enterprise compliant search](https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise).diff --git a/litellm/__init__.py b/litellm/__init__.pyindex 38f332b41e7..922a0afcede 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -825,6 +825,7 @@ from .utils import (create_tokenizer,supports_function_calling,supports_web_search,+ supports_url_context,supports_response_schema,supports_parallel_function_calling,supports_vision,diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.pyindex f7a9f7cb840..b90dc98ccf7 100644--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py@@ -266,11 +266,12 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):"""return Tools(googleSearch={})- def _map_function(self, value: List[dict]) -> List[Tools]:+ def _map_function(self, value: List[dict]) -> List[Tools]: # noqa: PLR0915gtool_func_declarations = []googleSearch: Optional[dict] = NonegoogleSearchRetrieval: Optional[dict] = NoneenterpriseWebSearch: Optional[dict] = None+ urlContext: Optional[dict] = Nonecode_execution: Optional[dict] = None# remove 'additionalProperties' from toolsvalue = _remove_additional_properties(value)@@ -334,6 +335,8 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):googleSearchRetrieval = get_tool_value(tool, "googleSearchRetrieval")elif tool_name and tool_name == "enterpriseWebSearch":enterpriseWebSearch = get_tool_value(tool, "enterpriseWebSearch")+ elif tool_name and tool_name == "urlContext":+ urlContext = get_tool_value(tool, "urlContext")elif openai_function_object is not None:gtool_func_declaration = FunctionDeclaration(name=openai_function_object["name"],@@ -362,6 +365,8 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):_tools["enterpriseWebSearch"] = enterpriseWebSearchif code_execution is not None:_tools["code_execution"] = code_execution+ if urlContext is not None:+ _tools["url_context"] = urlContextreturn [_tools]def _map_response_schema(self, value: dict) -> dict:@@ -1016,6 +1021,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):)grounding_metadata: List[dict] = []+ url_context_metadata: List[dict] = []safety_ratings: List = []citation_metadata: List = []chat_completion_message: ChatCompletionResponseMessage = {"role": "assistant"}@@ -1036,6 +1042,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):if "citationMetadata" in candidate:citation_metadata.append(candidate["citationMetadata"])+ if "urlContextMetadata" in candidate:+ # Add URL context metadata to grounding metadata+ url_context_metadata.append(candidate["urlContextMetadata"])+if "parts" in candidate["content"]:(content,@@ -1090,7 +1100,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):model_response.choices.append(choice)- return grounding_metadata, safety_ratings, citation_metadata+ return grounding_metadata, url_context_metadata, safety_ratings, citation_metadatadef transform_response(self,@@ -1160,6 +1170,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):if _candidates:(grounding_metadata,+ url_context_metadata,safety_ratings,citation_metadata,) = self._process_candidates(@@ -1177,6 +1188,11 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):"vertex_ai_grounding_metadata"] = grounding_metadata+ setattr(model_response, "vertex_ai_url_context_metadata", url_context_metadata)+ model_response._hidden_params[+ "vertex_ai_url_context_metadata"+ ] = url_context_metadata+setattr(model_response, "vertex_ai_safety_results", safety_ratings)model_response._hidden_params["vertex_ai_safety_results"diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex d6564e63ece..fa716e3e12b 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -6474,7 +6474,8 @@"text"],"source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-preview",- "supports_web_search": true+ "supports_web_search": true,+ "supports_url_context": true},"gemini/gemini-2.5-flash-preview-04-17": {"max_tokens": 65535,@@ -6556,7 +6557,8 @@],"source": "https://ai.google.dev/gemini-api/docs/models#gemini-2.5-flash-preview","supports_parallel_function_calling": true,- "supports_web_search": true+ "supports_web_search": true,+ "supports_url_context": true},"gemini-2.5-flash-preview-04-17": {"max_tokens": 65535,@@ -6633,7 +6635,8 @@"supports_tool_choice": true,"source": "https://ai.google.dev/pricing#2_0flash","supports_parallel_function_calling": true,- "supports_web_search": true+ "supports_web_search": true,+ "supports_url_context": true},"gemini-2.0-flash-lite": {"max_input_tokens": 1048576,@@ -6966,7 +6969,8 @@],"supports_tool_choice": true,"source": "https://ai.google.dev/pricing#2_0flash",- "supports_web_search": true+ "supports_web_search": true,+ "supports_url_context": true},"gemini/gemini-2.0-flash-lite": {"max_input_tokens": 1048576,@@ -7107,7 +7111,8 @@"text"],"source": "https://ai.google.dev/gemini-api/docs/pricing#gemini-2.5-pro-preview",- "supports_web_search": true+ "supports_web_search": true,+ "supports_url_context": true},"gemini/gemini-2.5-pro-preview-03-25": {"max_tokens": 65535,diff --git a/litellm/router.py b/litellm/router.pyindex 8168bed4c8d..ae45212dccf 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -5235,6 +5235,12 @@ class Router:and model_info["supports_web_search"] is True # type: ignore):model_group_info.supports_web_search = True+ if (+ model_info.get("supports_url_context", None) is not None+ and model_info["supports_url_context"] is True # type: ignore+ ):+ model_group_info.supports_url_context = True+if (model_info.get("supports_reasoning", None) is not Noneand model_info["supports_reasoning"] is True # type: ignorediff --git a/litellm/types/llms/vertex_ai.py b/litellm/types/llms/vertex_ai.pyindex b63b9c7fe0c..35ad9a4851f 100644--- a/litellm/types/llms/vertex_ai.py+++ b/litellm/types/llms/vertex_ai.py@@ -211,6 +211,7 @@ class Tools(TypedDict, total=False):googleSearch: dictgoogleSearchRetrieval: dictenterpriseWebSearch: dict+ url_context: dictcode_execution: dictretrieval: Retrievaldiff --git a/litellm/types/router.py b/litellm/types/router.pyindex f5634671350..a8b94c96328 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -570,6 +570,7 @@ class ModelGroupInfo(BaseModel):supports_parallel_function_calling: bool = Field(default=False)supports_vision: bool = Field(default=False)supports_web_search: bool = Field(default=False)+ supports_url_context: bool = Field(default=False)supports_reasoning: bool = Field(default=False)supports_function_calling: bool = Field(default=False)supported_openai_params: Optional[List[str]] = Field(default=[])diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex e94dbc225c6..e0e8f3f742f 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -122,6 +122,7 @@ class ProviderSpecificModelInfo(TypedDict, total=False):supports_parallel_function_calling: Optional[bool]supports_web_search: Optional[bool]supports_reasoning: Optional[bool]+ supports_url_context: Optional[bool]class SearchContextCostPerQuery(TypedDict, total=False):diff --git a/litellm/utils.py b/litellm/utils.pyindex 97d0b104f57..c2fb7644bda 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -1776,6 +1776,27 @@ def supports_web_search(model: str, custom_llm_provider: Optional[str] = None) -)+def supports_url_context(model: str, custom_llm_provider: Optional[str] = None) -> bool:+ """+ Check if the given model supports URL context and return a boolean value.++ Parameters:+ model (str): The model name to be checked.+ custom_llm_provider (str): The provider to be checked.++ Returns:+ bool: True if the model supports URL context, False otherwise.++ Raises:+ Exception: If the given model is not found in model_prices_and_context_window.json.+ """+ return _supports_factory(+ model=model,+ custom_llm_provider=custom_llm_provider,+ key="supports_url_context",+ )++def supports_native_streaming(model: str, custom_llm_provider: Optional[str]) -> bool:"""Check if the given model supports native streaming and return a boolean value.@@ -4600,6 +4621,7 @@ def _get_model_info_helper( # noqa: PLR0915"supports_native_streaming", None),supports_web_search=_model_info.get("supports_web_search", None),+ supports_url_context=_model_info.get("supports_url_context", None),supports_reasoning=_model_info.get("supports_reasoning", None),supports_computer_use=_model_info.get("supports_computer_use", None),search_context_cost_per_query=_model_info.get(@@ -4674,6 +4696,7 @@ def get_model_info(model: str, custom_llm_provider: Optional[str] = None) -> Modsupports_audio_output: Optional[bool]supports_pdf_input: Optional[bool]supports_web_search: Optional[bool]+ supports_url_context: Optional[bool]supports_reasoning: Optional[bool]Raises:Exception: If the model is not mapped yet.diff --git a/tests/llm_translation/base_llm_unit_tests.py b/tests/llm_translation/base_llm_unit_tests.pyindex 5184a025a2d..4d3dbee28ff 100644--- a/tests/llm_translation/base_llm_unit_tests.py+++ b/tests/llm_translation/base_llm_unit_tests.py@@ -209,6 +209,27 @@ class BaseLLMChatTest(ABC):print(f"response={response}")+ def test_url_context(self):+ from litellm.utils import supports_url_context+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")++ litellm._turn_on_debug()++ base_completion_call_args = self.get_base_completion_call_args()++ if not supports_url_context(base_completion_call_args["model"], None):+ pytest.skip("Model does not support url context")++ response = self.completion_function(+ **base_completion_call_args,+ messages=[{"role": "user", "content": "Summarize the content of this URL: https://en.wikipedia.org/wiki/Artificial_intelligence"}],+ tools=[{"urlContext": {}}],+ )++ assert response is not None+ print(f"response={response}")+@pytest.mark.parametrize("sync_mode", [True, False])@pytest.mark.asyncioasync def test_pdf_handling(self, pdf_messages, sync_mode):diff --git a/tests/llm_translation/test_gemini.py b/tests/llm_translation/test_gemini.pyindex 8d2de1ea04e..e0a82582e7b 100644--- a/tests/llm_translation/test_gemini.py+++ b/tests/llm_translation/test_gemini.py@@ -3,6 +3,8 @@ import sysimport pytest+from litellm.utils import supports_url_context+sys.path.insert(0, os.path.abspath("../..")) # Adds the parent directory to the system paths@@ -30,6 +32,27 @@ class TestGoogleAIStudioGemini(BaseLLMChatTest):result = convert_to_gemini_tool_call_invoke(tool_call_no_arguments)print(result)+ def test_url_context(self):+ from litellm.utils import supports_url_context+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")++ litellm._turn_on_debug()++ base_completion_call_args = self.get_base_completion_call_args()++ if not supports_url_context(base_completion_call_args["model"], None):+ pytest.skip("Model does not support url context")++ response = self.completion_function(+ **base_completion_call_args,+ messages=[{"role": "user", "content": "Summarize the content of this URL: https://en.wikipedia.org/wiki/Artificial_intelligence"}],+ tools=[{"urlContext": {}}],+ )++ assert response is not None+ assert response.model_extra['vertex_ai_url_context_metadata'] is not None, "URL context metadata should be present"+ print(f"response={response}")def test_gemini_context_caching_separate_messages():messages = [@@ -144,4 +167,29 @@ def test_gemini_finish_reason():response = completion(model="gemini/gemini-1.5-pro", messages=[{"role": "user", "content": "give me 3 random words"}], max_tokens=2)print(response)assert response.choices[0].finish_reason is not None- assert response.choices[0].finish_reason == "length"\ No newline at end of file+ assert response.choices[0].finish_reason == "length"+++def test_gemini_url_context():+ from litellm import completion+ litellm._turn_on_debug()++ url = "https://ai.google.dev/gemini-api/docs/models"+ prompt = f"""+ Summarize this document:+ {url}+ """+ response = completion(+ model="gemini/gemini-2.0-flash",+ messages=[{"role": "user", "content": prompt}],+ tools=[{"urlContext": {}}],+ )+ print(response)+ message = response.choices[0].message.content+ assert message is not None+ url_context_metadata = response.model_extra['vertex_ai_url_context_metadata']+ assert url_context_metadata is not None+ urlMetadata = url_context_metadata[0]['urlMetadata'][0]+ assert urlMetadata['retrievedUrl'] == url+ assert urlMetadata['urlRetrievalStatus'] == 'URL_RETRIEVAL_STATUS_SUCCESS'+