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]

fix(batches): keep published rates for a side the deployment leaves unset

Marty Sullivanb593cef75883
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 32143899125..c22ac9eb4c9 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -308,6 +308,14 @@ def _get_cached_prometheus_logger():
return _PrometheusLogger
+_DEPLOYMENT_PRICING_KEYS: Final = (
+ "input_cost_per_token",
+ "output_cost_per_token",
+ "input_cost_per_token_batches",
+ "output_cost_per_token_batches",
+)
+
+
class Logging(LiteLLMLoggingBaseClass):
global \
supabaseClient, \
@@ -602,24 +610,44 @@ class Logging(LiteLLMLoggingBaseClass):
caller falls back to the global cost map. The raw registration is what
decides that: the router registers an entry for every deployment, and
get_model_info fills absent costs with 0, so asking it directly cannot
- tell "configured as free" apart from "no pricing configured".
+ tell "configured as free" apart from "no pricing configured". A deployment
+ may declare only one side of its pricing, so a rate it leaves unset keeps
+ the model's published value instead of billing as zero.
"""
- pricing_keys: Final = (
- "input_cost_per_token",
- "output_cost_per_token",
- "input_cost_per_token_batches",
- "output_cost_per_token_batches",
- )
model_id: Final = self.get_router_model_id()
if model_id is None:
return None
registered: Final = litellm.model_cost.get(model_id)
- if not isinstance(registered, dict) or not any(registered.get(key) is not None for key in pricing_keys):
+ if not isinstance(registered, dict) or not any(
+ registered.get(key) is not None for key in _DEPLOYMENT_PRICING_KEYS
+ ):
return None
try:
- return litellm.get_model_info(model=model_id)
+ merged: Final = litellm.get_model_info(model=model_id)
except Exception: # noqa: BLE001 # get_model_info raises for ids it cannot resolve a provider for
return None
+ published: Final = self._published_model_info()
+ if published is None:
+ return merged
+ if registered.get("input_cost_per_token") is None:
+ merged["input_cost_per_token"] = published.get("input_cost_per_token")
+ if registered.get("output_cost_per_token") is None:
+ merged["output_cost_per_token"] = published.get("output_cost_per_token")
+ if registered.get("input_cost_per_token_batches") is None:
+ merged["input_cost_per_token_batches"] = published.get("input_cost_per_token_batches")
+ if registered.get("output_cost_per_token_batches") is None:
+ merged["output_cost_per_token_batches"] = published.get("output_cost_per_token_batches")
+ return merged
+
+ def _published_model_info(self) -> ModelInfo | None:
+ """The cost map's own entry for this deployment's model, when it resolves."""
+ deployment_model: Final = self.get_deployment_model_for_cost()
+ if deployment_model is None:
+ return None
+ try:
+ return litellm.get_model_info(model=deployment_model)
+ except Exception: # noqa: BLE001 # no published entry to layer the declared rates over
+ return None
def update_environment_variables(
self,
diff --git a/tests/test_litellm/batches/test_batch_utils.py b/tests/test_litellm/batches/test_batch_utils.py
index 033febabd45..177a4e354ca 100644
--- a/tests/test_litellm/batches/test_batch_utils.py
+++ b/tests/test_litellm/batches/test_batch_utils.py
@@ -1324,17 +1324,10 @@ async def test_output_file_content_bedrock_reads_with_deployment_aws_credentials
# =========================================================================== #
# _handle_completed_batch threads the deployment's model identity + pricing
-#
-# Regression: the retrieve path called _handle_completed_batch with neither
-# model_name nor model_info. For bedrock that left cost_model falling back to
-# the provider's own response model ("claude-sonnet-4-6"), which does not
-# resolve under custom_llm_provider="bedrock", so cost silently became $0 while
-# usage stayed correct. Dropping model_info separately discarded a deployment's
-# configured rates, billing a zero-cost deployment at the public rate.
# =========================================================================== #
-def _bedrock_row(model, input_tokens, output_tokens):
+def _bedrock_row(model: str, input_tokens: int, output_tokens: int) -> dict[str, object]:
return {
"modelInput": {"messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]},
"modelOutput": {
@@ -1356,11 +1349,11 @@ def _bedrock_row(model, input_tokens, output_tokens):
@pytest.mark.asyncio
-async def test_handle_completed_bedrock_batch_prices_from_deployment_model(monkeypatch):
+async def test_handle_completed_bedrock_batch_prices_from_deployment_model(monkeypatch) -> None:
"""A bedrock batch must price from the deployment model, not the response model."""
rows = [_bedrock_row("claude-sonnet-4-6", 18, 10)] * 100
- async def fake_fetch(batch, custom_llm_provider, litellm_params=None):
+ async def fake_fetch(batch: object, custom_llm_provider: str, litellm_params: dict | None = None) -> bytes:
return _vertex_jsonl(rows)
monkeypatch.setattr(bu, "_fetch_batch_output_file_content", fake_fetch)
@@ -1386,11 +1379,11 @@ async def test_handle_completed_bedrock_batch_prices_from_deployment_model(monke
@pytest.mark.asyncio
-async def test_handle_completed_batch_honors_deployment_pricing(monkeypatch):
+async def test_handle_completed_batch_honors_deployment_pricing(monkeypatch) -> None:
"""A deployment's configured rates must win over the global cost map."""
rows = [_success_row(model="gemini-2.5-flash", usage=_usage(60, 75))]
- async def fake_fetch(batch, custom_llm_provider, litellm_params=None):
+ async def fake_fetch(batch: object, custom_llm_provider: str, litellm_params: dict | None = None) -> bytes:
return _vertex_jsonl(rows)
monkeypatch.setattr(bu, "_fetch_batch_output_file_content", fake_fetch)
diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
index 3b5e8aaf1f8..4acbe276cf5 100644
--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
@@ -344,7 +344,7 @@ class TestGetRouterModelId:
class TestGetRouterDeploymentModelInfo:
"""Pricing a deployment registered under its own model_info.id."""
- def test_returns_registered_deployment_pricing(self, logging_obj):
+ def test_returns_registered_deployment_pricing(self, logging_obj) -> None:
deployment_id = "deploy-zero-cost-1"
litellm.model_cost[deployment_id] = {
"input_cost_per_token": 0.0,
@@ -363,11 +363,11 @@ class TestGetRouterDeploymentModelInfo:
finally:
litellm.model_cost.pop(deployment_id, None)
- def test_returns_none_for_unregistered_deployment(self, logging_obj):
+ def test_returns_none_for_unregistered_deployment(self, logging_obj) -> None:
logging_obj.litellm_params = {"litellm_metadata": {"model_info": {"id": "deploy-never-registered"}}}
assert logging_obj.get_router_deployment_model_info() is None
- def test_returns_none_when_deployment_registered_without_pricing(self, logging_obj):
+ def test_returns_none_when_deployment_registered_without_pricing(self, logging_obj) -> None:
"""The router registers an entry for EVERY deployment, priced or not.
get_model_info fills absent costs with 0, so consulting it directly would
@@ -385,10 +385,74 @@ class TestGetRouterDeploymentModelInfo:
finally:
litellm.model_cost.pop(deployment_id, None)
- def test_returns_none_without_a_deployment_id(self, logging_obj):
+ def test_returns_none_without_a_deployment_id(self, logging_obj) -> None:
logging_obj.litellm_params = {"api_base": ""}
assert logging_obj.get_router_deployment_model_info() is None
+ @pytest.mark.parametrize(
+ "declared,expected_input,expected_output",
+ [
+ ({"input_cost_per_token": 1e-06}, 1e-06, 1.5e-05),
+ ({"output_cost_per_token": 5e-06}, 3e-06, 5e-06),
+ ({"input_cost_per_token": 0.0, "output_cost_per_token": 0.0}, 0.0, 0.0),
+ ],
+ ids=["input-only", "output-only", "both-zero"],
+ )
+ def test_one_sided_override_keeps_the_published_rate_for_the_other_side(
+ self,
+ declared: dict[str, float],
+ expected_input: float,
+ expected_output: float,
+ ) -> None:
+ """A deployment may configure one direction only.
+
+ Substituting its pricing wholesale billed the direction it left unset at
+ zero, because get_model_info fills an absent cost with 0 and that
+ suppressed the global fallback.
+ """
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+
+ model = "bedrock/global.anthropic.claude-sonnet-4-6"
+ published = litellm.get_model_info(model=model)
+ assert (published["input_cost_per_token"], published["output_cost_per_token"]) == (3e-06, 1.5e-05)
+
+ deployment_id = f"deploy-one-sided-{'-'.join(sorted(declared))}"
+ litellm.model_cost[deployment_id] = {"id": deployment_id, **declared}
+ obj = LiteLLMLoggingObj(
+ model=model,
+ messages=[],
+ stream=False,
+ call_type="aretrieve_batch",
+ start_time=time.time(),
+ litellm_call_id="one-sided",
+ function_id="f",
+ )
+ obj.litellm_params = {"litellm_metadata": {"model_info": {"id": deployment_id}}, "model": model}
+ obj.model_call_details["model"] = model
+ try:
+ info = obj.get_router_deployment_model_info()
+ assert info is not None
+ assert info["input_cost_per_token"] == expected_input
+ assert info["output_cost_per_token"] == expected_output
+ finally:
+ litellm.model_cost.pop(deployment_id, None)
+
+ def test_falls_back_to_declared_rates_when_the_model_has_no_published_entry(self, logging_obj) -> None:
+ """With no published entry to layer under, the declared rates still apply."""
+ deployment_id = "deploy-unpublished-model-1"
+ litellm.model_cost[deployment_id] = {"id": deployment_id, "input_cost_per_token": 7e-06}
+ logging_obj.litellm_params = {
+ "litellm_metadata": {"model_info": {"id": deployment_id}},
+ "model": "not-a-real-provider/not-a-real-model-xyz",
+ }
+ logging_obj.model_call_details["model"] = "not-a-real-provider/not-a-real-model-xyz"
+ try:
+ info = logging_obj.get_router_deployment_model_info()
+ assert info is not None
+ assert info["input_cost_per_token"] == 7e-06
+ finally:
+ litellm.model_cost.pop(deployment_id, None)
+
class TestRetrieveBatchCostPassesModelIdentity:
"""Regression: retrieving a batch priced it with no model identity at all.
@@ -400,7 +464,7 @@ class TestRetrieveBatchCostPassesModelIdentity:
"""
@pytest.mark.asyncio
- async def test_forwards_deployment_model_and_pricing(self, monkeypatch):
+ async def test_forwards_deployment_model_and_pricing(self, monkeypatch) -> None:
from litellm.litellm_core_utils import litellm_logging as logging_module
from litellm.types.utils import LiteLLMBatch, Usage
@@ -412,9 +476,9 @@ class TestRetrieveBatchCostPassesModelIdentity:
"mode": "chat",
}
- captured: dict = {}
+ captured: dict[str, object] = {}
- async def fake_handle_completed_batch(**kwargs):
+ async def fake_handle_completed_batch(**kwargs: object) -> tuple[float, Usage, list[str]]:
captured.update(kwargs)
return 1.25, Usage(prompt_tokens=1800, completion_tokens=1000, total_tokens=2800), ["m"]