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(search): price Tavily advanced and Linkup deep searches at their own cost map entries (#47411)
yucheng-berrif03f98ac227f
diff --git a/litellm/search/cost_calculator.py b/litellm/search/cost_calculator.pyindex 21f27075e0f..15755128136 100644--- a/litellm/search/cost_calculator.py+++ b/litellm/search/cost_calculator.py@@ -8,12 +8,17 @@ from typing import Finalfrom pydantic import TypeAdapter, ValidationError+import litellm+from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMapfrom litellm.utils import get_model_infoPROVIDER_USAGE_ADAPTER: Final[TypeAdapter[tuple[Mapping[str, object], ...]]] = TypeAdapter(tuple[Mapping[str, object], ...])EMPTY_OPTIONAL_PARAMS: Final[Mapping[str, object]] = MappingProxyType({})+SEARCH_MODE_PARAM_BY_PROVIDER: Final[Mapping[str, str]] = MappingProxyType(+ {"tavily": "search_depth", "linkup": "depth"}+)def _provider_usage(@@ -28,6 +33,32 @@ def _provider_usage(return None+def _registered_at_runtime(entry: str) -> bool:+ """Whether `entry`'s live price differs from the catalog as loaded, i.e. `register_model` changed it."""+ live: Final[object] = litellm.model_cost.get(entry) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] # registry is dynamically typed+ return live != GetModelCostMap.loaded_model_cost_map().get(entry) # pyright: ignore[reportUnknownVariableType] # `live` comes from the untyped registry+++def _pricing_model(+ model: str,+ custom_llm_provider: str | None,+ optional_params: Mapping[str, object] | None,+) -> str:+ """`<provider>/search-<mode>` when `model` is the generic `<provider>/search` entry (bare or provider-prefixed) and+ the request's mode parameter names a priced entry, else `model`. A price registered at runtime on the generic entry+ keeps applying until the mode entry is registered too."""+ mode_param: Final = SEARCH_MODE_PARAM_BY_PROVIDER.get(custom_llm_provider or "")+ generic_model: Final = f"{custom_llm_provider}/search"+ if mode_param is None or model not in (generic_model, f"{custom_llm_provider}/{generic_model}"):+ return model+ mode: Final = (optional_params if optional_params is not None else EMPTY_OPTIONAL_PARAMS).get(mode_param)+ mode_model: Final = f"{custom_llm_provider}/search-{mode}"+ priced: Final = mode_model in litellm.model_cost # pyright: ignore[reportUnknownMemberType] # registry is dynamically typed+ if not priced or (_registered_at_runtime(generic_model) and not _registered_at_runtime(mode_model)):+ return model+ return mode_model++def search_provider_cost_per_query(model: str,custom_llm_provider: str | None = None,@@ -38,7 +69,8 @@ def search_provider_cost_per_query(Calculate cost for search-only providers.Returns (input_cost, output_cost) where input_cost = queries * cost_per_query- Supports tiered pricing based on max_results parameter.+ Supports tiered pricing based on max_results parameter, and per-mode price entries selected by the+ provider's mode parameter (Tavily `search_depth`, Linkup `depth`).Args:model: Model name (e.g., "exa_ai/search", "tavily/search")@@ -61,7 +93,10 @@ def search_provider_cost_per_query()return (input_cost, 0.0)- model_info: Final = get_model_info(model=model, custom_llm_provider=custom_llm_provider)+ model_info: Final = get_model_info(+ model=_pricing_model(model, custom_llm_provider, optional_params),+ custom_llm_provider=custom_llm_provider,+ )# Check for tiered pricing (e.g., Exa AI based on max_results)tiered_pricing: Final = model_info.get("tiered_pricing")diff --git a/tests/integration/pricing/test_search_mode_pricing.py b/tests/integration/pricing/test_search_mode_pricing.pynew file mode 100644index 00000000000..02b1ce75dd6--- /dev/null+++ b/tests/integration/pricing/test_search_mode_pricing.py@@ -0,0 +1,411 @@+import json+import uuid+from collections.abc import Mapping, Sequence+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from types import MappingProxyType+from typing import Final++import httpx+import pytest+import yaml+from integration._support import interception_vendor as iv+from integration._support.client import Gateway, Scenario, eventually, string_value+from integration._support.process import owned_proxy+from integration._support.wire import Reply, Request, wire_server+from pydantic import JsonValue, TypeAdapter++_API_KEY: Final = "synthetic-search-key"+_QUERY: Final = "integration search pricing"+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_PACKAGED_PRICES: Final = _JSON_OBJECT.validate_json(+ (Path(__file__).resolve().parents[3] / "litellm" / "model_prices_and_context_window_backup.json").read_bytes()+)+_RESULTS: Final = {+ "tavily": {"results": [{"title": "Priced result", "url": "https://result.invalid/a", "content": "snippet"}]},+ "linkup": {+ "results": [{"type": "text", "name": "Priced result", "url": "https://result.invalid/a", "content": "snippet"}]+ },+}+_MODE_PARAM: Final = {"tavily": "search_depth", "linkup": "depth"}+_QUERY_FIELD: Final = {"tavily": "query", "linkup": "q"}+_MODE_ENTRY: Final = {"tavily": "tavily/search-advanced", "linkup": "linkup/search-deep"}+_MODE_VALUE: Final = {"tavily": "advanced", "linkup": "deep"}+_BASE_MODE: Final = {"tavily": "basic", "linkup": "standard"}+_NO_PARAMS: Final[Mapping[str, JsonValue]] = MappingProxyType({})+++def _price(entry: str) -> float:+ prices: Final = _PACKAGED_PRICES[entry]+ assert isinstance(prices, dict), entry+ rate: Final = prices["input_cost_per_query"]+ assert isinstance(rate, int | float), (entry, rate)+ return float(rate)+++def _search_tool(+ gateway: Gateway,+ scenario: Scenario,+ provider: str,+ api_base: str,+ litellm_params: Mapping[str, JsonValue] = _NO_PARAMS,+) -> str:+ name: Final = f"{provider}-priced-{uuid.uuid4().hex}"+ created: Final = gateway.post(+ "/search_tools",+ {+ "search_tool": {+ "search_tool_name": name,+ "litellm_params": {+ "search_provider": provider,+ "api_key": _API_KEY,+ "api_base": api_base,+ **litellm_params,+ },+ }+ },+ )+ scenario.cleanups.callback(gateway.request, "DELETE", f"/search_tools/{string_value(created['search_tool_id'])}")+ return name+++def _spend(gateway: Gateway, call_id: str) -> float:+ rows: Final = eventually(+ lambda: gateway.rows('SELECT spend FROM "LiteLLM_SpendLogs" WHERE request_id=%s', (call_id,)),+ lambda found: len(found) == 1,+ seconds=70,+ )+ return float(str(rows[0]["spend"]))+++ ("provider", "mode", "wire_mode", "priced_entry"),+ [+ ("tavily", "advanced", "advanced", "tavily/search-advanced"),+ ("tavily", "basic", "basic", "tavily/search"),+ ("tavily", None, None, "tavily/search"),+ ("linkup", "deep", "deep", "linkup/search-deep"),+ ("linkup", "standard", "standard", "linkup/search"),+ ("linkup", None, "standard", "linkup/search"),+ ],+ ids=["tavily-advanced", "tavily-basic", "tavily-default", "linkup-deep", "linkup-standard", "linkup-default"],+)+def test_search_is_charged_at_the_price_entry_for_the_mode_the_provider_ran(+ gateway: Gateway, provider: str, mode: str | None, wire_mode: str | None, priced_entry: str+) -> None:+ mode_param: Final = _MODE_PARAM[provider]++ def respond(request: Request) -> Reply:+ assert (request.method, request.target) == ("POST", f"/{provider}/search"), request.target+ assert request.headers["authorization"] == f"Bearer {_API_KEY}", request.headers+ assert json.loads(request.body).get(mode_param) == wire_mode, request.body+ return Reply(body=json.dumps(_RESULTS[provider]).encode())++ body: Final = {"query": _QUERY} if mode is None else {"query": _QUERY, mode_param: mode}+ with wire_server(respond) as wire, gateway.scenario() as scenario:+ tool: Final = _search_tool(gateway, scenario, provider, f"{wire.url}/{provider}")+ spellings: Final = (+ (f"/v1/search/{tool}", body),+ (f"/search/{tool}", body),+ ("/v1/search", {"search_tool_name": tool, **body}),+ ("/search", {"model": tool, **body}),+ )+ responses: Final = tuple(gateway.request("POST", path, sent) for path, sent in spellings)+ for (path, _), response in zip(spellings, responses, strict=True):+ assert response.status_code == 200, f"{path}: {response.text}"+ assert float(response.headers["x-litellm-response-cost"]) == pytest.approx(_price(priced_entry)), (+ path,+ response.headers,+ )+ assert [request.target for request in wire.drain()] == [f"/{provider}/search"] * len(spellings)+ assert [_spend(gateway, response.headers["x-litellm-call-id"]) for response in responses] == pytest.approx(+ [_price(priced_entry)] * len(spellings)+ )+++ ("provider", "modes"),+ [+ ("tavily", ("ultra-fast", "ADVANCED", " advanced", "", 7, ["advanced"], {"depth": "advanced"})),+ ("linkup", ("DEEP", "deeper", "", 7, ["deep"], {"depth": "deep"})),+ ],+ ids=["tavily", "linkup"],+)+def test_a_mode_with_no_price_entry_of_its_own_is_charged_at_the_base_price(+ gateway: Gateway, provider: str, modes: tuple[JsonValue, ...]+) -> None:+ mode_param: Final = _MODE_PARAM[provider]++ def respond(request: Request) -> Reply:+ assert (request.method, request.target) == ("POST", f"/{provider}/search"), request.target+ return Reply(body=json.dumps(_RESULTS[provider]).encode())++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ tool: Final = _search_tool(gateway, scenario, provider, f"{wire.url}/{provider}")+ responses: Final = tuple(+ gateway.request("POST", f"/v1/search/{tool}", {"query": _QUERY, mode_param: mode}) for mode in modes+ )+ assert [response.status_code for response in responses] == [200] * len(modes), [r.text for r in responses]+ assert [json.loads(request.body)[mode_param] for request in wire.drain()] == list(modes)+ assert [float(response.headers["x-litellm-response-cost"]) for response in responses] == pytest.approx(+ [_price(f"{provider}/search")] * len(modes)+ )+ assert [_spend(gateway, response.headers["x-litellm-call-id"]) for response in responses] == pytest.approx(+ [_price(f"{provider}/search")] * len(modes)+ )+++def _burst_cells(provider: str) -> tuple[tuple[str, str | None], ...]:+ return tuple((provider, mode) for mode in (_MODE_VALUE[provider], _BASE_MODE[provider], None))+++def _burst_price(provider: str, mode: str | None) -> float:+ return _price(_MODE_ENTRY[provider] if mode == _MODE_VALUE[provider] else f"{provider}/search")+++def test_a_concurrent_burst_with_upstream_failures_charges_each_success_at_its_mode_price_and_no_failure(+ gateway: Gateway,+) -> None:+ plan: Final = tuple(+ (provider, mode, index % 7 == 0)+ for index, (provider, mode) in enumerate((*_burst_cells("tavily"), *_burst_cells("linkup")) * 4)+ )++ def respond(request: Request) -> Reply:+ provider: Final = request.target.split("/")[1]+ if json.loads(request.body)[_QUERY_FIELD[provider]].endswith("-down"):+ return Reply(status=500, body=b'{"detail":{"error":"scripted search outage"}}')+ return Reply(body=json.dumps(_RESULTS[provider]).encode())++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ tools: Final = {+ provider: _search_tool(gateway, scenario, provider, f"{wire.url}/{provider}")+ for provider in ("tavily", "linkup")+ }++ def send(index: int) -> httpx.Response:+ provider, mode, fails = plan[index]+ query: Final = f"{_QUERY} {index}{'-down' if fails else ''}"+ body: Final = {"query": query} if mode is None else {"query": query, _MODE_PARAM[provider]: mode}+ return gateway.request("POST", f"/v1/search/{tools[provider]}", body)++ with ThreadPoolExecutor(max_workers=12) as pool:+ responses: Final = tuple(pool.map(send, range(len(plan))))+ assert [response.status_code for response in responses] == [500 if fails else 200 for *_, fails in plan], [+ response.text for response in responses+ ]+ assert len(wire.drain()) == len(plan)+ successes: Final = tuple(+ (response, _burst_price(provider, mode))+ for (provider, mode, fails), response in zip(plan, responses, strict=True)+ if not fails+ )+ assert [float(response.headers["x-litellm-response-cost"]) for response, _ in successes] == pytest.approx(+ [price for _, price in successes]+ )+ rows: Final = eventually(+ lambda: gateway.rows(+ 'SELECT request_id, status, spend FROM "LiteLLM_SpendLogs" WHERE model_group = ANY(%s)',+ (list(tools.values()),),+ ),+ lambda found: len(found) == len(plan),+ seconds=70,+ )+ assert {str(row["request_id"]): float(str(row["spend"])) for row in rows if row["status"] == "success"} == (+ pytest.approx({response.headers["x-litellm-call-id"]: price for response, price in successes})+ )+ assert [float(str(row["spend"])) for row in rows if row["status"] != "success"] == [0.0] * (+ len(plan) - len(successes)+ )+++def _owned_config(+ tmp_path: Path, search_tools: Sequence[JsonValue], litellm_settings: Mapping[str, JsonValue] = _NO_PARAMS+) -> Path:+ config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())+ config["search_tools"] = list(search_tools)+ config["litellm_settings"].update(litellm_settings)+ path: Final = tmp_path / f"search-mode-{uuid.uuid4().hex}.yaml"+ path.write_text(yaml.safe_dump(config))+ return path+++def _config_tool(name: str, provider: str, api_base: str, litellm_params: Mapping[str, JsonValue]) -> JsonValue:+ return {+ "search_tool_name": name,+ "litellm_params": {"search_provider": provider, "api_key": _API_KEY, "api_base": api_base, **litellm_params},+ }+++def test_a_mode_set_on_a_config_search_tool_is_charged_at_that_modes_price_unless_the_request_overrides_it(+ gateway: Gateway, tmp_path: Path+) -> None:+ cases: Final = (("tavily", "advanced", "basic"), ("linkup", "deep", "standard"))++ def respond(request: Request) -> Reply:+ provider: Final = request.target.split("/")[1]+ assert (request.method, request.target) == ("POST", f"/{provider}/search"), request.target+ return Reply(body=json.dumps(_RESULTS[provider]).encode())++ with wire_server(respond) as wire:+ tools: Final = [+ _config_tool(f"{provider}-configured", provider, f"{wire.url}/{provider}", {_MODE_PARAM[provider]: mode})+ for provider, mode, _ in cases+ ]+ with owned_proxy(gateway, tmp_path, {}, config=_owned_config(tmp_path, tools)) as candidate:+ for provider, configured_mode, base_mode in cases:+ mode_param = _MODE_PARAM[provider]+ configured = candidate.request("POST", f"/v1/search/{provider}-configured", {"query": _QUERY})+ overridden = candidate.request(+ "POST", f"/v1/search/{provider}-configured", {"query": _QUERY, mode_param: base_mode}+ )+ assert (configured.status_code, overridden.status_code) == (200, 200), (+ configured.text,+ overridden.text,+ )+ assert [json.loads(request.body)[mode_param] for request in wire.drain()] == [+ configured_mode,+ base_mode,+ ]+ assert (+ float(configured.headers["x-litellm-response-cost"]),+ float(overridden.headers["x-litellm-response-cost"]),+ _spend(candidate, configured.headers["x-litellm-call-id"]),+ _spend(candidate, overridden.headers["x-litellm-call-id"]),+ ) == pytest.approx((_price(_MODE_ENTRY[provider]), _price(f"{provider}/search")) * 2), provider+++def test_a_price_set_on_the_search_tool_still_wins_over_the_mode_price_entry(gateway: Gateway) -> None:+ def respond(request: Request) -> Reply:+ assert json.loads(request.body)["search_depth"] == "advanced", request.body+ return Reply(body=json.dumps(_RESULTS["tavily"]).encode())++ with wire_server(respond) as wire, gateway.scenario() as scenario:+ tool: Final = _search_tool(gateway, scenario, "tavily", f"{wire.url}/tavily", {"input_cost_per_query": 0.02})+ response: Final = gateway.request("POST", f"/v1/search/{tool}", {"query": _QUERY, "search_depth": "advanced"})+ assert response.status_code == 200, response.text+ assert [request.target for request in wire.drain()] == ["/tavily/search"]+ assert float(response.headers["x-litellm-response-cost"]) == pytest.approx(0.02), response.headers+ assert _spend(gateway, response.headers["x-litellm-call-id"]) == pytest.approx(0.02)+++def _anthropic_reply(identity: str, content: Sequence[JsonValue], stop_reason: str) -> Reply:+ return Reply(+ body=json.dumps(+ {+ "id": identity,+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5-20250929",+ "content": content,+ "stop_reason": stop_reason,+ "stop_sequence": None,+ "usage": {"input_tokens": 10, "output_tokens": 4},+ }+ ).encode()+ )+++def test_a_web_search_intercepted_on_every_llm_endpoint_is_charged_at_the_search_tools_mode_price(+ gateway: Gateway, tmp_path: Path+) -> None:+ identity: Final = f"search-mode-{uuid.uuid4().hex}"+ tool: Final = f"tavily-intercepted-{uuid.uuid4().hex}"+ chat_deployment: Final = iv.deployment("search")+ responses_deployment: Final = iv.deployment("search")++ def respond(request: Request) -> Reply:+ if request.target == "/tavily/search":+ assert json.loads(request.body)["search_depth"] == "advanced", request.body+ return Reply(body=json.dumps(_RESULTS["tavily"]).encode())+ if request.target != "/v1/messages":+ return iv.respond(request)+ body: Final = json.loads(request.body)+ if any(entry.get("type") == "web_search_20250305" for entry in body["tools"]):+ return _anthropic_reply(identity, [{"type": "text", "text": "not intercepted"}], "end_turn")+ answered: Final = any(+ isinstance(message["content"], list) and any(part["type"] == "tool_result" for part in message["content"])+ for message in body["messages"]+ )+ if answered:+ return _anthropic_reply(identity, [{"type": "text", "text": "answered"}], "end_turn")+ tool_use: Final[JsonValue] = {+ "type": "tool_use",+ "id": identity,+ "name": iv.SEARCH_TOOL,+ "input": {"query": _QUERY},+ }+ return _anthropic_reply(identity, [tool_use], "tool_use")++ with wire_server(respond) as wire:+ path: Final = _owned_config(+ tmp_path,+ [_config_tool(tool, "tavily", f"{wire.url}/tavily", {"search_depth": "advanced"})],+ {+ "callbacks": ["websearch_interception"],+ "websearch_interception_params": {+ "enabled": True,+ "enabled_providers": ["anthropic", "azure"],+ "search_tool_name": tool,+ },+ },+ )+ with owned_proxy(gateway, tmp_path, {}, config=path) as candidate, candidate.scenario() as models:+ azure: Final = {"api_base": wire.url, "api_key": iv.AZURE_KEY, "api_version": iv.API_VERSION}+ sends: Final = (+ (+ "/v1/messages",+ {+ "model": models.model(+ model="anthropic/claude-sonnet-4-5-20250929",+ api_base=wire.url,+ api_key="synthetic-anthropic-key",+ ),+ "max_tokens": 64,+ "messages": [{"role": "user", "content": identity}],+ "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 1}],+ },+ "answered",+ ),+ (+ "/v1/chat/completions",+ {+ "model": models.model(model=f"azure/{chat_deployment}", **azure),+ "messages": [{"role": "user", "content": f"Search for {chat_deployment}"}],+ "tools": [{"type": "web_search"}],+ },+ iv.answer(chat_deployment),+ ),+ (+ "/v1/responses",+ {+ "model": models.model(model=f"azure/{responses_deployment}", **azure),+ "input": f"Search for {responses_deployment}",+ "tools": [{"type": "web_search"}],+ },+ iv.answer(responses_deployment),+ ),+ )+ responses: Final = tuple(+ eventually(+ lambda route=route, body=body: candidate.request("POST", route, body),+ lambda response, answer=answer: answer in response.text,+ seconds=40,+ )+ for route, body, answer in sends+ )+ assert [response.status_code for response in responses] == [200, 200, 200], [r.text for r in responses]+ searches: Final = tuple(+ json.loads(request.body)["query"] for request in wire.drain() if request.target == "/tavily/search"+ )+ assert sorted(searches) == sorted((_QUERY, iv.query(chat_deployment), iv.query(responses_deployment))), (+ searches+ )+ rows: Final = eventually(+ lambda: candidate.rows(+ """SELECT spend FROM "LiteLLM_SpendLogs" WHERE call_type IN ('search', 'asearch')""", ()+ ),+ lambda found: len(found) == len(searches),+ seconds=70,+ )+ assert [float(str(row["spend"])) for row in rows] == pytest.approx([_price("tavily/search-advanced")] * 3), rowsdiff --git a/tests/unit/search/test_main.py b/tests/unit/search/test_main.pyindex 72266321715..e30fd2eb6f8 100644--- a/tests/unit/search/test_main.py+++ b/tests/unit/search/test_main.py@@ -1,4 +1,6 @@import datetime+import json+from collections.abc import Mappingfrom typing import Finalimport httpx@@ -6,19 +8,40 @@ import pytestimport respximport litellm+from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMapfrom litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.search.cost_calculator import search_provider_cost_per_queryEXA_SEARCH_URL: Final = "https://api.exa.ai/search"+TAVILY_SEARCH_URL: Final = "https://api.tavily.com/search"+LINKUP_SEARCH_URL: Final = "https://api.linkup.so/v1/search"+SEARCH_MODE_PRICES: Final = {+ "tavily/search": 0.002,+ "tavily/search-advanced": 0.007,+ "tavily/search-fast": 0.001,+ "linkup/search": 0.003,+ "linkup/search-deep": 0.011,+ "perplexity/search": 0.004,+ "perplexity/search-advanced": 0.009,+ "tavily/negotiated-search": 0.004,+}@pytest.fixturedef _local_model_cost_map(monkeypatch: pytest.MonkeyPatch) -> None:- from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap-monkeypatch.setattr(litellm, "model_cost", GetModelCostMap.load_local_model_cost_map())+def _search_mode_prices(_local_model_cost_map: None, monkeypatch: pytest.MonkeyPatch) -> None:+ for model, price in SEARCH_MODE_PRICES.items():+ monkeypatch.setitem(+ litellm.model_cost,+ model,+ {"input_cost_per_query": price, "litellm_provider": model.split("/", 1)[0], "mode": "search"},+ )++def _proxy_style_logging_obj() -> Logging:"""The proxy builds the logging object from the request body before the router adds the search tool'slitellm_params, so the per-tool price only reaches cost tracking if the search call itself records it."""@@ -90,3 +113,169 @@ def test_unpriced_fallback_search_tool_is_billed_at_its_own_price_not_the_failed)assert fallback._hidden_params["response_cost"] == pytest.approx(map_price)++[email protected]("_search_mode_prices")+ ("provider", "optional_params", "expected"),+ [+ ("tavily", {"search_depth": "advanced"}, 0.007),+ ("tavily", {"search_depth": "fast"}, 0.001),+ ("tavily", {"search_depth": "basic"}, 0.002),+ ("tavily", {"search_depth": "ultra-fast"}, 0.002),+ ("tavily", {}, 0.002),+ ("tavily", None, 0.002),+ ("tavily", {"search_depth": ["advanced"]}, 0.002),+ ("tavily", {"depth": "advanced"}, 0.002),+ ("linkup", {"depth": "deep"}, 0.011),+ ("linkup", {"depth": "standard"}, 0.003),+ ("linkup", {}, 0.003),+ ("linkup", {"search_depth": "deep"}, 0.003),+ ("perplexity", {"search_depth": "advanced", "depth": "advanced"}, 0.004),+ ],+ ids=[+ "tavily-advanced",+ "tavily-fast",+ "tavily-basic-has-no-entry",+ "tavily-mode-without-entry",+ "tavily-no-mode",+ "tavily-no-params",+ "tavily-non-string-mode",+ "tavily-ignores-linkup-param",+ "linkup-deep",+ "linkup-standard-has-no-entry",+ "linkup-no-mode",+ "linkup-ignores-tavily-param",+ "provider-without-mode-param-keeps-base-entry",+ ],+)+def test_search_cost_is_the_price_entry_of_the_requested_mode(+ provider: str, optional_params: Mapping[str, object] | None, expected: float+) -> None:+ cost: Final = search_provider_cost_per_query(+ model=f"{provider}/search", custom_llm_provider=provider, optional_params=optional_params+ )+ assert cost == pytest.approx((expected, 0.0))++[email protected]("_search_mode_prices")+def test_a_registered_search_model_keeps_its_own_price_for_an_advanced_search() -> None:+ cost: Final = search_provider_cost_per_query(+ model="tavily/negotiated-search", custom_llm_provider="tavily", optional_params={"search_depth": "advanced"}+ )+ assert cost == pytest.approx((0.004, 0.0))+++def _loaded_catalog_prices(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ litellm,+ "model_cost",+ {key: dict(entry) for key, entry in GetModelCostMap.loaded_model_cost_map().items()},+ )+++MODE_CASES: Final = (+ pytest.param("tavily", "tavily/search", {"search_depth": "advanced"}, id="tavily"),+ pytest.param("tavily", "tavily/tavily/search", {"search_depth": "advanced"}, id="tavily-sdk-spelling"),+ pytest.param("linkup", "linkup/search", {"depth": "deep"}, id="linkup"),+)+++def _register(monkeypatch: pytest.MonkeyPatch, entry: str, price: float) -> None:+ monkeypatch.setitem(+ litellm.model_cost,+ entry,+ {"input_cost_per_query": price, "litellm_provider": entry.split("/", 1)[0], "mode": "search"},+ )+++def _mode_entry(provider: str, optional_params: Mapping[str, object]) -> str:+ return f"{provider}/search-{next(iter(optional_params.values()))}"++[email protected]("_loaded_catalog_prices")[email protected](("provider", "model", "optional_params"), MODE_CASES)+def test_the_catalog_mode_price_applies_when_nothing_is_registered_at_runtime(+ provider: str, model: str, optional_params: Mapping[str, object]+) -> None:+ catalog: Final = GetModelCostMap.loaded_model_cost_map()+ mode_price: Final = catalog[_mode_entry(provider, optional_params)]["input_cost_per_query"]+ assert mode_price != catalog[f"{provider}/search"]["input_cost_per_query"]+ cost: Final = search_provider_cost_per_query(+ model=model, custom_llm_provider=provider, optional_params=optional_params+ )+ assert cost == pytest.approx((mode_price, 0.0))++[email protected]("_loaded_catalog_prices")+ ("provider", "optional_params"),+ [+ ("tavily", {"search_depth": "ultra-fast"}),+ ("tavily", {"search_depth": 7}),+ ("tavily", {"search_depth": ["advanced"]}),+ ("linkup", {"depth": "standard"}),+ ("linkup", {"depth": "DEEP"}),+ ],+ ids=["tavily-ultra-fast", "tavily-int", "tavily-list", "linkup-standard", "linkup-uppercase"],+)+def test_a_mode_without_its_own_catalog_entry_gets_the_catalog_base_price(+ provider: str, optional_params: Mapping[str, object]+) -> None:+ cost: Final = search_provider_cost_per_query(+ model=f"{provider}/search", custom_llm_provider=provider, optional_params=optional_params+ )+ base_price: Final = GetModelCostMap.loaded_model_cost_map()[f"{provider}/search"]["input_cost_per_query"]+ assert cost == pytest.approx((base_price, 0.0))++[email protected]("_loaded_catalog_prices")[email protected](("provider", "model", "optional_params"), MODE_CASES)+def test_a_runtime_price_on_the_generic_entry_keeps_applying_to_a_mode_without_a_runtime_price(+ monkeypatch: pytest.MonkeyPatch, provider: str, model: str, optional_params: Mapping[str, object]+) -> None:+ _register(monkeypatch, f"{provider}/search", 0.004)+ cost: Final = search_provider_cost_per_query(+ model=model, custom_llm_provider=provider, optional_params=optional_params+ )+ assert cost == pytest.approx((0.004, 0.0))++[email protected]("_loaded_catalog_prices")[email protected](("provider", "model", "optional_params"), MODE_CASES)+def test_a_runtime_price_on_the_mode_entry_wins_over_a_runtime_price_on_the_generic_entry(+ monkeypatch: pytest.MonkeyPatch, provider: str, model: str, optional_params: Mapping[str, object]+) -> None:+ _register(monkeypatch, f"{provider}/search", 0.004)+ _register(monkeypatch, _mode_entry(provider, optional_params), 0.011)+ cost: Final = search_provider_cost_per_query(+ model=model, custom_llm_provider=provider, optional_params=optional_params+ )+ assert cost == pytest.approx((0.011, 0.0))++[email protected]("_search_mode_prices")+def test_sync_tavily_advanced_search_reports_the_advanced_price(respx_mock: respx.MockRouter) -> None:+ respx_mock.post(TAVILY_SEARCH_URL).respond(json={"results": [{"title": "t", "url": "https://example.com"}]})+ response: Final = litellm.search(+ query="litellm release notes", search_provider="tavily", api_key="test-tavily-key", search_depth="advanced"+ )+ assert json.loads(respx_mock.calls.last.request.content)["search_depth"] == "advanced"+ assert response.hidden_params["response_cost"] == pytest.approx(0.007)++[email protected]("_search_mode_prices")+async def test_async_linkup_deep_search_reports_the_deep_price(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ respx_mock.post(LINKUP_SEARCH_URL).respond(+ json={"results": [{"type": "text", "name": "t", "url": "https://example.com", "content": "c"}]}+ )+ response: Final = await litellm.asearch(+ query="litellm release notes", search_provider="linkup", api_key="test-linkup-key", depth="deep"+ )+ assert json.loads(respx_mock.calls.last.request.content)["depth"] == "deep"+ assert response.hidden_params["response_cost"] == pytest.approx(0.011)