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
fix(groq): translate web_search_options to the browser_search tool (#34971)
Ahmed N368dd0be5b9f
diff --git a/litellm/constants.py b/litellm/constants.pyindex 06421e6ed6a..164f5a77a76 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -313,6 +313,7 @@ MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES = int(os.getenv("MAX_LONG_SIDE_FOR_IMAGE_HIGH_RMAX_TILE_WIDTH = int(os.getenv("MAX_TILE_WIDTH", 512))MAX_TILE_HEIGHT = int(os.getenv("MAX_TILE_HEIGHT", 512))OPENAI_FILE_SEARCH_COST_PER_1K_CALLS = float(os.getenv("OPENAI_FILE_SEARCH_COST_PER_1K_CALLS", 2.5 / 1000))+GROQ_BROWSER_VISIT_WEBSITE_COST_PER_CALL = 1.0 / 1000# Azure OpenAI Assistants feature costs# Source: https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/AZURE_FILE_SEARCH_COST_PER_GB_PER_DAY = float(diff --git a/litellm/llms/__init__.py b/litellm/llms/__init__.pyindex a35fe5b2093..72c8bf15b47 100644--- a/litellm/llms/__init__.py+++ b/litellm/llms/__init__.py@@ -55,6 +55,12 @@ def get_cost_for_web_search_request(custom_llm_provider: str, usage: "Usage", mofrom .xai.cost_calculator import cost_per_web_search_requestreturn cost_per_web_search_request(usage=usage, model_info=model_info)+ elif custom_llm_provider == "groq":+ from .groq.cost_calculator import (+ cost_per_web_search_request as groq_cost_per_web_search_request,+ )++ return groq_cost_per_web_search_request(usage=usage, model_info=model_info)else:return Nonediff --git a/litellm/llms/groq/chat/transformation.py b/litellm/llms/groq/chat/transformation.pyindex 35a4a14057f..b319d6067aa 100644--- a/litellm/llms/groq/chat/transformation.py+++ b/litellm/llms/groq/chat/transformation.py@@ -11,7 +11,7 @@ from typing import ()import httpx-from pydantic import BaseModel+from pydantic import BaseModel, TypeAdapter, ValidationErrorimport litellmfrom litellm._logging import verbose_logger@@ -27,10 +27,20 @@ from litellm.types.llms.openai import (ChatCompletionToolParam,ChatCompletionToolParamFunctionChunk,)-from litellm.types.utils import ModelResponse, ModelResponseStream+from litellm.types.utils import ModelResponse, ModelResponseStream, ServerToolUsefrom ...openai_like.chat.transformation import OpenAILikeChatConfig+GROQ_COMPOUND_MODELS = frozenset({"compound", "compound-mini"})+++class GroqExecutedToolIdentity(BaseModel):+ name: str | None = None+ type: str | None = None+++_EXECUTED_TOOLS_ADAPTER = TypeAdapter(tuple[GroqExecutedToolIdentity, ...])+class GroqChatConfig(OpenAILikeChatConfig):frequency_penalty: int | None = None@@ -95,6 +105,12 @@ class GroqChatConfig(OpenAILikeChatConfig):except ValueError:pass+ if not (+ self._is_compound_model(model)+ or litellm.supports_web_search(model=model, custom_llm_provider=self.custom_llm_provider)+ ):+ base_params.remove("web_search_options")+try:if litellm.supports_reasoning(model=model, custom_llm_provider=self.custom_llm_provider):base_params.append("reasoning_effort")@@ -103,6 +119,10 @@ class GroqChatConfig(OpenAILikeChatConfig):return base_params+ @staticmethod+ def _is_compound_model(model: str) -> bool:+ return model.removeprefix("groq/") in GROQ_COMPOUND_MODELS+@overloaddef _transform_messages(self, messages: list[AllMessageValues], model: str, is_async: Literal[True]@@ -238,7 +258,23 @@ class GroqChatConfig(OpenAILikeChatConfig):"response_format", None) # only remove if it's a json_schema - handled via using groq's tool calling params.# else: model supports native json_schema, let response_format pass through+ web_search_options = non_default_params.pop("web_search_options", None)optional_params = super().map_openai_params(non_default_params, optional_params, model, drop_params)+ if web_search_options is None:+ return optional_params++ if web_search_options:+ verbose_logger.info(+ "Groq web search enabled; ignoring unsupported web_search_options fields: %s",+ sorted(web_search_options),+ )+ if self._is_compound_model(model):+ return optional_params+ if not any(tool.get("type") == "browser_search" for tool in optional_params.get("tools") or ()):+ optional_params = self._add_tools_to_optional_params(+ optional_params=optional_params,+ tools=[{"type": "browser_search"}], # mutable-ok: request tools must be json dicts in a list+ )return optional_params@@ -274,8 +310,34 @@ class GroqChatConfig(OpenAILikeChatConfig):original_service_tier=getattr(model_response, "service_tier"))setattr(model_response, "service_tier", mapped_service_tier)+ self._add_web_search_usage(model_response=model_response)return model_response+ def _add_web_search_usage(self, model_response: ModelResponse) -> None:+ usage = getattr(model_response, "usage", None)+ if usage is None:+ return+ actions = self._executed_tool_actions(model_response)+ searches = actions.count("browser.search") + actions.count("browser_search")+ opens = actions.count("browser.open")+ if searches == 0 and opens == 0:+ return+ usage.server_tool_use = ServerToolUse(web_search_requests=searches, browser_open_requests=opens)++ @staticmethod+ def _executed_tool_actions(model_response: ModelResponse) -> tuple[str | None, ...]:+ try:+ return tuple(+ identity.name or identity.type+ for choice in model_response.choices+ for identity in _EXECUTED_TOOLS_ADAPTER.validate_python(+ getattr(getattr(choice, "message", None), "executed_tools", None) or ()+ )+ )+ except ValidationError as e:+ verbose_logger.info("Groq executed_tools entries did not match the expected shape; not billed: %s", e)+ return ()+def _map_groq_service_tier(self, original_service_tier: str | None) -> Literal["auto", "default", "flex"]:"""Ensure groq service tier is OpenAI compatible.diff --git a/litellm/llms/groq/cost_calculator.py b/litellm/llms/groq/cost_calculator.pynew file mode 100644index 00000000000..c31dea0fd4d--- /dev/null+++ b/litellm/llms/groq/cost_calculator.py@@ -0,0 +1,27 @@+"""+Groq-specific cost helpers.++Groq bills the built-in browser tool per executed action+(https://groq.com/pricing): `browser.search` at $5 per 1k and+`browser.open` at $1 per 1k. The Groq chat transformation counts both+action kinds off `executed_tools` into `usage.server_tool_use`.+"""++from typing import TYPE_CHECKING++from litellm.constants import GROQ_BROWSER_VISIT_WEBSITE_COST_PER_CALL+from litellm.types.utils import Usage++if TYPE_CHECKING:+ from litellm.types.utils import ModelInfo+++def cost_per_web_search_request(usage: Usage, model_info: "ModelInfo") -> float:+ search_costs = model_info.get("search_context_cost_per_query")+ cost_per_search = search_costs.get("search_context_size_medium", 0.0) if search_costs else 0.0+ server_tool_use = getattr(usage, "server_tool_use", None)+ if server_tool_use is None:+ return 0.0+ searches = server_tool_use.web_search_requests or 0+ opens = server_tool_use.browser_open_requests or 0+ return searches * cost_per_search + opens * GROQ_BROWSER_VISIT_WEBSITE_COST_PER_CALLdiff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 848af54cbcf..749663775ea 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -25681,6 +25681,11 @@"max_tokens": 32766,"mode": "chat","output_cost_per_token": 6e-07,+ "search_context_cost_per_query": {+ "search_context_size_high": 0.005,+ "search_context_size_low": 0.005,+ "search_context_size_medium": 0.005+ },"supports_function_calling": true,"supports_parallel_function_calling": true,"supports_reasoning": true,@@ -25697,6 +25702,11 @@"max_tokens": 32768,"mode": "chat","output_cost_per_token": 3e-07,+ "search_context_cost_per_query": {+ "search_context_size_high": 0.005,+ "search_context_size_low": 0.005,+ "search_context_size_medium": 0.005+ },"supports_function_calling": true,"supports_parallel_function_calling": true,"supports_reasoning": true,@@ -25713,6 +25723,11 @@"max_tokens": 65536,"mode": "chat","output_cost_per_token": 3e-07,+ "search_context_cost_per_query": {+ "search_context_size_high": 0.005,+ "search_context_size_low": 0.005,+ "search_context_size_medium": 0.005+ },"supports_function_calling": true,"supports_reasoning": true,"supports_response_schema": true,diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex c63f4d53572..902253ca3a4 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -1587,6 +1587,7 @@ class PromptTokensDetailsWrapper(class ServerToolUse(BaseModel):web_search_requests: Optional[int] = Nonetool_search_requests: Optional[int] = None+ browser_open_requests: Optional[int] = Nonedef __getitem__(self, key: str) -> Optional[int]:if key not in self.__class__.model_fields:diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 56e0391f419..8a8bbdad8f1 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -25756,6 +25756,11 @@"max_tokens": 32766,"mode": "chat","output_cost_per_token": 6e-07,+ "search_context_cost_per_query": {+ "search_context_size_high": 0.005,+ "search_context_size_low": 0.005,+ "search_context_size_medium": 0.005+ },"supports_function_calling": true,"supports_parallel_function_calling": true,"supports_reasoning": true,@@ -25772,6 +25777,11 @@"max_tokens": 32768,"mode": "chat","output_cost_per_token": 3e-07,+ "search_context_cost_per_query": {+ "search_context_size_high": 0.005,+ "search_context_size_low": 0.005,+ "search_context_size_medium": 0.005+ },"supports_function_calling": true,"supports_parallel_function_calling": true,"supports_reasoning": true,@@ -25788,6 +25798,11 @@"max_tokens": 65536,"mode": "chat","output_cost_per_token": 3e-07,+ "search_context_cost_per_query": {+ "search_context_size_high": 0.005,+ "search_context_size_low": 0.005,+ "search_context_size_medium": 0.005+ },"supports_function_calling": true,"supports_reasoning": true,"supports_response_schema": true,diff --git a/tests/test_litellm/llms/groq/__init__.py b/tests/test_litellm/llms/groq/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/test_litellm/llms/groq/chat/__init__.py b/tests/test_litellm/llms/groq/chat/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/test_litellm/llms/groq/chat/test_groq_chat_transformation.py b/tests/test_litellm/llms/groq/chat/test_groq_chat_transformation.pynew file mode 100644index 00000000000..b2ba919ac7f--- /dev/null+++ b/tests/test_litellm/llms/groq/chat/test_groq_chat_transformation.py@@ -0,0 +1,247 @@+import logging+from unittest.mock import patch++import httpx+import pytest++import litellm+from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import (+ StandardBuiltInToolCostTracking,+)+from litellm.llms.custom_httpx.http_handler import HTTPHandler+from litellm.llms.groq.chat.transformation import GroqChatConfig+from litellm.utils import get_optional_params++WEB_SEARCH_MODELS = (+ "openai/gpt-oss-120b",+ "openai/gpt-oss-20b",+ "openai/gpt-oss-safeguard-20b",+)++COMPOUND_MODELS = ("compound", "compound-mini", "groq/compound", "groq/compound-mini")+++def local_model_cost_map(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")+ monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))+ litellm.get_model_info.cache_clear()+ yield+ litellm.get_model_info.cache_clear()+++class TestGroqWebSearchOptions:+ @pytest.mark.parametrize("model", WEB_SEARCH_MODELS + COMPOUND_MODELS)+ def test_supported_on_search_capable_models(self, model: str):+ assert "web_search_options" in GroqChatConfig().get_supported_openai_params(model)++ def test_not_supported_on_other_models(self):+ assert "web_search_options" not in GroqChatConfig().get_supported_openai_params("llama-3.3-70b-versatile")++ @pytest.mark.parametrize("web_search_options", [{"search_context_size": "high"}, {}])+ def test_translates_to_browser_search_tool(self, web_search_options: dict):+ optional_params = get_optional_params(+ model="openai/gpt-oss-20b",+ custom_llm_provider="groq",+ web_search_options=web_search_options,+ )+ assert optional_params["tools"] == [{"type": "browser_search"}]+ assert "web_search_options" not in optional_params++ def test_no_duplicate_browser_search_tool(self):+ optional_params = get_optional_params(+ model="openai/gpt-oss-20b",+ custom_llm_provider="groq",+ web_search_options={"search_context_size": "high"},+ tools=[{"type": "browser_search"}],+ )+ assert optional_params["tools"] == [{"type": "browser_search"}]++ def test_caller_function_tools_preserved(self):+ function_tool = {+ "type": "function",+ "function": {+ "name": "get_weather",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ optional_params = get_optional_params(+ model="openai/gpt-oss-20b",+ custom_llm_provider="groq",+ web_search_options={},+ tools=[function_tool],+ )+ assert optional_params["tools"] == [function_tool, {"type": "browser_search"}]++ def test_unsupported_model_drops_param_with_drop_params(self):+ optional_params = get_optional_params(+ model="llama-3.3-70b-versatile",+ custom_llm_provider="groq",+ web_search_options={"search_context_size": "high"},+ drop_params=True,+ )+ assert "web_search_options" not in optional_params+ assert "tools" not in optional_params++ def test_unsupported_model_raises_without_drop_params(self):+ with pytest.raises(litellm.UnsupportedParamsError):+ get_optional_params(+ model="llama-3.3-70b-versatile",+ custom_llm_provider="groq",+ web_search_options={"search_context_size": "high"},+ drop_params=False,+ )++ @pytest.mark.parametrize("model", COMPOUND_MODELS)+ def test_compound_injects_no_tool(self, model: str):+ optional_params = get_optional_params(+ model=model,+ custom_llm_provider="groq",+ web_search_options={"search_context_size": "high"},+ )+ assert "web_search_options" not in optional_params+ assert "tools" not in optional_params++ def test_ignored_fields_logged_as_info(self, caplog: pytest.LogCaptureFixture):+ with caplog.at_level(logging.INFO, logger="LiteLLM"):+ get_optional_params(+ model="openai/gpt-oss-20b",+ custom_llm_provider="groq",+ web_search_options={"search_context_size": "high", "user_location": {"type": "approximate"}},+ )+ ignored_fields_records = tuple(+ record+ for record in caplog.records+ if "search_context_size" in record.message and "user_location" in record.message+ )+ assert len(ignored_fields_records) == 1+ assert ignored_fields_records[0].levelno == logging.INFO+ assert "enabled" in ignored_fields_records[0].message++ def test_empty_options_log_nothing(self, caplog: pytest.LogCaptureFixture):+ with caplog.at_level(logging.INFO, logger="LiteLLM"):+ get_optional_params(+ model="openai/gpt-oss-20b",+ custom_llm_provider="groq",+ web_search_options={},+ )+ assert not [record for record in caplog.records if "web_search_options" in record.message]+++def _searched_groq_response(executed_tools: list | None) -> dict:+ return {+ "id": "chatcmpl-1",+ "object": "chat.completion",+ "created": 1,+ "model": "openai/gpt-oss-20b",+ "service_tier": "auto",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "Top headline: example",+ **({"executed_tools": executed_tools} if executed_tools is not None else {}),+ },+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 100, "completion_tokens": 10, "total_tokens": 110},+ }+++EXECUTED_TOOLS_THREE_SEARCHES_TWO_OPENS = [+ {"name": "browser.search", "type": "browser_search"},+ {"name": "browser.open", "type": "function"},+ {"name": "browser.search", "type": "browser_search"},+ {"type": "browser_search"},+ {"name": "browser.open", "type": "browser_search"},+ {"name": "browser.find", "type": "browser.find"},+]++EXECUTED_TOOLS_OPENS_ONLY = [+ {"name": "browser.open", "type": "browser.open"},+ {"name": "browser.open", "type": "function"},+ {"name": "browser.find", "type": "browser.find"},+]+++def _groq_completion_with_mocked_response(response_json: dict) -> litellm.ModelResponse:+ client = HTTPHandler()+ fake_response = httpx.Response(+ status_code=200,+ json=response_json,+ request=httpx.Request("POST", "https://api.groq.com/openai/v1/chat/completions"),+ )+ with patch.object(client, "post", return_value=fake_response):+ return litellm.completion(+ model="groq/openai/gpt-oss-20b",+ messages=[{"role": "user", "content": "hi"}],+ web_search_options={"search_context_size": "high"},+ api_key="fake-key",+ client=client,+ )+++class TestGroqWebSearchUsageSignal:+ @pytest.mark.parametrize(+ "executed_tools, expected_searches, expected_opens",+ [+ (EXECUTED_TOOLS_THREE_SEARCHES_TWO_OPENS, 3, 2),+ (EXECUTED_TOOLS_OPENS_ONLY, 0, 2),+ ],+ )+ def test_counts_actions_into_usage(self, executed_tools: list, expected_searches: int, expected_opens: int):+ response = _groq_completion_with_mocked_response(_searched_groq_response(executed_tools))+ assert response.usage.server_tool_use.web_search_requests == expected_searches+ assert response.usage.server_tool_use.browser_open_requests == expected_opens++ def test_no_signal_without_executed_tools(self):+ response = _groq_completion_with_mocked_response(_searched_groq_response(None))+ assert getattr(response.usage, "server_tool_use", None) is None++ def test_malformed_executed_tools_skips_billing_without_breaking_response(self):+ response = _groq_completion_with_mocked_response(+ _searched_groq_response(["not-a-dict", {"name": {"nested": "junk"}}])+ )+ assert response.choices[0].message.content == "Top headline: example"+ assert getattr(response.usage, "server_tool_use", None) is None++ def test_response_without_usage_is_left_untouched(self):+ model_response = litellm.ModelResponse()+ GroqChatConfig()._add_web_search_usage(model_response=model_response)+ assert getattr(model_response, "usage", None) is None++ @pytest.mark.usefixtures("local_model_cost_map")+ @pytest.mark.parametrize(+ "executed_tools, expected_cost",+ [+ (EXECUTED_TOOLS_THREE_SEARCHES_TWO_OPENS, 3 * 0.005 + 2 * 0.001),+ (EXECUTED_TOOLS_OPENS_ONLY, 2 * 0.001),+ ],+ )+ def test_response_billed_per_action(self, executed_tools: list, expected_cost: float):+ response = _groq_completion_with_mocked_response(_searched_groq_response(executed_tools))+ assert StandardBuiltInToolCostTracking.response_object_includes_web_search_call(+ response_object=response, usage=response.usage+ )+ cost = StandardBuiltInToolCostTracking.get_cost_for_built_in_tools(+ model="groq/openai/gpt-oss-20b",+ response_object=response,+ usage=response.usage,+ custom_llm_provider="groq",+ standard_built_in_tools_params={"web_search_options": {"search_context_size": "high"}},+ )+ assert cost == pytest.approx(expected_cost)+++class TestGroqWebSearchCost:+ @pytest.mark.usefixtures("local_model_cost_map")+ @pytest.mark.parametrize("model", WEB_SEARCH_MODELS)+ @pytest.mark.parametrize("search_context_size", ["low", "medium", "high"])+ def test_browser_search_priced_per_search(self, model: str, search_context_size: str):+ cost = StandardBuiltInToolCostTracking.get_cost_for_web_search(+ web_search_options={"search_context_size": search_context_size},+ model_info=litellm.get_model_info(model=model, custom_llm_provider="groq"),+ )+ assert cost == 0.005diff --git a/tests/test_litellm/llms/groq/test_groq_cost_calculator.py b/tests/test_litellm/llms/groq/test_groq_cost_calculator.pynew file mode 100644index 00000000000..bc3b8058b7f--- /dev/null+++ b/tests/test_litellm/llms/groq/test_groq_cost_calculator.py@@ -0,0 +1,56 @@+import pytest++from litellm.llms.groq.cost_calculator import cost_per_web_search_request+from litellm.types.utils import ModelInfo, ServerToolUse, Usage++PRICED_MODEL_INFO = ModelInfo(+ key="groq/openai/gpt-oss-20b",+ litellm_provider="groq",+ mode="chat",+ search_context_cost_per_query={+ "search_context_size_low": 0.005,+ "search_context_size_medium": 0.005,+ "search_context_size_high": 0.005,+ },+)+++def _usage_with_actions(searches: int | None, opens: int | None = None) -> Usage:+ return Usage(+ prompt_tokens=100,+ completion_tokens=10,+ total_tokens=110,+ server_tool_use=ServerToolUse(web_search_requests=searches, browser_open_requests=opens),+ )+++def test_bills_per_executed_search():+ cost = cost_per_web_search_request(usage=_usage_with_actions(7), model_info=PRICED_MODEL_INFO)+ assert cost == pytest.approx(7 * 0.005)+++def test_no_searches_costs_nothing():+ cost = cost_per_web_search_request(usage=_usage_with_actions(None), model_info=PRICED_MODEL_INFO)+ assert cost == 0.0+++def test_missing_usage_signal_costs_nothing():+ usage = Usage(prompt_tokens=100, completion_tokens=10, total_tokens=110)+ cost = cost_per_web_search_request(usage=usage, model_info=PRICED_MODEL_INFO)+ assert cost == 0.0+++def test_missing_pricing_costs_nothing():+ unpriced = ModelInfo(key="groq/openai/gpt-oss-20b", litellm_provider="groq", mode="chat")+ cost = cost_per_web_search_request(usage=_usage_with_actions(3), model_info=unpriced)+ assert cost == 0.0+++def test_bills_visit_website_per_open():+ cost = cost_per_web_search_request(usage=_usage_with_actions(0, opens=15), model_info=PRICED_MODEL_INFO)+ assert cost == pytest.approx(15 * 0.001)+++def test_bills_searches_and_opens_together():+ cost = cost_per_web_search_request(usage=_usage_with_actions(2, opens=3), model_info=PRICED_MODEL_INFO)+ assert cost == pytest.approx(2 * 0.005 + 3 * 0.001)