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(ptu): stop per-token billing on a PTU-configured deployment (#36829)

yucheng-berri0a25756e782b
diff --git a/litellm/constants.py b/litellm/constants.py
index e9d2d719ae2..6449834d6a4 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1745,6 +1745,9 @@ PTU_ROLLUP_LOCK_TTL_SECONDS: Final[int] = 900
# Furthest back the catch-up pass looks for unpriced PTU days when a deployment
# declares no ptu_effective_from, bounding the scan for an open-ended window.
PTU_ROLLUP_MAX_BACKFILL_DAYS: Final[int] = 90
+# Deployments named in the lapsed-window alert before it is truncated, so a fleet-wide
+# expiry cannot produce an alert too large for the channel delivering it.
+PTU_LAPSED_ALERT_LIMIT: Final[int] = 10
# Slack allowed when deciding a sentinel row is stale. The row's updated_at and the
# run's cutoff are stamped by different hosts, so clock skew between them must not let
# one run delete a charge another just wrote. A stale row is hours old and a concurrent
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 0239368ad0e..51050e62494 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -14,6 +14,7 @@ import math
import re
import time
from collections.abc import Iterator, Mapping, Sequence
+from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Protocol, cast
from fastapi import HTTPException, Request, status
@@ -376,6 +377,16 @@ def _is_model_cost_zero(model: str | list[str] | None, llm_router: Router | None
zero_cost_cache[model_name] = False
return False
+ if _has_ptu_flat_cost(model_name, llm_router):
+ verbose_proxy_logger.debug(
+ "Model %s prices reserved PTU capacity as a flat cost, so its zero per-token "
+ "rate is not a free model (enforce budget)",
+ safe_name,
+ )
+ if zero_cost_cache is not None:
+ zero_cost_cache[model_name] = False
+ return False
+
verbose_proxy_logger.debug(
"Model %s has zero cost explicitly configured (input: %s, output: %s)",
safe_name,
@@ -394,6 +405,24 @@ def _is_model_cost_zero(model: str | list[str] | None, llm_router: Router | None
return True
+_NO_MODEL_INFO: Final[Mapping[str, object]] = MappingProxyType({})
+
+
+def _has_ptu_flat_cost(model: str, llm_router: "Router") -> bool:
+ """Whether any deployment in the model group bills reserved PTU capacity as a flat cost.
+
+ Such a deployment carries an explicit zero per-token price so the flat cost is not charged
+ twice, which otherwise reads here as a free model and waives every budget check for it.
+ """
+ for deployment in llm_router.model_list:
+ if deployment.get("model_name") != model:
+ continue
+ model_info = deployment.get("model_info") or _NO_MODEL_INFO
+ if model_info.get("ptu_count") is not None and model_info.get("cost_per_ptu_per_hour") is not None:
+ return True
+ return False
+
+
def _is_cost_explicitly_configured(model: str, llm_router: "Router") -> bool:
"""
Check if any deployment in the model group has cost fields explicitly
diff --git a/litellm/proxy/management_endpoints/model_management_endpoints.py b/litellm/proxy/management_endpoints/model_management_endpoints.py
index 4bc72f554b1..912e18150b3 100644
--- a/litellm/proxy/management_endpoints/model_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/model_management_endpoints.py
@@ -89,6 +89,7 @@ from litellm.types.router import (
ModelInfo,
updateDeployment,
)
+from litellm.types.utils import CustomPricingLiteLLMParams
from litellm.utils import get_utc_datetime
router: Final = APIRouter()
@@ -242,6 +243,7 @@ def _raise_on_strategy_router_write_violation(
_PTU_MODEL_INFO_FIELDS: Final = ("ptu_count", "cost_per_ptu_per_hour", "ptu_effective_from", "ptu_effective_to")
+_PTU_PRICED_PAIR: Final = frozenset({"ptu_count", "cost_per_ptu_per_hour"})
def _explicitly_cleared_ptu_fields(model_info: ModelInfo | None) -> frozenset[str]:
@@ -265,9 +267,10 @@ def _merged_ptu_model_info(*, db_model: Deployment, patch_data: updateDeployment
A PTU invariant holds over the deployment as it will exist, not over whichever subset
of fields a caller happened to send.
"""
- empty: Final[Mapping[str, object]] = MappingProxyType({})
- stored: Final = db_model.model_info.model_dump(exclude_none=True) if db_model.model_info else empty
- incoming: Final = patch_data.model_info.model_dump(exclude_none=True) if patch_data.model_info else empty
+ stored: Final = db_model.model_info.model_dump(exclude_none=True) if db_model.model_info else _EMPTY_MODEL_INFO
+ incoming: Final = (
+ patch_data.model_info.model_dump(exclude_none=True) if patch_data.model_info else _EMPTY_MODEL_INFO
+ )
cleared: Final = _explicitly_cleared_ptu_fields(patch_data.model_info)
return MappingProxyType({k: v for k, v in {**stored, **incoming}.items() if k not in cleared})
@@ -339,6 +342,140 @@ def _validate_ptu_model_info(model_info: Mapping[str, object]) -> None:
)
+# The six mirrored pricing fields plus the three remaining fields
+# Router._inherit_builtin_cache_pricing back-fills from the public cost map. An unset field is
+# what that back-fill targets, so a field left out here is one a PTU deployment still bills.
+_PTU_ZEROED_PRICING_FIELDS: Final = SPECIAL_MODEL_INFO_PARAMS + (
+ "cache_creation_input_token_cost_above_1hr",
+ "cache_creation_input_token_cost_above_200k_tokens",
+ "cache_read_input_token_cost_above_200k_tokens",
+)
+_PTU_ZEROED_PRICING: Final[Mapping[str, float]] = MappingProxyType(dict.fromkeys(_PTU_ZEROED_PRICING_FIELDS, 0.0))
+_NO_PRICING_OVERRIDE: Final[Mapping[str, float]] = MappingProxyType({})
+_EMPTY_MODEL_INFO: Final[Mapping[str, object]] = _NO_PRICING_OVERRIDE
+# Rate fields only. CustomPricingLiteLLMParams also carries settings that are not charges
+# (an embedding's output_vector_size, the regional uplift multipliers), and zeroing one of
+# those would destroy the deployment's configuration rather than stop a charge.
+_CUSTOM_PRICING_FIELDS: Final = frozenset(f for f in CustomPricingLiteLLMParams.model_fields if "cost" in f)
+
+
+def _is_nonzero_price(value: object) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and value != 0
+
+
+def _is_zero_price(value: object) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and value == 0
+
+
+def _raise_if_ptu_deployment_is_priced(*, model_info: Mapping[str, object], supplied: Mapping[str, object]) -> None:
+ """Refuse a rate the caller supplies for a deployment that bills reserved capacity.
+
+ Separate from the zeroing so the team-model path can run it before it touches the team, whose
+ ACL write autocommits: a refusal raised after it would leave the team changed and the
+ deployment row never written.
+ """
+ if not is_ptu_cost_attribution_enabled():
+ return
+ if model_info.get("ptu_count") is None or model_info.get("cost_per_ptu_per_hour") is None:
+ return
+ priced: Final = tuple(sorted(field for field in _CUSTOM_PRICING_FIELDS if _is_nonzero_price(supplied.get(field))))
+ if not priced:
+ return
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"A PTU deployment bills by reserved capacity, so {', '.join(priced)} cannot be charged on "
+ "top of it. Send 0 or no value, or remove ptu_count and cost_per_ptu_per_hour to bill per token."
+ ),
+ )
+
+
+def _ptu_zeroed_pricing(
+ *,
+ model_info: Mapping[str, object],
+ litellm_params: Mapping[str, object],
+ supplied: Mapping[str, object],
+) -> Mapping[str, float]:
+ """The pricing a PTU deployment must carry, empty unless one is being stored.
+
+ Reserved capacity is already billed by the flat cost the rollup writes, so charging the
+ traffic it serves bills the same tokens twice. Left unset the rate falls back to the public
+ cost map, which makes the double charge the default rather than an opt-in.
+
+ Only a price the caller supplies is refused. A non-zero price already on the row is zeroed
+ instead, so a deployment priced through a path this rule does not cover heals on its next
+ save rather than rejecting every later edit of a field that has nothing to do with pricing.
+
+ ``supplied`` is the caller's litellm_params alone, because that is the blob a price is
+ authored on. model_info's copy is written by the server, both by the mirror in
+ ``Deployment.__init__`` and by the cost-map defaults /model/info fills in, so a client that
+ round-trips a model_info blob sends back prices it never chose.
+ """
+ if not is_ptu_cost_attribution_enabled():
+ return _NO_PRICING_OVERRIDE
+ if model_info.get("ptu_count") is None or model_info.get("cost_per_ptu_per_hour") is None:
+ return _NO_PRICING_OVERRIDE
+ _raise_if_ptu_deployment_is_priced(model_info=model_info, supplied=supplied)
+ stored: Final = frozenset(
+ field
+ for field in _CUSTOM_PRICING_FIELDS
+ if _is_nonzero_price(model_info.get(field)) or _is_nonzero_price(litellm_params.get(field))
+ )
+ if not stored:
+ return _PTU_ZEROED_PRICING
+ return MappingProxyType({**_PTU_ZEROED_PRICING, **dict.fromkeys(stored, 0.0)})
+
+
+def _ptu_pricing_delta(
+ *,
+ stored_model_info: Mapping[str, object],
+ model_info: Mapping[str, object],
+ litellm_params: Mapping[str, object],
+ patch: updateDeployment,
+) -> tuple[Mapping[str, float], frozenset[str]]:
+ """The pricing a patch must write into both blobs, and the pricing it must drop from them.
+
+ A patch that takes the deployment off PTU takes the zeroed pricing with it, since the zeros
+ exist only to stop the double charge. Left behind they would serve the deployment for free.
+ Reading the stored row rather than the patch alone keeps that release off a deployment that
+ never carried PTU config, whose zero price is a rate its operator chose. A zero the patch
+ itself carries is released with the rest, because the dashboard echoes the whole stored
+ blob on every save, so a supplied zero cannot be told apart from the one this rule wrote.
+
+ The release spans every field the zeroing could have written, not just the mirrored ones, or
+ a rate zeroed on the way in (per-second, per-character tiers) would bill nothing forever.
+ """
+ supplied: Final = patch.litellm_params.model_dump(exclude_none=True) if patch.litellm_params else _EMPTY_MODEL_INFO
+ zeroed: Final = _ptu_zeroed_pricing(model_info=model_info, litellm_params=litellm_params, supplied=supplied)
+ if zeroed:
+ return zeroed, frozenset()
+ was_ptu: Final = any(stored_model_info.get(field) is not None for field in _PTU_PRICED_PAIR)
+ if not was_ptu or not _explicitly_cleared_ptu_fields(patch.model_info) & _PTU_PRICED_PAIR:
+ return _NO_PRICING_OVERRIDE, frozenset()
+ return _NO_PRICING_OVERRIDE, frozenset(
+ field
+ for field in _CUSTOM_PRICING_FIELDS.union(_PTU_ZEROED_PRICING_FIELDS)
+ if _is_zero_price(model_info.get(field)) or _is_zero_price(litellm_params.get(field))
+ )
+
+
+def _ptu_priced_deployment(model_params: Deployment) -> Deployment:
+ """``model_params`` with PTU pricing applied, or itself when it configures no PTU."""
+ model_info: Final = model_params.model_info.model_dump(exclude_none=True)
+ litellm_params: Final = model_params.litellm_params.model_dump(exclude_none=True)
+ override: Final = _ptu_zeroed_pricing(model_info=model_info, litellm_params=litellm_params, supplied=litellm_params)
+ if not override:
+ return model_params
+ return model_params.model_copy(
+ update=MappingProxyType(
+ {
+ "litellm_params": model_params.litellm_params.model_copy(update=override),
+ "model_info": model_params.model_info.model_copy(update=override),
+ }
+ )
+ )
+
+
def _parse_ptu_datetime(value: object) -> datetime.datetime | None:
"""``value`` as a datetime, parsing an ISO string, else None."""
if isinstance(value, datetime.datetime):
@@ -404,6 +541,19 @@ def update_db_model(db_model: Deployment, updated_patch: updateDeployment) -> Pr
merged_model_info.pop(field, None)
_validate_ptu_model_info(merged_model_info)
+ ptu_pricing, ptu_released = _ptu_pricing_delta(
+ stored_model_info=db_model.model_info.model_dump(exclude_none=True)
+ if db_model.model_info
+ else _EMPTY_MODEL_INFO,
+ model_info=merged_model_info,
+ litellm_params=merged_litellm_params,
+ patch=updated_patch,
+ )
+ merged_model_info.update(ptu_pricing)
+ merged_litellm_params.update(ptu_pricing)
+ for field in ptu_released:
+ merged_model_info.pop(field, None)
+ merged_litellm_params.pop(field, None)
# convert to prisma compatible format
@@ -863,6 +1013,12 @@ async def _update_team_model_in_db(
if patch_data.model_info is not None:
_raise_if_ptu_cost_attribution_disabled(patch_data.model_info.model_dump(exclude_none=True))
_validate_ptu_model_info(_merged_ptu_model_info(db_model=db_model, patch_data=patch_data))
+ _raise_if_ptu_deployment_is_priced(
+ model_info=_merged_ptu_model_info(db_model=db_model, patch_data=patch_data),
+ supplied=(
+ patch_data.litellm_params.model_dump(exclude_none=True) if patch_data.litellm_params else _EMPTY_MODEL_INFO
+ ),
+ )
patch_team_id: Final = patch_data.model_info.team_id if patch_data.model_info else None
@@ -1589,6 +1745,7 @@ async def add_new_model(
incoming_model_info: Final = model_params.model_info.model_dump(exclude_none=True)
_raise_if_ptu_cost_attribution_disabled(incoming_model_info)
_validate_ptu_model_info(incoming_model_info)
+ priced_model_params: Final = _ptu_priced_deployment(model_params)
if store_model_in_db is True:
"""
@@ -1602,13 +1759,13 @@ async def add_new_model(
_original_litellm_model_name: Final = model_params.model_name
if model_params.model_info.team_id is None:
model_response = await _add_model_to_db(
- model_params=model_params,
+ model_params=priced_model_params,
user_api_key_dict=user_api_key_dict,
prisma_client=prisma_client,
)
else:
model_response = await _add_team_model_to_db(
- model_params=model_params,
+ model_params=priced_model_params,
user_api_key_dict=user_api_key_dict,
prisma_client=prisma_client,
)
@@ -1620,9 +1777,9 @@ async def add_new_model(
if "slack" in _alerting:
# send notification - new model added
await proxy_logging_obj.slack_alerting_instance.model_added_alert(
- model_name=model_params.model_name,
+ model_name=priced_model_params.model_name,
litellm_model_name=_original_litellm_model_name,
- passed_model_info=model_params.model_info,
+ passed_model_info=priced_model_params.model_info,
)
except Exception as e:
verbose_proxy_logger.exception("Exception in add_new_model: %s", e)
diff --git a/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py b/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py
index 029648f7901..efdbda47fdc 100644
--- a/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py
+++ b/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py
@@ -21,6 +21,7 @@ from typing import TYPE_CHECKING, Final
from litellm._logging import verbose_proxy_logger
from litellm.constants import (
+ PTU_LAPSED_ALERT_LIMIT,
PTU_PRUNE_SKEW_GRACE_SECONDS,
PTU_ROLLUP_JOB_ID,
PTU_ROLLUP_LOCK_TTL_SECONDS,
@@ -45,6 +46,7 @@ class RollupResult:
models_processed: int
rows_written: int
rows_failed: int = 0
+ lapsed: tuple[str, ...] = ()
@dataclass(frozen=True, slots=True)
@@ -387,6 +389,34 @@ async def run_ptu_flat_cost_rollup(
models_processed=len(ptu_models),
rows_written=rows_written,
rows_failed=rows_failed,
+ lapsed=_lapsed_models(ptu_models, run_started),
+ )
+
+
+def _slack_safe(model_name: str) -> str:
+ """``model_name`` with the characters Slack reads as markup escaped.
+
+ A model name is operator-supplied and this alert is delivered to an operator channel, so an
+ unescaped name could post a channel-wide mention or a disguised link.
+ """
+ return model_name.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+
+def _lapsed_models(ptu_models: tuple[PTUModel, ...], now: datetime) -> tuple[str, ...]:
+ """PTU deployments whose window has closed, newest bound first.
+
+ The provider bills reserved capacity until the deployment is deleted, so a closed window
+ stops this attribution without stopping the charge. The deployment is left alone: the
+ window is what the operator asked to be attributed, and per-token pricing would invent a
+ charge the provider does not make for reserved capacity.
+ """
+ return tuple(
+ _slack_safe(model.model_name)
+ for model in sorted(
+ (m for m in ptu_models if m.effective_to is not None and m.effective_to <= now),
+ key=lambda m: m.effective_to,
+ reverse=True,
+ )
)
@@ -585,6 +615,14 @@ async def _run_and_alert(
f"{result.rows_written + result.rows_failed} team charges failed to write. Those teams show no PTU "
f"cost for that date until the rollup is rerun for it.",
)
+ if result.lapsed:
+ await _deliver_alert(
+ alert,
+ f"PTU flat-cost attribution has stopped for {len(result.lapsed)} deployment(s) whose effective "
+ f"window has closed: {', '.join(result.lapsed[:PTU_LAPSED_ALERT_LIMIT])}. Reserved capacity is billed "
+ "until the deployment is deleted, so a deployment still serving traffic is still being charged for "
+ "by the provider with nothing attributing it here. Extend the window, or retire the deployment.",
+ )
if target_date is None:
await _backfill_and_alert(prisma_client, alert=alert)
return result
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.py b/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.py
index 178e9379ea7..6e670e48b6a 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.py
@@ -4,6 +4,7 @@ import datetime
import json
from contextlib import ExitStack
from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import patch as patch_ctx
import pytest
from fastapi import HTTPException
@@ -14,15 +15,28 @@ from litellm.proxy._types import (
ReconcileOutcome,
UserAPIKeyAuth,
)
+from litellm.proxy.auth.auth_checks import _is_model_cost_zero
from litellm.proxy.management_endpoints.model_management_endpoints import (
+ _PTU_ZEROED_PRICING_FIELDS,
_merged_ptu_model_info,
+ _update_team_model_in_db,
+ _ptu_priced_deployment,
+ _ptu_zeroed_pricing,
_raise_if_ptu_cost_attribution_disabled,
_validate_ptu_model_info,
add_new_model,
update_db_model,
)
from litellm.proxy.spend_tracking.ptu_feature_flag import PTU_COST_ATTRIBUTION_ENV_VAR
-from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo, updateDeployment
+from litellm.router import Router
+from litellm.types.router import (
+ SPECIAL_MODEL_INFO_PARAMS,
+ Deployment,
+ LiteLLM_Params,
+ ModelInfo,
+ updateDeployment,
+ updateLiteLLMParams,
+)
def test_model_info_accepts_valid_ptu_fields():
@@ -717,3 +731,390 @@ class TestAddNewModelPtuGate:
assert result.model_id == "ptu-gate-model"
add_team_model_to_db.assert_called_once()
+
+
+
+class TestPtuDeploymentsAreNotBilledPerToken:
+ """Reserved capacity is billed by the flat cost the rollup writes, so a PTU deployment must
+ not also bill the traffic that capacity serves."""
+
+ PTU = {"ptu_count": 15, "cost_per_ptu_per_hour": 2.0}
+
+ @pytest.fixture(autouse=True)
+ def _flag_on(self, monkeypatch):
+ monkeypatch.setenv(PTU_COST_ATTRIBUTION_ENV_VAR, "true")
+ # update_db_model encrypts every litellm_params value it is handed, and the salt falls
+ # back to the master key the proxy sets at boot, which no unit test has.
+ monkeypatch.setenv("LITELLM_SALT_KEY", "test-salt-key")
+
+ @staticmethod
+ def _zeroed(model_info=None, litellm_params=None, supplied=None):
+ return _ptu_zeroed_pricing(
+ model_info=model_info if model_info is not None else {},
+ litellm_params=litellm_params if litellm_params is not None else {},
+ supplied=supplied if supplied is not None else {},
+ )
+
+ def test_a_deployment_without_ptu_config_keeps_its_pricing(self):
+ assert self._zeroed(model_info={"team_id": "t"}, litellm_params={"input_cost_per_token": 5e-07}) == {}
+
+ def test_a_half_set_pair_is_not_treated_as_ptu(self):
+ assert self._zeroed(model_info={"ptu_count": 15}) == {}
+
+ def test_every_field_the_cost_map_could_fill_is_zeroed(self):
+ assert self._zeroed(model_info=self.PTU) == dict.fromkeys(_PTU_ZEROED_PRICING_FIELDS, 0.0)
+
+ def test_nothing_is_zeroed_while_the_feature_is_disabled(self, monkeypatch):
+ monkeypatch.delenv(PTU_COST_ATTRIBUTION_ENV_VAR, raising=False)
+ assert self._zeroed(model_info=self.PTU) == {}
+
+ @pytest.mark.parametrize("field", ["input_cost_per_token", "cache_read_input_token_cost", "input_cost_per_second"])
+ def test_a_price_the_caller_supplies_is_refused(self, field):
+ """Every custom-pricing field, not only the mirrored ones: per-second pricing bills a
+ PTU deployment just as surely as per-token pricing does."""
+ with pytest.raises(HTTPException) as exc:
+ self._zeroed(model_info=self.PTU, supplied={field: 5e-07})
+ assert exc.value.status_code == 400
+ assert field in str(exc.value.detail)
+
+ def test_a_price_the_caller_supplies_as_zero_is_accepted(self):
+ assert self._zeroed(model_info={**self.PTU, "input_cost_per_token": 0}, supplied={"input_cost_per_token": 0})[
+ "input_cost_per_token"
+ ] == 0
+
+ def test_a_price_already_on_the_row_is_zeroed_rather_than_refused(self):
+ """A row priced through a path this rule does not cover must heal on its next save. The
+ alternative refuses every later edit of a field that has nothing to do with pricing."""
+ zeroed = self._zeroed(model_info={**self.PTU, "input_cost_per_second": 3.0}, litellm_params={})
+ assert zeroed["input_cost_per_second"] == 0
+ assert zeroed["input_cost_per_token"] == 0
+
+ @pytest.mark.asyncio
+ async def test_a_refused_price_does_not_leave_the_team_changed(self):
+ """The team ACL write autocommits, so the refusal has to run before it. Otherwise a
+ rejected edit grants the team a model whose settings were never saved."""
+ db_model = Deployment(
+ model_name="gpt-4o",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o"),
+ model_info=ModelInfo(
+ id="dep-0",
+ team_id="team-1",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ ),
+ )
+ patch = updateDeployment(
+ litellm_params=updateLiteLLMParams(model="openai/gpt-4o", input_cost_per_token=5e-07),
+ model_info=ModelInfo(id="dep-0", team_id="team-2"),
+ )
+ endpoints = "litellm.proxy.management_endpoints.model_management_endpoints"
+ setup_new = AsyncMock()
+ update_existing = AsyncMock()
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch_ctx(f"{endpoints}.ModelManagementAuthChecks.allow_team_model_action", AsyncMock(return_value=True))
+ )
+ stack.enter_context(patch_ctx(f"{endpoints}._setup_new_team_model_assignment", setup_new))
+ stack.enter_context(patch_ctx(f"{endpoints}._update_existing_team_model_assignment", update_existing))
+ stack.enter_context(patch_ctx("litellm.proxy.proxy_server.premium_user", True))
+ with pytest.raises(HTTPException) as exc:
+ await _update_team_model_in_db(
+ db_model=db_model,
+ patch_data=patch,
+ user_api_key_dict=UserAPIKeyAuth(user_id="a", user_role=LitellmUserRoles.PROXY_ADMIN),
+ prisma_client=MagicMock(),
+ )
+
+ assert exc.value.status_code == 400
+ setup_new.assert_not_called()
+ update_existing.assert_not_called()
+
+ def test_a_setting_that_is_not_a_charge_is_left_alone(self):
+ """CustomPricingLiteLLMParams also carries an embedding's output vector size and the
+ regional uplift multipliers. Zeroing one of those destroys the deployment's config, and
+ refusing it answers with a message calling a setting a charge."""
+ priced = _ptu_priced_deployment(
+ Deployment(
+ model_name="embeddings",
+ litellm_params=LiteLLM_Params(
+ model="azure/text-embedding-3-large",
+ output_vector_size=1536,
+ regional_processing_uplift_multiplier_eu=1.15,
+ ),
+ model_info=ModelInfo(
+ id="dep-emb",
+ team_id="team-1",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ ),
+ )
+ )
+ assert priced.litellm_params.get("output_vector_size") == 1536
+ assert priced.litellm_params.get("regional_processing_uplift_multiplier_eu") == 1.15
+ assert priced.litellm_params.get("input_cost_per_token") == 0
+
+ def test_removing_ptu_config_releases_every_rate_it_zeroed(self):
+ """The zeroing covers any stored rate, so a release that only spans the mirrored fields
+ leaves a per-second deployment billing nothing for that dimension forever."""
+ on = update_db_model(
+ db_model=Deployment(
+ model_name="audio",
+ litellm_params=LiteLLM_Params(model="azure/whisper", input_cost_per_second=0.006),
+ model_info=ModelInfo(id="dep-audio", team_id="t"),
+ ),
+ updated_patch=updateDeployment(
+ model_info=ModelInfo(
+ id="dep-audio",
+ team_id="t",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ )
+ ),
+ )
+ assert json.loads(on["litellm_params"])["input_cost_per_second"] == 0
+
+ off = update_db_model(
+ db_model=Deployment(
+ model_name="audio",
+ litellm_params=LiteLLM_Params(**json.loads(on["litellm_params"])),
+ model_info=ModelInfo(**json.loads(on["model_info"])),
+ ),
+ updated_patch=updateDeployment(
+ model_info=ModelInfo(id="dep-audio", ptu_count=None, cost_per_ptu_per_hour=None)
+ ),
+ )
+ assert "input_cost_per_second" not in json.loads(off["litellm_params"])
+
+ @pytest.mark.parametrize(
+ "backend", ["azure/gpt-4o", "anthropic/claude-sonnet-4-5", "bedrock/anthropic.claude-sonnet-4-20250514-v1:0"]
+ )
+ def test_the_cost_map_contributes_no_price_to_a_priced_ptu_deployment(self, backend):
+ """The acceptance criterion, read off the entry the router registers for the deployment.
+
+ Zeroing only the per-token pair leaves the cache-tier fields unset, which is exactly what
+ Router._inherit_builtin_cache_pricing back-fills from the public cost map, so a cached
+ prompt would still be billed at the public rate."""
+ priced = _ptu_priced_deployment(
+ Deployment(
+ model_name="ptu-deployment",
+ litellm_params=LiteLLM_Params(model=backend, api_key="fake-key"),
+ model_info=ModelInfo(
+ id="dep-ptu",
+ team_id="team-1",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ ),
+ )
+ )
+ registered = Router._deployment_model_cost_payload(priced)
+ charged = {k: v for k, v in registered.items() if "cost" in k and k != "cost_per_ptu_per_hour" and v}
+ assert charged == {}
+
+ def test_the_zeroed_pricing_does_not_waive_budget_enforcement(self):
+ """A zero price otherwise tells auth the model is free and skips every budget check."""
+ priced = _ptu_priced_deployment(
+ Deployment(
+ model_name="model_name_team-1_dep-ptu",
+ litellm_params=LiteLLM_Params(model="gemini/gemini-2.5-flash", api_key="fake-key"),
+ model_info=ModelInfo(
+ id="dep-ptu",
+ team_id="team-1",
+ team_public_model_name="ptu-model",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ ),
+ )
+ )
+ router = Router(model_list=[priced.to_json(exclude_none=True)])
+ assert _is_model_cost_zero(model="model_name_team-1_dep-ptu", llm_router=router) is False
+ assert _is_model_cost_zero(model="ptu-model", llm_router=router) is False
+
+ def test_an_unrelated_patch_heals_a_deployment_stored_before_this_rule(self):
+ """Both blobs, because litellm_params wins over model_info wherever the two are merged."""
+ written = update_db_model(
+ db_model=_deployment_with_stored_ptu(),
+ updated_patch=updateDeployment(model_name="gpt-4o-renamed"),
+ )
+ for blob in ("model_info", "litellm_params"):
+ stored = json.loads(written[blob])
+ assert all(stored[field] == 0 for field in _PTU_ZEROED_PRICING_FIELDS), blob
+
+ def test_an_unrelated_patch_of_a_ptu_row_that_carries_a_price_is_not_refused(self):
+ """The pause toggle and the credential-rotation modal send no pricing at all. Refusing
+ them because the stored row is mispriced blocks flows that cannot fix it."""
+ priced_ptu = Deployment(
+ model_name="gpt-4o",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o", input_cost_per_token=5e-07),
+ model_info=ModelInfo(
+ id="dep-0",
+ team_id="t",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ ),
+ )
+ written = update_db_model(db_model=priced_ptu, updated_patch=updateDeployment(model_name="renamed"))
+ assert written["model_name"] == "renamed"
+ assert json.loads(written["litellm_params"])["input_cost_per_token"] == 0
+
+ def test_removing_ptu_config_hands_per_token_billing_back(self):
+ """Left behind, the zeros this rule wrote would serve the deployment for free forever."""
+ zeros = dict.fromkeys(_PTU_ZEROED_PRICING_FIELDS, 0.0)
+ written = update_db_model(
+ db_model=Deployment(
+ model_name="gpt-4o",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o", **zeros),
+ model_info=ModelInfo(
+ id="dep-0",
+ team_id="t",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ **zeros,
+ ),
+ ),
+ updated_patch=updateDeployment(
+ model_info=ModelInfo(id="dep-0", ptu_count=None, cost_per_ptu_per_hour=None)
+ ),
+ )
+ for blob in ("model_info", "litellm_params"):
+ stored = json.loads(written[blob])
+ assert not any(field in stored for field in _PTU_ZEROED_PRICING_FIELDS), blob
+
+ def test_the_dashboard_clear_releases_the_zeros_it_echoes_back(self):
+ """The edit form re-sends the whole stored model_info on every save, so the clearing
+ patch carries the zeros this rule wrote. Treating those as a rate the operator chose
+ left the deployment serving free and reading as a free model to the budget checks."""
+ zeros = dict.fromkeys(_PTU_ZEROED_PRICING_FIELDS, 0.0)
+ written = update_db_model(
+ db_model=Deployment(
+ model_name="gpt-4o",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o", **zeros),
+ model_info=ModelInfo(
+ id="dep-0",
+ team_id="t",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ **zeros,
+ ),
+ ),
+ updated_patch=updateDeployment(
+ model_info=ModelInfo(id="dep-0", ptu_count=None, cost_per_ptu_per_hour=None, **zeros)
+ ),
+ )
+ stored = json.loads(written["model_info"])
+ assert not any(field in stored for field in _PTU_ZEROED_PRICING_FIELDS)
+
+ def test_a_deployment_that_never_had_ptu_keeps_a_price_its_operator_set_to_zero(self):
+ """The dashboard sends both PTU keys as null on every save while the feature is on, so a
+ release keyed on the patch alone would strip a deliberate zero rate from any model."""
+ free = Deployment(
+ model_name="free-model",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o", input_cost_per_token=0.0),
+ model_info=ModelInfo(id="dep-free", team_id="t", input_cost_per_token=0.0),
+ )
+ written = update_db_model(
+ db_model=free,
+ updated_patch=updateDeployment(
+ model_info=ModelInfo(id="dep-free", ptu_count=None, cost_per_ptu_per_hour=None)
+ ),
+ )
+ for blob in ("model_info", "litellm_params"):
+ assert json.loads(written[blob])["input_cost_per_token"] == 0, blob
+
+ def test_a_patch_pricing_a_ptu_deployment_is_refused(self):
+ with pytest.raises(HTTPException) as exc:
+ update_db_model(
+ db_model=_deployment_with_stored_ptu(),
+ updated_patch=updateDeployment(
+ litellm_params=updateLiteLLMParams(model="openai/gpt-4o", input_cost_per_token=5e-07)
+ ),
+ )
+ assert exc.value.status_code == 400
+
+ def test_a_price_the_client_only_echoes_back_is_not_read_as_an_attempt_to_charge(self):
+ """/model/info fills missing rates from the public cost map and the edit form re-sends the
+ whole blob, so a model_info price is one the server wrote. Reading it as the operator's
+ refused every attempt to put an existing deployment on PTU from the dashboard."""
+ written = update_db_model(
+ db_model=_deployment_without_ptu(),
+ updated_patch=updateDeployment(
+ model_info=ModelInfo(
+ id="dep-0",
+ team_id="t",
+ input_cost_per_token=3e-07,
+ output_cost_per_token=2.5e-06,
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ )
+ ),
+ )
+ stored = json.loads(written["model_info"])
+ assert stored["ptu_count"] == 15
+ assert stored["input_cost_per_token"] == 0
+ assert stored["output_cost_per_token"] == 0
+
+ def test_adding_ptu_config_to_an_already_priced_deployment_is_refused(self):
+ priced = Deployment(
+ model_name="gpt-4o",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o"),
+ model_info=ModelInfo(id="dep-0", team_id="t"),
+ )
+ with pytest.raises(HTTPException) as exc:
+ update_db_model(
+ db_model=priced,
+ updated_patch=updateDeployment(
+ litellm_params=updateLiteLLMParams(model="openai/gpt-4o", input_cost_per_token=5e-07),
+ model_info=ModelInfo(
+ id="dep-0",
+ team_id="t",
+ ptu_effective_from=datetime.datetime(2020, 1, 1, tzinfo=datetime.timezone.utc),
+ **self.PTU,
+ ),
+ ),
+ )
+ assert exc.value.status_code == 400
+
+ def test_a_deployment_without_ptu_config_keeps_its_pricing_through_a_patch(self):
+ priced = Deployment(
+ model_name="gpt-4o",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o"),
+ model_info=ModelInfo(id="dep-0", team_id="t", input_cost_per_token=5e-07),
+ )
+ stored = json.loads(
+ update_db_model(db_model=priced, updated_patch=updateDeployment(model_name="renamed"))["model_info"]
+ )
+ assert stored["input_cost_per_token"] == 5e-07
+
+ @pytest.mark.asyncio
+ async def test_model_new_stores_zero_pricing_on_both_blobs(self):
+ (_, add_team_model_to_db), patches = TestAddNewModelPtuGate._patched_proxy("ptu-priced-model")
+ admin = UserAPIKeyAuth(user_id="test-admin", user_role=LitellmUserRoles.PROXY_ADMIN)
+
+ with ExitStack() as stack:
+ for active_patch in patches:
+ stack.enter_context(active_patch)
+ await add_new_model(
+ model_params=TestAddNewModelPtuGate._ptu_deployment("ptu-priced-model"),
+ user_api_key_dict=admin,
+ )
+
+ written = add_team_model_to_db.call_args.kwargs["model_params"]
+ assert all(getattr(written.model_info, field, None) == 0 for field in SPECIAL_MODEL_INFO_PARAMS)
+ assert all(written.litellm_params.get(field) == 0 for field in _PTU_ZEROED_PRICING_FIELDS)
+
+ @pytest.mark.asyncio
+ async def test_model_new_refuses_a_priced_ptu_deployment(self):
+ (_, add_team_model_to_db), patches = TestAddNewModelPtuGate._patched_proxy("ptu-priced-model")
+ admin = UserAPIKeyAuth(user_id="test-admin", user_role=LitellmUserRoles.PROXY_ADMIN)
+ base = TestAddNewModelPtuGate._ptu_deployment("ptu-priced-model")
+ deployment = base.model_copy(
+ update={"litellm_params": base.litellm_params.model_copy(update={"input_cost_per_token": 5e-07})}
+ )
+
+ with ExitStack() as stack:
+ for active_patch in patches:
+ stack.enter_context(active_patch)
+ with pytest.raises(Exception) as exc:
+ await add_new_model(model_params=deployment, user_api_key_dict=admin)
+
+ assert "input_cost_per_token" in str(exc.value)
+ add_team_model_to_db.assert_not_called()
diff --git a/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py b/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py
index d17f6293cc3..736fc13d137 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py
@@ -657,6 +657,87 @@ async def test_scheduled_rollup_stays_quiet_when_every_charge_landed():
alert.assert_not_awaited()
+async def test_scheduled_rollup_alerts_once_a_ptu_window_has_closed():
+ """Reserved capacity is billed until the deployment is deleted, so a closed window stops
+ the attribution without stopping the charge. Nobody notices unless it is escalated."""
+ ptu = {
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "t",
+ "ptu_effective_from": "2020-01-01T00:00:00Z",
+ "ptu_effective_to": "2020-02-01T00:00:00Z",
+ }
+ prisma, _ = _prisma_with_models([_model_row(model_id="dep-lapsed", model_info=ptu)])
+ alert = AsyncMock()
+
+ result = await run_scheduled_ptu_rollup(prisma, target_date=DAY, alert=alert)
+
+ assert result.lapsed == ("gpt-4o-mini-ptu",)
+ alert.assert_awaited_once()
+ message = alert.await_args.args[0]
+ assert "window has closed" in message
+ assert "gpt-4o-mini-ptu" in message
+
+
+async def test_a_model_name_cannot_smuggle_slack_markup_into_the_alert():
+ """The alert lands in an operator channel and a model name is operator-supplied, so an
+ unescaped name could post a channel-wide mention."""
+ ptu = {
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "t",
+ "ptu_effective_from": "2020-01-01T00:00:00Z",
+ "ptu_effective_to": "2020-02-01T00:00:00Z",
+ }
+ row = _model_row(model_id="dep-x", model_name="<!channel> & <https://evil.example|click>", model_info=ptu)
+ prisma, _ = _prisma_with_models([row])
+ alert = AsyncMock()
+
+ await run_scheduled_ptu_rollup(prisma, target_date=DAY, alert=alert)
+
+ message = alert.await_args.args[0]
+ assert "<!channel>" not in message
+ assert "&lt;!channel&gt;" in message
+
+
+async def test_an_open_ptu_window_raises_no_lapsed_alert():
+ ptu = {
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "t",
+ "ptu_effective_from": "2020-01-01T00:00:00Z",
+ "ptu_effective_to": "2999-01-01T00:00:00Z",
+ }
+ prisma, _ = _prisma_with_models([_model_row(model_id="dep-open", model_info=ptu)])
+ alert = AsyncMock()
+
+ result = await run_scheduled_ptu_rollup(prisma, target_date=DAY, alert=alert)
+
+ assert result.lapsed == ()
+ alert.assert_not_awaited()
+
+
+async def test_an_open_ended_ptu_window_raises_no_lapsed_alert():
+ """No end bound means the operator never asked the attribution to stop."""
+ ptu = {
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "t",
+ "ptu_effective_from": "2020-01-01T00:00:00Z",
+ }
+ prisma, _ = _prisma_with_models([_model_row(model_id="dep-forever", model_info=ptu)])
+ alert = AsyncMock()
+
+ result = await run_scheduled_ptu_rollup(prisma, target_date=DAY, alert=alert)
+
+ assert result.lapsed == ()
+ alert.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_a_broken_alert_channel_does_not_fail_the_rollup():
rows = [_model_row(model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})]
diff --git a/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx b/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx
index 5d7196a84fe..df20924d321 100644
--- a/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx
@@ -14,6 +14,7 @@ import {
PTU_RATE_FIELD,
PTU_START_FIELD,
ptuCountRules,
+ ptuNoUsageCostRule,
ptuPairRule,
ptuRateRules,
ptuStartRequiredRule,
@@ -261,7 +262,8 @@ const AdvancedSettings: React.FC<AdvancedSettingsProps> = ({
<Form.Item
label="Input Cost (per 1M tokens)"
name="input_cost_per_token"
- rules={[{ validator: validateNumber }]}
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={[{ validator: validateNumber }, ptuNoUsageCostRule(PTU_COUNT_FIELD)]}
className="mb-4"
>
<TextInput />
@@ -269,7 +271,8 @@ const AdvancedSettings: React.FC<AdvancedSettingsProps> = ({
<Form.Item
label="Output Cost (per 1M tokens)"
name="output_cost_per_token"
- rules={[{ validator: validateNumber }]}
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={[{ validator: validateNumber }, ptuNoUsageCostRule(PTU_COUNT_FIELD)]}
className="mb-4"
>
<TextInput />
@@ -277,7 +280,8 @@ const AdvancedSettings: React.FC<AdvancedSettingsProps> = ({
<Form.Item
label="Cache Read Cost (per 1M tokens)"
name="cache_read_input_token_cost"
- rules={[{ validator: validateNumber }]}
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={[{ validator: validateNumber }, ptuNoUsageCostRule(PTU_COUNT_FIELD)]}
tooltip="If left blank, defaults to Input Cost."
className="mb-4"
>
@@ -286,7 +290,8 @@ const AdvancedSettings: React.FC<AdvancedSettingsProps> = ({
<Form.Item
label="Cache Write Cost (per 1M tokens)"
name="cache_creation_input_token_cost"
- rules={[{ validator: validateNumber }]}
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={[{ validator: validateNumber }, ptuNoUsageCostRule(PTU_COUNT_FIELD)]}
tooltip="If left blank, defaults to Input Cost (the backend falls back to input_cost_per_token when no cache-write rate is set)."
className="mb-4"
>
@@ -297,7 +302,8 @@ const AdvancedSettings: React.FC<AdvancedSettingsProps> = ({
<Form.Item
label="Cost Per Second"
name="input_cost_per_second"
- rules={[{ validator: validateNumber }]}
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={[{ validator: validateNumber }, ptuNoUsageCostRule(PTU_COUNT_FIELD)]}
className="mb-4"
>
<TextInput />
diff --git a/ui/litellm-dashboard/src/components/model_info_view.test.tsx b/ui/litellm-dashboard/src/components/model_info_view.test.tsx
index a3ce40494eb..5eb17fee2c4 100644
--- a/ui/litellm-dashboard/src/components/model_info_view.test.tsx
+++ b/ui/litellm-dashboard/src/components/model_info_view.test.tsx
@@ -617,9 +617,14 @@ describe("ModelInfoView", () => {
describe("PTU cost attribution gate", () => {
const ptuModelData = {
...defaultModelData,
+ // Zero per-token pricing is what the backend stores for a PTU deployment, since the flat
+ // cost of its reserved capacity already covers the traffic that capacity serves.
+ litellm_params: { ...defaultModelData.litellm_params, input_cost_per_token: 0, output_cost_per_token: 0 },
model_info: {
...defaultModelData.model_info,
team_id: "team-1",
+ input_cost_per_token: 0,
+ output_cost_per_token: 0,
ptu_count: 15,
cost_per_ptu_per_hour: 2,
ptu_effective_from: "2026-07-01T00:00:00+00:00",
@@ -683,6 +688,70 @@ describe("ModelInfoView", () => {
expect(modelInfo).not.toHaveProperty("ptu_effective_to");
});
+ it("shows a zeroed PTU price as 0.0000 rather than Not Set", async () => {
+ mockUsePtuCostAttributionEnabled.mockReturnValue(true);
+ renderWithPtuModel();
+
+ await waitFor(() => {
+ expect(screen.getByText("Input Cost (per 1M tokens)")).toBeInTheDocument();
+ });
+ for (const label of ["Input Cost (per 1M tokens)", "Output Cost (per 1M tokens)"]) {
+ expect(screen.getByText(label).parentElement).toHaveTextContent("0.0000");
+ }
+ });
+
+ it("blocks the save once the operator types a non-zero per-token cost alongside PTU config", async () => {
+ mockUsePtuCostAttributionEnabled.mockReturnValue(true);
+ const user = userEvent.setup();
+ renderWithPtuModel();
+
+ await waitFor(() => {
+ expect(screen.getByRole("button", { name: /edit settings/i })).toBeInTheDocument();
+ });
+ await user.click(screen.getByRole("button", { name: /edit settings/i }));
+
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("Enter input cost")).toBeInTheDocument();
+ });
+ await user.clear(screen.getByPlaceholderText("Enter input cost"));
+ await user.type(screen.getByPlaceholderText("Enter input cost"), "2.5");
+ await user.click(screen.getByRole("button", { name: /save changes/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText(/bills by reserved capacity/i)).toBeInTheDocument();
+ });
+ expect(mockModelPatchUpdateCall).not.toHaveBeenCalled();
+ });
+
+ it("lets the operator put a cost-map-priced deployment on PTU without clearing the seeded rate", async () => {
+ // A rate the form seeded from /model/info is the server's own, so refusing it blocked
+ // every attempt to enable PTU from the dashboard.
+ mockUsePtuCostAttributionEnabled.mockReturnValue(true);
+ const seededModel = {
+ ...defaultModelData,
+ model_info: { ...defaultModelData.model_info, team_id: "team-1", input_cost_per_token: 0.0000003 },
+ };
+ mockUseModelsInfo.mockReturnValue({ data: { data: [seededModel] }, isLoading: false, error: null });
+ mockModelInfoV1Call.mockResolvedValue({ data: [seededModel] });
+ const user = userEvent.setup();
+ render(<ModelInfoView {...DEFAULT_ADMIN_PROPS} />, { wrapper });
+
+ await waitFor(() => {
+ expect(screen.getByRole("button", { name: /edit settings/i })).toBeInTheDocument();
+ });
+ await user.click(screen.getByRole("button", { name: /edit settings/i }));
+
+ await waitFor(() => {
+ expect(screen.getByPlaceholderText("e.g. 15")).toBeInTheDocument();
+ });
+ await user.type(screen.getByPlaceholderText("e.g. 15"), "15");
+ await user.click(screen.getByRole("button", { name: /save changes/i }));
+
+ await waitFor(() => {
+ expect(screen.queryByText(/bills by reserved capacity/i)).not.toBeInTheDocument();
+ });
+ });
+
it("sends the PTU fields on save when enabled", async () => {
mockUsePtuCostAttributionEnabled.mockReturnValue(true);
const user = userEvent.setup();
diff --git a/ui/litellm-dashboard/src/components/model_info_view.tsx b/ui/litellm-dashboard/src/components/model_info_view.tsx
index e1a4d4311ab..a0c545e17aa 100644
--- a/ui/litellm-dashboard/src/components/model_info_view.tsx
+++ b/ui/litellm-dashboard/src/components/model_info_view.tsx
@@ -25,6 +25,7 @@ import {
PTU_COUNT_FIELD,
PTU_RATE_FIELD,
ptuCountRules,
+ ptuNoUsageCostRule,
ptuPairRule,
ptuRateRules,
ptuStartRequiredRule,
@@ -128,6 +129,12 @@ const PTU_EDIT_FIELDS: PtuEditField[] = [
},
];
+/** Per-1M-token rate for the first rate that is set, so a deliberate 0 seeds the form as 0. */
+const perMillionTokens = (...rates: (number | null | undefined)[]): number | null => {
+ const rate = rates.find((candidate) => candidate != null);
+ return rate == null ? null : rate * 1_000_000;
+};
+
const ptuFieldDependencies = ({ isStart, pairedWith, windowPeer }: PtuEditField): string[] | undefined => {
const deps = [
...(isStart ? [PTU_COUNT_FIELD] : []),
@@ -227,6 +234,8 @@ export default function ModelInfoView({
const { data: modelHubData } = useModelHub();
const { data: teams } = useTeams();
const ptuCostAttributionEnabled = usePtuCostAttributionEnabled();
+ const ptuCostRule = (field: string) =>
+ ptuCostAttributionEnabled ? [ptuNoUsageCostRule(PTU_COUNT_FIELD, field)] : [];
// Transform the model data
const getProviderFromModel = (model: string) => {
@@ -835,12 +844,14 @@ export default function ModelInfoView({
max_retries: localModelData.litellm_params.max_retries,
timeout: localModelData.litellm_params.timeout,
stream_timeout: localModelData.litellm_params.stream_timeout,
- input_cost: localModelData.litellm_params.input_cost_per_token
- ? localModelData.litellm_params.input_cost_per_token * 1_000_000
- : localModelData.model_info?.input_cost_per_token * 1_000_000 || null,
- output_cost: localModelData.litellm_params?.output_cost_per_token
- ? localModelData.litellm_params.output_cost_per_token * 1_000_000
- : localModelData.model_info?.output_cost_per_token * 1_000_000 || null,
+ input_cost: perMillionTokens(
+ localModelData.litellm_params.input_cost_per_token,
+ localModelData.model_info?.input_cost_per_token,
+ ),
+ output_cost: perMillionTokens(
+ localModelData.litellm_params?.output_cost_per_token,
+ localModelData.model_info?.output_cost_per_token,
+ ),
ptu_count: localModelData.model_info?.ptu_count ?? null,
cost_per_ptu_per_hour: localModelData.model_info?.cost_per_ptu_per_hour ?? null,
ptu_effective_from: utcIsoToPickerValue(localModelData.model_info?.ptu_effective_from),
@@ -917,14 +928,19 @@ export default function ModelInfoView({
<div>
<Text className="font-medium">Input Cost (per 1M tokens)</Text>
{isEditing ? (
- <Form.Item name="input_cost" className="mb-0">
+ <Form.Item
+ name="input_cost"
+ className="mb-0"
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={ptuCostRule("input_cost")}
+ >
<NumericalInput placeholder="Enter input cost" />
</Form.Item>
) : (
<div className="mt-1 p-2 bg-gray-50 rounded-sm">
- {localModelData?.litellm_params?.input_cost_per_token
- ? (localModelData.litellm_params?.input_cost_per_token * 1_000_000).toFixed(4)
- : localModelData?.model_info?.input_cost_per_token
+ {localModelData?.litellm_params?.input_cost_per_token != null
+ ? (localModelData.litellm_params.input_cost_per_token * 1_000_000).toFixed(4)
+ : localModelData?.model_info?.input_cost_per_token != null
? (localModelData.model_info.input_cost_per_token * 1_000_000).toFixed(4)
: "Not Set"}
</div>
@@ -934,14 +950,19 @@ export default function ModelInfoView({
<div>
<Text className="font-medium">Output Cost (per 1M tokens)</Text>
{isEditing ? (
- <Form.Item name="output_cost" className="mb-0">
+ <Form.Item
+ name="output_cost"
+ className="mb-0"
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={ptuCostRule("output_cost")}
+ >
<NumericalInput placeholder="Enter output cost" />
</Form.Item>
) : (
<div className="mt-1 p-2 bg-gray-50 rounded-sm">
- {localModelData?.litellm_params?.output_cost_per_token
+ {localModelData?.litellm_params?.output_cost_per_token != null
? (localModelData.litellm_params.output_cost_per_token * 1_000_000).toFixed(4)
- : localModelData?.model_info?.output_cost_per_token
+ : localModelData?.model_info?.output_cost_per_token != null
? (localModelData.model_info.output_cost_per_token * 1_000_000).toFixed(4)
: "Not Set"}
</div>
@@ -995,6 +1016,8 @@ export default function ModelInfoView({
<Form.Item
name="cache_read_cost"
className="mb-0"
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={ptuCostRule("cache_read_cost")}
tooltip="If left blank on save, defaults to Input Cost."
>
<NumericalInput placeholder="Defaults to Input Cost if blank" />
@@ -1018,6 +1041,8 @@ export default function ModelInfoView({
<Form.Item
name="cache_write_cost"
className="mb-0"
+ dependencies={[PTU_COUNT_FIELD]}
+ rules={ptuCostRule("cache_write_cost")}
tooltip="If left blank on save, defaults to Input Cost (backend falls back to input_cost_per_token)."
>
<NumericalInput placeholder="Defaults to Input Cost if blank" />
diff --git a/ui/litellm-dashboard/src/utils/ptuValidation.test.ts b/ui/litellm-dashboard/src/utils/ptuValidation.test.ts
index 1338c2a39ae..ed30e6a7b20 100644
--- a/ui/litellm-dashboard/src/utils/ptuValidation.test.ts
+++ b/ui/litellm-dashboard/src/utils/ptuValidation.test.ts
@@ -3,6 +3,7 @@ import {
PTU_COUNT_FIELD,
PTU_RATE_FIELD,
ptuCountRules,
+ ptuNoUsageCostRule,
ptuPairRule,
ptuRateRules,
ptuStartRequiredRule,
@@ -40,6 +41,39 @@ describe("ptuCountRules", () => {
});
});
+describe("ptuNoUsageCostRule", () => {
+ const check = (value: unknown, count: unknown) =>
+ ptuNoUsageCostRule(PTU_COUNT_FIELD)({ getFieldValue: () => count }).validator(null, value);
+
+ it("leaves a deployment without PTU config free to carry any price", async () => {
+ await expect(check("2.5", "")).resolves.toBeUndefined();
+ await expect(check(0.5, null)).resolves.toBeUndefined();
+ });
+
+ it("accepts a blank or zero price alongside PTU config, which is what the backend stores", async () => {
+ await expect(check("", 15)).resolves.toBeUndefined();
+ await expect(check(null, 15)).resolves.toBeUndefined();
+ await expect(check(0, 15)).resolves.toBeUndefined();
+ await expect(check("0", 15)).resolves.toBeUndefined();
+ });
+
+ it("rejects a non-zero price alongside PTU config, which the backend answers with a 400", async () => {
+ await expect(check("2.5", 15)).rejects.toThrow("bills by reserved capacity");
+ await expect(check(0.000001, 15)).rejects.toThrow("bills by reserved capacity");
+ });
+
+ it("reads the count by the field name it was given", () => {
+ const seen: string[] = [];
+ ptuNoUsageCostRule(PTU_COUNT_FIELD)({
+ getFieldValue: (name: string) => {
+ seen.push(name);
+ return 15;
+ },
+ }).validator(null, 0);
+ expect(seen).toEqual([PTU_COUNT_FIELD]);
+ });
+});
+
describe("ptuPairRule", () => {
const rule = (sibling: unknown) => ptuPairRule(PTU_RATE_FIELD)({ getFieldValue: () => sibling });
const check = (value: unknown, sibling: unknown) => rule(sibling).validator(null, value);
diff --git a/ui/litellm-dashboard/src/utils/ptuValidation.ts b/ui/litellm-dashboard/src/utils/ptuValidation.ts
index 9fabf39ae23..da367f233b6 100644
--- a/ui/litellm-dashboard/src/utils/ptuValidation.ts
+++ b/ui/litellm-dashboard/src/utils/ptuValidation.ts
@@ -4,6 +4,7 @@ interface ValidatorRule {
interface FormInstance {
getFieldValue: (name: string) => unknown;
+ isFieldTouched?: (name: string) => boolean;
}
export const PTU_COUNT_FIELD = "ptu_count";
@@ -71,6 +72,25 @@ export const ptuPairRule =
: Promise.reject(new Error("PTU Count and Cost per PTU / Hour must be set together")),
});
+/**
+ * A PTU deployment is billed by the flat cost of its reserved capacity, so the backend refuses
+ * a non-zero per-token price alongside PTU config and stores 0 when none is given. Pair this
+ * with `dependencies` on the count so the error clears once the price or the PTU config goes.
+ */
+export const ptuNoUsageCostRule =
+ (countField: string, thisField?: string) =>
+ ({ getFieldValue, isFieldTouched }: FormInstance): ValidatorRule => ({
+ validator: (_, value) => {
+ // A cost the operator never typed was seeded from the rate /model/info resolved, which
+ // for an unpriced deployment is the public cost map. Refusing it would block every
+ // attempt to put an existing deployment on PTU, and the save omits it anyway.
+ const echoed = thisField !== undefined && isFieldTouched !== undefined && !isFieldTouched(thisField);
+ return echoed || !isFilled(getFieldValue(countField)) || !isFilled(value) || Number(value) === 0
+ ? Promise.resolve()
+ : Promise.reject(new Error("A PTU deployment bills by reserved capacity, so this cost must be 0 or blank"));
+ },
+ });
+
/**
* The backend requires an effective start whenever PTU is configured, since flat cost
* accrues from that instant and an inferred start would bill days a deployment did not