Skip to content

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]

feat(gemini): forward web search tools in image generation (#30119)

Sameer Kankute87cf67ec3068
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py
index 93049adf75a..d75850984a9 100644
--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py
+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py
@@ -949,6 +949,43 @@ def calculate_image_response_cost_from_usage(
return prompt_cost + completion_cost
+def calculate_image_response_web_search_cost(
+ image_response: ImageResponse,
+ custom_llm_provider: str,
+ model_info: ModelInfo,
+) -> float:
+ """
+ Cost of Google Search grounding performed during image generation.
+
+ The grounding request count is carried on the image usage object by the
+ provider transformers; it is billed with the same per-request accounting
+ used for chat completions.
+ """
+ usage = image_response.usage
+ if usage is None:
+ return 0.0
+
+ web_search_requests = getattr(usage, "web_search_requests", None)
+ if not web_search_requests:
+ return 0.0
+
+ from litellm.llms import get_cost_for_web_search_request
+
+ synthetic_usage = Usage(
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ web_search_requests=web_search_requests
+ )
+ )
+ return (
+ get_cost_for_web_search_request(
+ custom_llm_provider=custom_llm_provider,
+ usage=synthetic_usage,
+ model_info=model_info,
+ )
+ or 0.0
+ )
+
+
class CostCalculatorUtils:
@staticmethod
def _call_type_has_image_response(call_type: str) -> bool:
diff --git a/litellm/llms/gemini/common_utils.py b/litellm/llms/gemini/common_utils.py
index 42a807983b9..4cca2e2b850 100644
--- a/litellm/llms/gemini/common_utils.py
+++ b/litellm/llms/gemini/common_utils.py
@@ -174,12 +174,110 @@ def map_openai_image_params_to_gemini(
mapped_params["imageConfig"] = image_config_param
for key, value in filtered_params.items():
- if key not in ("n", "size", "imageConfig") and key not in optional_params:
+ if (
+ key not in ("n", "size", "imageConfig", "tools", "web_search_options")
+ and key not in optional_params
+ ):
mapped_params[key] = value
return mapped_params
+def _dedupe_gemini_search_tools(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
+ VertexGeminiConfig,
+ )
+
+ search_tool_keys = VertexGeminiConfig._search_tool_keys()
+ seen_search_keys: set[str] = set()
+ deduped_tools: List[Dict[str, Any]] = []
+
+ for tool in tools:
+ if not isinstance(tool, dict):
+ deduped_tools.append(tool)
+ continue
+
+ search_key = next((key for key in search_tool_keys if key in tool), None)
+ if search_key is None:
+ deduped_tools.append(tool)
+ continue
+
+ if search_key in seen_search_keys:
+ continue
+
+ seen_search_keys.add(search_key)
+ deduped_tools.append(tool)
+
+ return deduped_tools
+
+
+def _has_gemini_search_tool(tools: List[Any]) -> bool:
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
+ VertexGeminiConfig,
+ )
+
+ search_tool_keys = VertexGeminiConfig._search_tool_keys()
+ return any(
+ isinstance(tool, dict) and any(key in tool for key in search_tool_keys)
+ for tool in tools
+ )
+
+
+def map_gemini_image_tools_params(
+ non_default_params: Dict[str, Any],
+ mapped_params: Dict[str, Any],
+) -> Dict[str, Any]:
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
+ VertexGeminiConfig,
+ )
+
+ gemini_config = VertexGeminiConfig()
+ result = dict(mapped_params)
+ result.pop("web_search_options", None)
+
+ tools_value = non_default_params.get("tools")
+ if isinstance(tools_value, list) and tools_value:
+ mapped_tools = gemini_config._map_function(
+ value=tools_value, optional_params=result
+ )
+ result = gemini_config._add_tools_to_optional_params(result, mapped_tools)
+
+ web_search_options = non_default_params.get("web_search_options")
+ existing_tools = result.get("tools")
+ if isinstance(web_search_options, dict) and not (
+ isinstance(existing_tools, list) and _has_gemini_search_tool(existing_tools)
+ ):
+ search_tool = gemini_config._map_web_search_options(web_search_options)
+ result = gemini_config._add_tools_to_optional_params(result, [search_tool])
+
+ gemini_config._drop_search_tools_mixed_with_functions(result)
+
+ if isinstance(result.get("tools"), list):
+ result["tools"] = _dedupe_gemini_search_tools(result["tools"])
+
+ return result
+
+
+def get_gemini_image_web_search_requests(
+ response_data: Dict[str, Any],
+) -> Optional[int]:
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
+ VertexGeminiConfig,
+ )
+
+ grounding_metadata: List[Dict[str, Any]] = []
+ for candidate in response_data.get("candidates", []):
+ if not isinstance(candidate, dict):
+ continue
+ candidate_grounding = candidate.get("groundingMetadata")
+ if isinstance(candidate_grounding, list):
+ grounding_metadata.extend(candidate_grounding)
+ elif isinstance(candidate_grounding, dict):
+ grounding_metadata.append(candidate_grounding)
+
+ return VertexGeminiConfig._calculate_web_search_requests(grounding_metadata)
+
+
def get_gemini_image_generation_config(
model: str,
optional_params: Dict[str, Any],
diff --git a/litellm/llms/gemini/image_generation/cost_calculator.py b/litellm/llms/gemini/image_generation/cost_calculator.py
index 3c8e69374af..380e2c21e9e 100644
--- a/litellm/llms/gemini/image_generation/cost_calculator.py
+++ b/litellm/llms/gemini/image_generation/cost_calculator.py
@@ -7,6 +7,7 @@ from typing import Any
import litellm
from litellm.litellm_core_utils.llm_cost_calc.utils import (
calculate_image_response_cost_from_usage,
+ calculate_image_response_web_search_cost,
)
from litellm.types.utils import ImageResponse
@@ -23,22 +24,25 @@ def cost_calculator(
custom_llm_provider="gemini",
)
- if isinstance(image_response, ImageResponse):
- token_based_cost = calculate_image_response_cost_from_usage(
- model=model,
- image_response=image_response,
- custom_llm_provider="gemini",
- )
- if token_based_cost is not None:
- return token_based_cost
-
- output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0
- num_images: int = 0
- if isinstance(image_response, ImageResponse):
- if image_response.data:
- num_images = len(image_response.data)
- return output_cost_per_image * num_images
- else:
+ if not isinstance(image_response, ImageResponse):
raise ValueError(
f"image_response must be of type ImageResponse got type={type(image_response)}"
)
+
+ web_search_cost = calculate_image_response_web_search_cost(
+ image_response=image_response,
+ custom_llm_provider="gemini",
+ model_info=_model_info,
+ )
+
+ token_based_cost = calculate_image_response_cost_from_usage(
+ model=model,
+ image_response=image_response,
+ custom_llm_provider="gemini",
+ )
+ if token_based_cost is not None:
+ return token_based_cost + web_search_cost
+
+ output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0
+ num_images: int = len(image_response.data) if image_response.data else 0
+ return output_cost_per_image * num_images + web_search_cost
diff --git a/litellm/llms/gemini/image_generation/transformation.py b/litellm/llms/gemini/image_generation/transformation.py
index e6770a76bcb..ebfb0d68830 100644
--- a/litellm/llms/gemini/image_generation/transformation.py
+++ b/litellm/llms/gemini/image_generation/transformation.py
@@ -7,7 +7,9 @@ from litellm.llms.base_llm.image_generation.transformation import (
)
from litellm.llms.gemini.common_utils import (
get_gemini_image_generation_config,
+ get_gemini_image_web_search_requests,
is_gemini_image_model,
+ map_gemini_image_tools_params,
map_openai_image_params_to_gemini,
)
from litellm.llms.gemini.image_usage_transformation import (
@@ -41,7 +43,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig):
"""
supported_params = ["n", "size"]
if is_gemini_image_model(model):
- supported_params.append("imageConfig")
+ supported_params.extend(["imageConfig", "tools", "web_search_options"])
return supported_params # type: ignore[return-value]
def map_openai_params(
@@ -51,12 +53,17 @@ class GoogleImageGenConfig(BaseImageGenerationConfig):
model: str,
drop_params: bool,
) -> dict:
- return map_openai_image_params_to_gemini(
+ mapped_params = map_openai_image_params_to_gemini(
params=non_default_params,
model=model,
supported_params=self.get_supported_openai_params(model),
optional_params=optional_params,
)
+ if is_gemini_image_model(model):
+ mapped_params = map_gemini_image_tools_params(
+ non_default_params, mapped_params
+ )
+ return mapped_params
def get_complete_url(
self,
@@ -140,6 +147,10 @@ class GoogleImageGenConfig(BaseImageGenerationConfig):
optional_params=optional_params,
),
}
+ if tools := optional_params.get("tools"):
+ request_body["tools"] = tools
+ if tool_config := optional_params.get("toolConfig"):
+ request_body["toolConfig"] = tool_config
return request_body
else:
# For other Imagen models, use the original Imagen format
@@ -217,6 +228,11 @@ class GoogleImageGenConfig(BaseImageGenerationConfig):
model_response.usage = transform_gemini_image_usage(
response_data["usageMetadata"]
)
+ web_search_requests = get_gemini_image_web_search_requests(response_data)
+ if web_search_requests and model_response.usage is not None:
+ setattr(
+ model_response.usage, "web_search_requests", web_search_requests
+ )
else:
# Original Imagen format - predictions with generated images
predictions = response_data.get("predictions", [])
diff --git a/litellm/llms/vertex_ai/image_generation/cost_calculator.py b/litellm/llms/vertex_ai/image_generation/cost_calculator.py
index 012de5498cb..5c04ebf79ee 100644
--- a/litellm/llms/vertex_ai/image_generation/cost_calculator.py
+++ b/litellm/llms/vertex_ai/image_generation/cost_calculator.py
@@ -5,6 +5,7 @@ Vertex AI Image Generation Cost Calculator
import litellm
from litellm.litellm_core_utils.llm_cost_calc.utils import (
calculate_image_response_cost_from_usage,
+ calculate_image_response_web_search_cost,
)
from litellm.types.utils import ImageResponse
@@ -21,16 +22,20 @@ def cost_calculator(
custom_llm_provider="vertex_ai",
)
+ web_search_cost = calculate_image_response_web_search_cost(
+ image_response=image_response,
+ custom_llm_provider="vertex_ai",
+ model_info=_model_info,
+ )
+
token_based_cost = calculate_image_response_cost_from_usage(
model=model,
image_response=image_response,
custom_llm_provider="vertex_ai",
)
if token_based_cost is not None:
- return token_based_cost
+ return token_based_cost + web_search_cost
output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0
- num_images: int = 0
- if image_response.data:
- num_images = len(image_response.data)
- return output_cost_per_image * num_images
+ num_images: int = len(image_response.data) if image_response.data else 0
+ return output_cost_per_image * num_images + web_search_cost
diff --git a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py
index f4bda8d1bed..103c7b2a28a 100644
--- a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py
+++ b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py
@@ -7,6 +7,10 @@ import litellm
from litellm.llms.base_llm.image_generation.transformation import (
BaseImageGenerationConfig,
)
+from litellm.llms.gemini.common_utils import (
+ get_gemini_image_web_search_requests,
+ map_gemini_image_tools_params,
+)
from litellm.llms.vertex_ai.common_utils import get_vertex_base_url
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexLLM
from litellm.secret_managers.main import get_secret_str
@@ -52,6 +56,8 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM):
"aspect_ratio",
"imageSize",
"image_size",
+ "tools",
+ "web_search_options",
]
def map_openai_params(
@@ -77,9 +83,10 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM):
mapped_params["aspectRatio"] = v
elif k in ("imageSize", "image_size"):
mapped_params["imageSize"] = v
- else:
+ elif k not in ("tools", "web_search_options"):
mapped_params[k] = v
+ mapped_params = map_gemini_image_tools_params(non_default_params, mapped_params)
return mapped_params
def _map_size_to_aspect_ratio(self, size: str) -> str:
@@ -247,6 +254,11 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM):
"generationConfig": generation_config,
}
+ if tools := optional_params.get("tools"):
+ request_body["tools"] = tools
+ if tool_config := optional_params.get("toolConfig"):
+ request_body["toolConfig"] = tool_config
+
return request_body
def _transform_image_usage(self, usage: dict) -> ImageUsage:
@@ -324,4 +336,8 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM):
if usage_metadata := response_data.get("usageMetadata", None):
model_response.usage = self._transform_image_usage(usage_metadata)
+ web_search_requests = get_gemini_image_web_search_requests(response_data)
+ if web_search_requests and model_response.usage is not None:
+ setattr(model_response.usage, "web_search_requests", web_search_requests)
+
return model_response
diff --git a/litellm/utils.py b/litellm/utils.py
index a0b66234a70..46d48279198 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -3260,6 +3260,8 @@ def get_optional_params_image_gen(
"style": None,
"user": None,
"imageConfig": None,
+ "tools": None,
+ "web_search_options": None,
}
non_default_params = _get_non_default_params(
diff --git a/tests/test_litellm/llms/gemini/test_cost_calculator.py b/tests/test_litellm/llms/gemini/test_cost_calculator.py
index 6d51bcd2c88..6917092966b 100644
--- a/tests/test_litellm/llms/gemini/test_cost_calculator.py
+++ b/tests/test_litellm/llms/gemini/test_cost_calculator.py
@@ -247,3 +247,57 @@ def test_gemini_image_edit_cost_falls_back_to_flat_image_pricing():
)
assert cost == len(image_response.data or []) * model_info["output_cost_per_image"]
+
+
+def _image_response_with_web_search(web_search_requests):
+ usage = ImageUsage(
+ input_tokens=20,
+ input_tokens_details=ImageUsageInputTokensDetails(
+ text_tokens=20,
+ image_tokens=0,
+ ),
+ output_tokens=1120,
+ total_tokens=1140,
+ )
+ if web_search_requests is not None:
+ usage.web_search_requests = web_search_requests
+ return ImageResponse(data=[ImageObject(b64_json="img1")], usage=usage)
+
+
+def test_gemini_image_generation_cost_adds_web_search_grounding():
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+ model = "gemini/gemini-3-pro-image-preview"
+ model_info = litellm.get_model_info(model=model, custom_llm_provider="gemini")
+
+ grounded = gemini_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(2),
+ )
+ ungrounded = gemini_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(None),
+ )
+
+ expected_web_search_cost = cost_per_web_search_request(
+ usage=_make_usage(2), model_info=model_info
+ )
+ assert expected_web_search_cost > 0
+ assert round(grounded - ungrounded, 10) == round(expected_web_search_cost, 10)
+
+
+def test_gemini_image_generation_cost_no_web_search_when_absent():
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+ model = "gemini/gemini-3-pro-image-preview"
+
+ cost_zero = gemini_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(0),
+ )
+ cost_none = gemini_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(None),
+ )
+
+ assert cost_zero == cost_none
diff --git a/tests/test_litellm/llms/gemini/test_gemini_image_generation_transformation.py b/tests/test_litellm/llms/gemini/test_gemini_image_generation_transformation.py
index 4610d1b99bf..d9509856759 100644
--- a/tests/test_litellm/llms/gemini/test_gemini_image_generation_transformation.py
+++ b/tests/test_litellm/llms/gemini/test_gemini_image_generation_transformation.py
@@ -196,6 +196,100 @@ def test_gemini_image_generation_usage_includes_chat_token_details():
assert logging_usage["completion_tokens_details"]["image_tokens"] == 1120
+def test_gemini_image_generation_web_search_options_maps_to_google_search_tool():
+ config = GoogleImageGenConfig()
+
+ mapped = config.map_openai_params(
+ non_default_params={"web_search_options": {}},
+ optional_params={},
+ model="gemini-3.1-flash-image-preview",
+ drop_params=False,
+ )
+
+ assert "tools" in mapped
+ assert mapped["tools"] == [{"googleSearch": {}}]
+
+ request = config.transform_image_generation_request(
+ model="gemini-3.1-flash-image-preview",
+ prompt="Generate an image of the latest iPhone",
+ optional_params=mapped,
+ litellm_params={},
+ headers={},
+ )
+
+ assert request["tools"] == [{"googleSearch": {}}]
+
+
+def test_gemini_image_generation_openai_web_search_tool_maps_to_google_search():
+ config = GoogleImageGenConfig()
+
+ mapped = config.map_openai_params(
+ non_default_params={"tools": [{"type": "web_search"}]},
+ optional_params={},
+ model="gemini-3.1-flash-image-preview",
+ drop_params=False,
+ )
+
+ assert mapped["tools"] == [{"googleSearch": {}}]
+
+ request = config.transform_image_generation_request(
+ model="gemini-3.1-flash-image-preview",
+ prompt="Generate an image of the latest iPhone",
+ optional_params=mapped,
+ litellm_params={},
+ headers={},
+ )
+
+ assert request["tools"] == [{"googleSearch": {}}]
+
+
+def test_gemini_image_generation_dedupes_search_tools_from_tools_and_web_search_options():
+ config = GoogleImageGenConfig()
+
+ mapped = config.map_openai_params(
+ non_default_params={
+ "tools": [{"type": "web_search"}],
+ "web_search_options": {},
+ },
+ optional_params={},
+ model="gemini-3.1-flash-image-preview",
+ drop_params=False,
+ )
+
+ assert mapped["tools"] == [{"googleSearch": {}}]
+
+
+def test_gemini_image_generation_preserves_tool_config_side_effect():
+ config = GoogleImageGenConfig()
+
+ mapped = config.map_openai_params(
+ non_default_params={
+ "tools": [{"googleMaps": {"latitude": 37.7, "longitude": -122.4}}]
+ },
+ optional_params={},
+ model="gemini-3.1-flash-image-preview",
+ drop_params=False,
+ )
+
+ assert mapped["tools"] == [{"googleMaps": {}}]
+ assert mapped["toolConfig"] == {
+ "retrievalConfig": {"latLng": {"latitude": 37.7, "longitude": -122.4}}
+ }
+
+ request = config.transform_image_generation_request(
+ model="gemini-3.1-flash-image-preview",
+ prompt="Generate an image of a coffee shop nearby",
+ optional_params=mapped,
+ litellm_params={},
+ headers={},
+ )
+
+ assert request["tools"] == [{"googleMaps": {}}]
+ assert request["toolConfig"] == {
+ "retrievalConfig": {"latLng": {"latitude": 37.7, "longitude": -122.4}}
+ }
+
+
def test_gemini_image_generation_usage_without_output_details_treats_output_as_image():
config = GoogleImageGenConfig()
raw_response = httpx.Response(
@@ -238,3 +332,90 @@ def test_gemini_image_generation_usage_without_output_details_treats_output_as_i
usage = result.model_dump()["usage"]
assert usage["completion_tokens_details"]["text_tokens"] == 0
assert usage["completion_tokens_details"]["image_tokens"] == 1716
+
+
+def test_gemini_image_generation_response_tracks_web_search_requests():
+ config = GoogleImageGenConfig()
+ raw_response = httpx.Response(
+ status_code=200,
+ json={
+ "candidates": [
+ {
+ "content": {
+ "parts": [
+ {
+ "inlineData": {
+ "mimeType": "image/png",
+ "data": "fake-image",
+ }
+ }
+ ]
+ },
+ "groundingMetadata": {
+ "webSearchQueries": ["latest iphone", "iphone colors"]
+ },
+ }
+ ],
+ "usageMetadata": {
+ "promptTokenCount": 35,
+ "candidatesTokenCount": 1716,
+ "totalTokenCount": 1751,
+ "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 35}],
+ },
+ },
+ )
+
+ result = config.transform_image_generation_response(
+ model="gemini-3.1-flash-image-preview",
+ raw_response=raw_response,
+ model_response=ImageResponse(data=[]),
+ logging_obj=None,
+ request_data={},
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result.usage.web_search_requests == 2
+
+
+def test_gemini_image_generation_response_without_grounding_has_no_web_search_requests():
+ config = GoogleImageGenConfig()
+ raw_response = httpx.Response(
+ status_code=200,
+ json={
+ "candidates": [
+ {
+ "content": {
+ "parts": [
+ {
+ "inlineData": {
+ "mimeType": "image/png",
+ "data": "fake-image",
+ }
+ }
+ ]
+ }
+ }
+ ],
+ "usageMetadata": {
+ "promptTokenCount": 35,
+ "candidatesTokenCount": 1716,
+ "totalTokenCount": 1751,
+ "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 35}],
+ },
+ },
+ )
+
+ result = config.transform_image_generation_response(
+ model="gemini-3.1-flash-image-preview",
+ raw_response=raw_response,
+ model_response=ImageResponse(data=[]),
+ logging_obj=None,
+ request_data={},
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert getattr(result.usage, "web_search_requests", None) is None
diff --git a/tests/test_litellm/llms/vertex_ai/image_generation/test_vertex_ai_image_generation_cost_calculator.py b/tests/test_litellm/llms/vertex_ai/image_generation/test_vertex_ai_image_generation_cost_calculator.py
new file mode 100644
index 00000000000..cd866187166
--- /dev/null
+++ b/tests/test_litellm/llms/vertex_ai/image_generation/test_vertex_ai_image_generation_cost_calculator.py
@@ -0,0 +1,72 @@
+import os
+
+import litellm
+from litellm.llms.vertex_ai.gemini.cost_calculator import cost_per_web_search_request
+from litellm.llms.vertex_ai.image_generation.cost_calculator import (
+ cost_calculator as vertex_image_generation_cost_calculator,
+)
+from litellm.types.utils import (
+ ImageObject,
+ ImageResponse,
+ ImageUsage,
+ ImageUsageInputTokensDetails,
+ PromptTokensDetailsWrapper,
+ Usage,
+)
+
+
+def _image_response_with_web_search(web_search_requests):
+ usage = ImageUsage(
+ input_tokens=20,
+ input_tokens_details=ImageUsageInputTokensDetails(
+ text_tokens=20,
+ image_tokens=0,
+ ),
+ output_tokens=1120,
+ total_tokens=1140,
+ )
+ if web_search_requests is not None:
+ usage.web_search_requests = web_search_requests
+ return ImageResponse(data=[ImageObject(b64_json="img1")], usage=usage)
+
+
+def test_vertex_image_generation_cost_adds_web_search_grounding():
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+ model = "gemini-3-pro-image-preview"
+ model_info = litellm.get_model_info(model=model, custom_llm_provider="vertex_ai")
+
+ grounded = vertex_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(3),
+ )
+ ungrounded = vertex_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(None),
+ )
+
+ expected_web_search_cost = cost_per_web_search_request(
+ usage=Usage(
+ prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=3)
+ ),
+ model_info=model_info,
+ )
+ assert expected_web_search_cost > 0
+ assert round(grounded - ungrounded, 10) == round(expected_web_search_cost, 10)
+
+
+def test_vertex_image_generation_cost_no_web_search_when_absent():
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+ model = "gemini-3-pro-image-preview"
+
+ cost_zero = vertex_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(0),
+ )
+ cost_none = vertex_image_generation_cost_calculator(
+ model=model,
+ image_response=_image_response_with_web_search(None),
+ )
+
+ assert cost_zero == cost_none
diff --git a/tests/test_litellm/llms/vertex_ai/image_generation/test_vertex_ai_image_generation_transformation.py b/tests/test_litellm/llms/vertex_ai/image_generation/test_vertex_ai_image_generation_transformation.py
index fe5b5a69c95..dc2d945c33b 100644
--- a/tests/test_litellm/llms/vertex_ai/image_generation/test_vertex_ai_image_generation_transformation.py
+++ b/tests/test_litellm/llms/vertex_ai/image_generation/test_vertex_ai_image_generation_transformation.py
@@ -139,6 +139,44 @@ class TestVertexAIGeminiImageGenerationConfig:
)
assert request["generationConfig"]["imageConfig"]["imageSize"] == "4K"
+ def test_map_openai_params_web_search_options(self):
+ """Test web_search_options maps to googleSearch tool"""
+ result = self.config.map_openai_params(
+ {"web_search_options": {}}, {}, "gemini-3.1-flash-image-preview", False
+ )
+ assert result["tools"] == [{"googleSearch": {}}]
+
+ def test_transform_image_generation_request_with_web_search_tools(self):
+ """Test request transformation includes googleSearch tools"""
+ request = self.config.transform_image_generation_request(
+ model="gemini-3.1-flash-image-preview",
+ prompt="Generate an image of the latest iPhone",
+ optional_params={"tools": [{"googleSearch": {}}]},
+ litellm_params={},
+ headers={},
+ )
+ assert request["tools"] == [{"googleSearch": {}}]
+
+ def test_transform_image_generation_request_forwards_tool_config(self):
+ """Test request transformation forwards toolConfig side-effects from tool mapping"""
+ mapped = self.config.map_openai_params(
+ {"tools": [{"googleMaps": {"latitude": 37.7, "longitude": -122.4}}]},
+ {},
+ "gemini-3.1-flash-image-preview",
+ False,
+ )
+ request = self.config.transform_image_generation_request(
+ model="gemini-3.1-flash-image-preview",
+ prompt="Generate an image of a coffee shop nearby",
+ optional_params=mapped,
+ litellm_params={},
+ headers={},
+ )
+ assert request["tools"] == [{"googleMaps": {}}]
+ assert request["toolConfig"] == {
+ "retrievalConfig": {"latLng": {"latitude": 37.7, "longitude": -122.4}}
+ }
+
def test_transform_image_generation_request_with_candidate_count(self):
"""Test request transformation with candidate_count"""
request = self.config.transform_image_generation_request(
@@ -311,6 +349,51 @@ class TestVertexAIGeminiImageGenerationConfig:
== "test_signature_abc123"
)
+ def test_transform_image_generation_response_tracks_web_search_requests(self):
+ """Grounding queries are carried onto usage so search spend can be billed"""
+ mock_response = MagicMock(spec=httpx.Response)
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "candidates": [
+ {
+ "content": {
+ "parts": [
+ {
+ "inlineData": {
+ "mimeType": "image/png",
+ "data": "base64_encoded_image_data",
+ }
+ }
+ ]
+ },
+ "groundingMetadata": {
+ "webSearchQueries": ["eiffel tower", "paris skyline"]
+ },
+ }
+ ],
+ "usageMetadata": {
+ "promptTokenCount": 93,
+ "candidatesTokenCount": 17,
+ "totalTokenCount": 110,
+ },
+ }
+ mock_response.headers = {}
+
+ from litellm.types.utils import ImageResponse
+
+ result = self.config.transform_image_generation_response(
+ model="gemini-2.5-flash-image",
+ raw_response=mock_response,
+ model_response=ImageResponse(),
+ logging_obj=MagicMock(),
+ request_data={},
+ optional_params={},
+ litellm_params={},
+ encoding=None,
+ )
+
+ assert result.usage.web_search_requests == 2
+
class TestVertexAIImagenImageGenerationConfig:
def setup_method(self):