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
feat(cost): add model_info.pricing_provider for cost-map lookups (#47620)
Kerry Lu1380e7e921b4
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex 51f6a65307d..67178c8959c 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -1511,6 +1511,7 @@ def completion_cost(litellm_model_name: str | None = None,router_model_id: str | None = None,litellm_logging_obj: LitellmLoggingObject | None = None,+ pricing_provider: str | None = None,### SERVICE TIER ###service_tier: str | None = None, # for OpenAI service tier pricing### DATA RESIDENCY ###@@ -1531,6 +1532,8 @@ def completion_cost("""try:call_type = infer_call_type(call_type, completion_response) or "completion"+ if pricing_provider is not None:+ custom_llm_provider = pricing_provider # rebind-ok: model_info.pricing_provider overrides the routing provider for cost-map lookupsif call_type == CallTypes.aresponses_websocket.value and isinstance(completion_response, LiteLLMRealtimeStreamLoggingObject@@ -1556,6 +1559,7 @@ def completion_cost(optional_params=optional_params,custom_pricing=custom_pricing,base_model=base_model,+ pricing_provider=pricing_provider,standard_built_in_tools_params=standard_built_in_tools_params,litellm_model_name=litellm_model_name,router_model_id=router_model_id,@@ -1649,7 +1653,7 @@ def completion_cost(raw_candidates if custom_pricing is True else _priced_candidates_before_unpriced_rules(raw_candidates))- for idx, (model, pricing_provider) in enumerate(potential_model_names):+ for idx, (model, candidate_pricing_provider) in enumerate(potential_model_names):try:if verbose_logger.isEnabledFor(logging.DEBUG):verbose_logger.debug("selected model name for cost calculation: %s", model)@@ -1716,7 +1720,9 @@ def completion_cost(hidden_params = getattr(completion_response, "_hidden_params", None)if hidden_params is not None:- custom_llm_provider = hidden_params.get("custom_llm_provider", custom_llm_provider or None)+ custom_llm_provider = pricing_provider or hidden_params.get(+ "custom_llm_provider", custom_llm_provider or None+ )region_name = hidden_params.get("region_name", region_name)else:@@ -2002,7 +2008,7 @@ def completion_cost(prompt_tokens=prompt_tokens or 0,completion_tokens=completion_tokens or 0,custom_llm_provider=_pricing_provider_for_cost_candidate(- candidate_provider=pricing_provider,+ candidate_provider=candidate_pricing_provider,request_provider=request_pricing_provider,current_provider=custom_llm_provider,),@@ -2106,7 +2112,7 @@ def completion_cost(_token_type_breakdown = get_token_type_cost_breakdown(model=model,custom_llm_provider=_pricing_provider_for_cost_candidate(- candidate_provider=pricing_provider,+ candidate_provider=candidate_pricing_provider,request_provider=request_pricing_provider,current_provider=custom_llm_provider,),@@ -2229,6 +2235,7 @@ def response_cost_calculator(litellm_model_name: str | None = None,router_model_id: str | None = None,litellm_logging_obj: LitellmLoggingObject | None = None,+ pricing_provider: str | None = None,### SERVICE TIER ###service_tier: str | None = None, # for OpenAI service tier pricing### DATA RESIDENCY ###@@ -2269,6 +2276,7 @@ def response_cost_calculator(litellm_model_name=litellm_model_name,router_model_id=router_model_id,litellm_logging_obj=litellm_logging_obj,+ pricing_provider=pricing_provider,service_tier=service_tier,data_residency=data_residency,vertex_location=vertex_location,diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 0d851ed38c2..37df750b555 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -338,6 +338,7 @@ def _get_provider_request_id(original_exception: Exception) -> str | None:# Cache custom pricing keys as frozenset for O(1) lookups instead of looping through 49 keys_CUSTOM_PRICING_KEYS: Final[frozenset[str]] = frozenset(CustomPricingLiteLLMParams.model_fields.keys())+_METADATA_MAPPING: Final = TypeAdapter(Mapping[str, object])_MODEL_INFO_CUSTOM_PRICING_KEYS: Final[frozenset[str]] = _CUSTOM_PRICING_KEYS | DEPLOYMENT_SCOPED_PRICING_FIELDS_UNSERIALIZABLE_METADATA_KEYS: Final[frozenset[str]] = frozenset(("user_api_key_auth", "user_api_key_budget_reservation")@@ -996,6 +997,21 @@ class Logging(LiteLLMLoggingBaseClass):return model_idreturn None+ def get_router_pricing_provider(self) -> str | None:+ """The deployment's ``model_info.pricing_provider``, the provider its cost-map lookups run under."""+ litellm_params: Final = cast( # cast-ok: callback metadata is caller-provided+ Mapping[str, object] | None, getattr(self, "litellm_params", None)+ )+ if not litellm_params:+ return None+ candidates: Final = (+ _METADATA_MAPPING.validate_python(+ _METADATA_MAPPING.validate_python(litellm_params.get(key) or {}).get("model_info") or {}+ ).get("pricing_provider")+ for key in ("litellm_metadata", "metadata")+ )+ return next((provider for provider in candidates if isinstance(provider, str) and provider), None)+def _routed_deployment_model(self) -> str | None:litellm_params: Final = self._model_call_details_view.get("litellm_params")metadata: Final = (@@ -2021,6 +2037,7 @@ class Logging(LiteLLMLoggingBaseClass):"prompt": prompt,"standard_built_in_tools_params": self.standard_built_in_tools_params,"router_model_id": router_model_id,+ "pricing_provider": self.get_router_pricing_provider(),"litellm_logging_obj": self,"data_residency": (self.litellm_params.get("data_residency")@@ -2165,7 +2182,7 @@ class Logging(LiteLLMLoggingBaseClass):pricing: Final = pricing_entry_for_cost_calc(model=model,completion_response=result,- custom_llm_provider=custom_llm_provider,+ custom_llm_provider=self.get_router_pricing_provider() or custom_llm_provider,custom_pricing=self.custom_pricing_for(result),base_model=get_base_model_from_metadata(model_call_details=self.model_call_details),router_model_id=router_model_id or self.get_router_model_id(),diff --git a/litellm/router.py b/litellm/router.pyindex e04d7da8806..74facf200d2 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -11261,6 +11261,9 @@ class Router:if field_value is not None:model_info[field] = field_valuebackend_model: Final = Router._cost_map_backend_model(deployment)+ pricing_provider: Final = (+ deployment.model_info.pricing_provider or deployment.litellm_params.custom_llm_provider+ )params: Final = _LITELLM_PARAMS_ADAPTER.validate_python(deployment.litellm_params.model_dump(exclude_none=True))if (params.get("model_id")@@ -11280,23 +11283,23 @@ class Router:Router._inherit_builtin_base_rates_for_off_peak(model_info=model_info,backend_model=backend_model,- custom_llm_provider=deployment.litellm_params.custom_llm_provider,+ custom_llm_provider=pricing_provider,)if model_info.get("input_cost_per_token") is not None:Router._inherit_builtin_cache_pricing(model_info=model_info,backend_model=backend_model,- custom_llm_provider=deployment.litellm_params.custom_llm_provider,+ custom_llm_provider=pricing_provider,)Router._inherit_builtin_service_tier_pricing(model_info=model_info,backend_model=backend_model,- custom_llm_provider=deployment.litellm_params.custom_llm_provider,+ custom_llm_provider=pricing_provider,)Router._inherit_builtin_tiered_output_rate(model_info=model_info,backend_model=backend_model,- custom_llm_provider=deployment.litellm_params.custom_llm_provider,+ custom_llm_provider=pricing_provider,)return model_info@@ -11313,6 +11316,7 @@ class Router:model_info=Router._deployment_model_cost_payload(deployment),model=deployment.litellm_params.model,custom_llm_provider=deployment.litellm_params.custom_llm_provider,+ pricing_provider=deployment.model_info.pricing_provider,)@staticmethod@@ -11322,6 +11326,7 @@ class Router:model_info: dict, # mutable-ok: cost-map entrymodel: str,custom_llm_provider: str | None,+ pricing_provider: str | None = None,) -> None:"""Write a deployment's metadata into ``litellm.model_cost``.@@ -11345,7 +11350,7 @@ class Router:model_cost={model_id: model_info},persist_across_reloads=False,warning_display_name=model,- custom_llm_provider=custom_llm_provider,+ custom_llm_provider=pricing_provider or custom_llm_provider,add_to_provider_model_sets=False,)@@ -11387,6 +11392,7 @@ class Router:model_info=Router._deployment_model_cost_payload(deployment),model=deployment.litellm_params.model,custom_llm_provider=deployment.litellm_params.custom_llm_provider,+ pricing_provider=deployment.model_info.pricing_provider,)self._invalidate_model_group_info_cache()diff --git a/litellm/types/router.py b/litellm/types/router.pyindex 2618bf698ee..97b0d81d33b 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -274,6 +274,7 @@ class ModelInfo(MirroredPricingParams):created_by: str | None = Nonebase_model: str | None = None # specify if the base model is azure/gpt-3.5-turbo etc for accurate cost tracking+ pricing_provider: str | None = None # provider whose cost-map rows price this deployment, else custom_llm_providertier: Literal["free", "paid"] | None = None"""diff --git a/tests/unit/test_router_model_cost_isolation.py b/tests/unit/test_router_model_cost_isolation.pyindex 1655dac6382..426481d2719 100644--- a/tests/unit/test_router_model_cost_isolation.py+++ b/tests/unit/test_router_model_cost_isolation.py@@ -4318,3 +4318,100 @@ def test_router_capacity_reads_a_model_info_base_model_before_a_litellm_params_oassert _effective_max_input_tokens(router) == 1024assert _deployments_allowed_for_2048_input_tokens(router) == 0_invalidate_model_cost_lowercase_map()+++def test_deployment_id_equal_to_another_providers_catalog_key_bills_its_own_prices_under_pricing_provider() -> None:+ """Resolving the id by name under the routing provider lands on the other provider's row and the+ provider check rejects it, billing $0. ``pricing_provider`` names the row's provider, so the+ deployment's own prices (merged into that row) bill."""+ model_cost_entries: Final = {+ key: copy.deepcopy(litellm.model_cost.get(key))+ for key in (_COLLIDING_BUILTIN_KEY, _COLLIDING_SHARED_OPENAI_KEY)+ }+ try:+ router: Final = Router(+ model_list=[+ _pricing_provider_deployment(+ _COLLIDING_BUILTIN_KEY,+ {"input_cost_per_token": 0.00000096, "output_cost_per_token": 0.00000302},+ )+ ]+ )++ response: Final = _glm_completion(router)++ assert response._hidden_params["response_cost"] == pytest.approx(1000 * 0.00000096 + 500 * 0.00000302)+ finally:+ _restore_model_cost_entries(model_cost_entries)+ litellm.get_model_info.cache_clear()+++def _pricing_provider_deployment(model_id: str, model_info: dict) -> DeploymentTypedDict:+ litellm_params: Final = LiteLLMParamsTypedDict(+ model="zai-org/GLM-5.2",+ api_base="https://inference.baseten.co/v1",+ custom_llm_provider="openai",+ )+ return DeploymentTypedDict(+ model_name="nvidia/zai-org/glm-5.2",+ litellm_params=litellm_params,+ model_info={"id": model_id, "pricing_provider": "baseten", **model_info},+ )+++def _glm_completion(router: Router) -> litellm.ModelResponse:+ response: Final = router.completion(+ model="nvidia/zai-org/glm-5.2",+ messages=[{"role": "user", "content": "priced under another provider"}],+ mock_response=litellm.ModelResponse(+ model="zai-org/GLM-5.2",+ usage=litellm.Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500),+ ),+ )+ assert isinstance(response, litellm.ModelResponse)+ return response+++def test_pricing_provider_without_custom_prices_bills_that_providers_catalog_rate() -> None:+ """An openai-compatible deployment pointed at another provider's host can name that provider for+ pricing: the request is priced from its catalog row, where the routing provider has none."""+ model_id: Final = "glm52-priced-as-baseten"+ catalog_row: Final = litellm.model_cost[_COLLIDING_BUILTIN_KEY]+ model_cost_entries: Final = {+ key: copy.deepcopy(litellm.model_cost.get(key))+ for key in (model_id, _COLLIDING_BUILTIN_KEY, _COLLIDING_SHARED_OPENAI_KEY)+ }+ try:+ response: Final = _glm_completion(Router(model_list=[_pricing_provider_deployment(model_id, {})]))++ assert response._hidden_params["response_cost"] == pytest.approx(+ 1000 * catalog_row["input_cost_per_token"] + 500 * catalog_row["output_cost_per_token"]+ )+ finally:+ _restore_model_cost_entries(model_cost_entries)+ litellm.get_model_info.cache_clear()+++def test_pricing_provider_fills_unset_rates_from_that_providers_catalog_row() -> None:+ """Rates the deployment sets win, rates it leaves out come from the pricing provider's row for the+ backend model rather than defaulting to 0 because the routing provider has no row."""+ model_id: Final = "glm52-priced-as-baseten-custom"+ catalog_row: Final = copy.deepcopy(litellm.model_cost[_COLLIDING_BUILTIN_KEY])+ model_cost_entries: Final = {+ key: copy.deepcopy(litellm.model_cost.get(key))+ for key in (model_id, _COLLIDING_BUILTIN_KEY, _COLLIDING_SHARED_OPENAI_KEY)+ }+ rates: Final = {"input_cost_per_token": 0.00000096, "output_cost_per_token": 0.00000302}+ try:+ router: Final = Router(model_list=[_pricing_provider_deployment(model_id, rates)])++ registered: Final = litellm.model_cost[model_id]+ assert {key: registered[key] for key in rates} == rates+ assert registered["cache_read_input_token_cost"] == catalog_row["cache_read_input_token_cost"]+ assert _glm_completion(router)._hidden_params["response_cost"] == pytest.approx(+ 1000 * 0.00000096 + 500 * 0.00000302+ )+ assert litellm.model_cost[_COLLIDING_BUILTIN_KEY] == catalog_row+ finally:+ _restore_model_cost_entries(model_cost_entries)+ litellm.get_model_info.cache_clear()diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex e432c947116..4bd945b13ca 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -50135,6 +50135,8 @@ export interface components {output_cost_per_character?: number | null;/** Output Cost Per Token */output_cost_per_token?: number | null;+ /** Pricing Provider */+ pricing_provider?: string | null;/** Ptu Count */ptu_count?: number | null;/** Ptu Effective From */