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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_together_cache_pricing

mateo-berridbadee7210d0
diff --cc litellm/utils.py
index 59a2de609d7,b164a9c4671..b75d0161cb4
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@@ -2903,10 -3023,15 +3023,14 @@@ def register_model
elif (
value.get("cache_creation_input_token_cost") is None
and value.get("cache_read_input_token_cost") is None
+ and value.get("tiered_pricing") is None
+ and (
- value.get("input_cost_per_token") is not None
- or value.get("output_cost_per_token") is not None
++ value.get("input_cost_per_token") is not None or value.get("output_cost_per_token") is not None
+ )
):
verbose_logger.warning(
- "register_model: model=%s not in built-in cost map and no prefix/region variant matched; cache cost fields will default to 0. To track cache cost, add cache_creation_input_token_cost and cache_read_input_token_cost to model_info",
- key,
+ "register_model: model=%s has custom pricing but not in built-in cost map and no prefix/region variant matched; cache_creation_input_token_cost and cache_read_input_token_cost will default to 0 for this model (input/output cost tracking is unaffected). To track cache cost, add them to model_info",
+ warning_display_name or key,
)
# ``get_model_info`` returns ``litellm_provider: None`` when the
# provider is unknown (e.g. custom deployments registered via
diff --cc tests/test_litellm/test_cost_calculator.py
index edc0635a741,0c99d128e14..d42d83ce6d9
--- a/tests/test_litellm/test_cost_calculator.py
+++ b/tests/test_litellm/test_cost_calculator.py
@@@ -3783,71 -3977,308 +3977,376 @@@ def test_completion_cost_prices_anthrop
assert cost == pytest.approx(3 * 4e-6 + 4014 * 4e-7 + 5 * 2e-5, rel=1e-9)
+def _together_chat_response(model: str, prompt_tokens: int, completion_tokens: int, cached_tokens: int) -> ModelResponse:
+ return ModelResponse(
+ id="chatcmpl-together-cache",
+ choices=[{"finish_reason": "stop", "index": 0, "message": {"content": "acknowledged", "role": "assistant"}}],
+ created=1756164000,
+ model=model,
+ object="chat.completion",
+ usage=Usage(
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=prompt_tokens + completion_tokens,
+ prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=cached_tokens),
+ ),
+ )
+
+
+def test_completion_cost_prices_together_cached_tokens_at_cache_read_rate(_local_model_cost_map):
+ """Regression: Together reports prompt_tokens_details.cached_tokens but no together_ai
+ registry entry carried cache_read_input_token_cost, so cache-hit tokens were priced at
+ 0.0 and spend on cache-heavy workloads was understated."""
+
+ cost = completion_cost(
+ completion_response=_together_chat_response(
+ model="deepseek-ai/DeepSeek-V4-Flash-0731", prompt_tokens=7864, completion_tokens=16, cached_tokens=7863
+ ),
+ custom_llm_provider="together_ai",
+ )
+
+ assert cost == pytest.approx(1 * 1.4e-07 + 7863 * 3e-08 + 16 * 2.8e-07, rel=1e-9)
+
+
+def test_completion_cost_together_mapped_model_skips_size_bucket(_local_model_cost_map):
+ """Regression: any together model whose name matches (\\d+b) was rewritten to a
+ together-ai-* size bucket before the registry lookup, so mapped models like
+ Muse-Glimmer-30B never used their per-model rates, cache fields included."""
+
+ cost = completion_cost(
+ completion_response=_together_chat_response(
+ model="meta-models/Muse-Glimmer-30B", prompt_tokens=63, completion_tokens=16, cached_tokens=0
+ ),
+ custom_llm_provider="together_ai",
+ )
+
+ assert cost == pytest.approx(63 * 3.5e-07 + 16 * 1.5e-06, rel=1e-9)
+
+
+def test_completion_cost_together_unmapped_model_still_uses_size_bucket(_local_model_cost_map):
+ cost = completion_cost(
+ completion_response=_together_chat_response(
+ model="qwen/Qwen2-72B-Instruct", prompt_tokens=23, completion_tokens=15, cached_tokens=0
+ ),
+ custom_llm_provider="together_ai",
+ )
+
+ assert cost == pytest.approx((23 + 15) * 9e-07, rel=1e-9)
+
+
+def test_completion_cost_together_metadata_only_model_still_uses_size_bucket(_local_model_cost_map):
+ assert "input_cost_per_token" not in litellm.model_cost["together_ai/togethercomputer/CodeLlama-34b-Instruct"]
+
+ cost = completion_cost(
+ completion_response=_together_chat_response(
+ model="togethercomputer/CodeLlama-34b-Instruct", prompt_tokens=23, completion_tokens=15, cached_tokens=0
+ ),
+ custom_llm_provider="together_ai",
+ )
+
+ assert cost == pytest.approx((23 + 15) * 8e-07, rel=1e-9)
+ def test_select_model_name_strips_unregistered_alias_prefix(_local_model_cost_map):
+ """A router-facing model_name alias containing "/" whose leading segment is NOT a
+ registered provider must not be double-prefixed into a non-existent cost key.
+
+ Regression test for #38069: alias "vertex/claude-opus-5" (real deployment
+ "vertex_ai/claude-opus-5") was re-prefixed into "vertex_ai/vertex/claude-opus-5",
+ silently pricing every streamed request at $0.
+ """
+
+ from litellm.cost_calculator import _select_model_name_for_cost_calc
+
+ response = litellm.ModelResponse(
+ id="x",
+ choices=[
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ model="vertex/claude-opus-5",
+ )
+ response._hidden_params = {}
+
+ selected = _select_model_name_for_cost_calc(
+ model=None,
+ completion_response=response,
+ custom_llm_provider="vertex_ai",
+ )
+
+ assert selected == "vertex_ai/claude-opus-5"
+
+
+ def test_select_model_name_strips_duplicated_region_segment(_local_model_cost_map):
+ """A "region/model" alias whose leading segment repeats the request's region must
+ resolve to the region-priced cost key instead of keeping the region segment twice."""
+
+ from litellm.cost_calculator import _select_model_name_for_cost_calc
+
+ response = litellm.ModelResponse(
+ id="x",
+ choices=[
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ model="us-east-1/anthropic.claude-v2:1",
+ )
+ response._hidden_params = {"region_name": "us-east-1"}
+
+ selected = _select_model_name_for_cost_calc(
+ model=None,
+ completion_response=response,
+ custom_llm_provider="bedrock",
+ )
+
+ assert selected == "bedrock/us-east-1/anthropic.claude-v2:1"
+
+
+ def test_completion_cost_nonzero_for_slash_alias_model_name(_local_model_cost_map):
+ """End-to-end cost through a "/"-containing alias must price above zero (#38069)."""
+
+ response = litellm.ModelResponse(
+ id="x",
+ choices=[
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ model="vertex/claude-opus-5",
+ )
+ response._hidden_params = {"custom_llm_provider": "vertex_ai"}
+ response.usage = litellm.Usage(prompt_tokens=100, completion_tokens=50)
+
+ cost = litellm.completion_cost(
+ completion_response=response,
+ custom_llm_provider="vertex_ai",
+ )
+
+ assert cost == pytest.approx(100 * 5e-6 + 50 * 2.5e-5, rel=1e-9)
+
+
+ def test_select_model_name_unresolvable_alias_unchanged(_local_model_cost_map):
+ """An alias that resolves to no known cost key keeps the legacy double-prefixed name."""
+
+ from litellm.cost_calculator import _select_model_name_for_cost_calc
+
+ response = litellm.ModelResponse(
+ id="x",
+ choices=[
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ model="team/nonsense-model",
+ )
+ response._hidden_params = {}
+
+ selected = _select_model_name_for_cost_calc(
+ model=None,
+ completion_response=response,
+ custom_llm_provider="vertex_ai",
+ )
+
+ assert selected == "vertex_ai/team/nonsense-model"
+
+
+ def test_completion_cost_keeps_custom_priced_slash_router_id(_local_model_cost_map):
+ """A custom-priced router id containing "/" keeps its custom pricing instead of being
+ rewritten to the built-in key its suffix happens to match."""
+
+ from litellm.cost_calculator import _select_model_name_for_cost_calc
+
+ litellm.register_model(
+ model_cost={
+ "vertex/claude-opus-5": {
+ "input_cost_per_token": 7e-6,
+ "output_cost_per_token": 8e-6,
+ "litellm_provider": "vertex_ai",
+ }
+ }
+ )
+
+ selected = _select_model_name_for_cost_calc(
+ model="vertex_ai/claude-opus-5",
+ completion_response=None,
+ custom_pricing=True,
+ custom_llm_provider="vertex_ai",
+ router_model_id="vertex/claude-opus-5",
+ )
+ assert selected == "vertex_ai/vertex/claude-opus-5"
+
+ response = litellm.ModelResponse(
+ id="x",
+ choices=[
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ model="vertex/claude-opus-5",
+ )
+ response._hidden_params = {"custom_llm_provider": "vertex_ai"}
+ response.usage = litellm.Usage(prompt_tokens=100, completion_tokens=50)
+
+ cost = litellm.completion_cost(
+ completion_response=response,
+ custom_llm_provider="vertex_ai",
+ custom_pricing=True,
+ router_model_id="vertex/claude-opus-5",
+ )
+ assert cost == pytest.approx(100 * 7e-6 + 50 * 8e-6, rel=1e-9)
+
+
+ @pytest.mark.parametrize(
+ ("model", "expected_1hr_rate"),
+ [("claude-3-haiku-20240307", 5e-07), ("claude-3-opus-20240229", 3e-05)],
+ )
+ def test_claude_3_one_hour_cache_writes_bill_at_double_input(
+ _local_model_cost_map, model: str, expected_1hr_rate: float
+ ):
+ """Regression: both models carried the Sonnet 1h cache-write rate (6e-06) instead of
+ 2x their own input price, overbilling haiku 12x and underbilling opus 5x."""
+
+ usage = Usage(
+ prompt_tokens=1000,
+ completion_tokens=0,
+ total_tokens=1000,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=0,
+ cache_creation_tokens=1000,
+ cache_creation_token_details=CacheCreationTokenDetails(
+ ephemeral_5m_input_tokens=0, ephemeral_1h_input_tokens=1000
+ ),
+ ),
+ )
+
+ prompt_cost, _ = cost_per_token(model=model, usage_object=usage, custom_llm_provider="anthropic")
+
+ assert prompt_cost == pytest.approx(1000 * expected_1hr_rate, rel=1e-9)
+
+
+ def test_every_one_hour_cache_write_rate_is_double_its_input_rate():
+ """Guard against pasting one model's 1h cache-write price onto another: every provider
+ LiteLLM tracks (Anthropic, Bedrock, Vertex, Azure) publishes the 1h write at 2x input."""
+
+ cost_map = json.loads(
+ (Path(__file__).parents[2] / "model_prices_and_context_window.json").read_text()
+ )
+ one_hour_prefix = "cache_creation_input_token_cost_above_1hr"
+ deviations = {
+ (name, key): (entry["input_cost_per_token" + key[len(one_hour_prefix) :]], entry[key])
+ for name, entry in cost_map.items()
+ if isinstance(entry, dict)
+ for key in entry
+ if key.startswith(one_hour_prefix)
+ and entry[key] != pytest.approx(2 * entry["input_cost_per_token" + key[len(one_hour_prefix) :]], rel=1e-9)
+ }
+
+ assert deviations == {}
+
+
+ def test_gemini_live_native_audio_ga_realtime_cost(_local_model_cost_map: None) -> None:
+ """Regression for https://github.com/BerriAI/litellm/issues/31087."""
+ from litellm.types.utils import CompletionTokensDetailsWrapper
+
+ results: OpenAIRealtimeStreamList = [
+ {"type": "session.created", "session": {"model": "gemini-live-2.5-flash-native-audio"}},
+ ]
+ combined_usage_object = Usage(
+ prompt_tokens=8,
+ completion_tokens=25,
+ total_tokens=33,
+ prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=8, audio_tokens=0),
+ completion_tokens_details=CompletionTokensDetailsWrapper(text_tokens=2, audio_tokens=23),
+ )
+
+ cost = handle_realtime_stream_cost_calculation(
+ results=results,
+ combined_usage_object=combined_usage_object,
+ custom_llm_provider="vertex_ai",
+ litellm_model_name="vertex_ai/gemini-live-2.5-flash-native-audio",
+ )
+
+ expected_cost = 8 * 5e-07 + 2 * 2e-06 + 23 * 1.2e-05
+ assert cost == pytest.approx(expected_cost, rel=1e-9)
+
+
+ @pytest.mark.parametrize(
+ "priceless_entry",
+ [
+ {"litellm_provider": "vertex_ai", "mode": "realtime"},
+ {
+ "litellm_provider": "vertex_ai",
+ "mode": "realtime",
+ "input_cost_per_token": None,
+ "output_cost_per_token": None,
+ "input_cost_per_audio_token": None,
+ },
+ ],
+ ids=["registered_without_price_fields", "registered_with_none_valued_price_fields"],
+ )
+ def test_realtime_priceless_deployment_entry_falls_through_to_priced_model(
+ _local_model_cost_map: None, monkeypatch: pytest.MonkeyPatch, priceless_entry: dict
+ ) -> None:
+ """Regression for https://github.com/BerriAI/litellm/issues/31087 (router-registered priceless entries)."""
+ monkeypatch.setitem(
+ litellm.model_cost,
+ "vertex_ai/some-unmapped-live-model",
+ priceless_entry,
+ )
+ priced_model = "vertex_ai/gemini-live-2.5-flash-preview-native-audio-09-2025"
+ priced_entry = litellm.model_cost["gemini-live-2.5-flash-preview-native-audio-09-2025"]
+
+ results: OpenAIRealtimeStreamList = [
+ {"type": "session.created", "session": {"model": "some-unmapped-live-model"}},
+ ]
+ combined_usage_object = Usage(prompt_tokens=8, completion_tokens=25, total_tokens=33)
+
+ cost = handle_realtime_stream_cost_calculation(
+ results=results,
+ combined_usage_object=combined_usage_object,
+ custom_llm_provider="vertex_ai",
+ litellm_model_name=priced_model,
+ )
+
+ expected_cost = 8 * priced_entry["input_cost_per_token"] + 25 * priced_entry["output_cost_per_token"]
+ assert cost == pytest.approx(expected_cost, rel=1e-9)
+ assert cost > 0
+
+
+ def test_realtime_explicitly_free_session_model_still_bills_zero(
+ _local_model_cost_map: None, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setitem(
+ litellm.model_cost,
+ "vertex_ai/free-live-model",
+ {
+ "litellm_provider": "vertex_ai",
+ "mode": "realtime",
+ "input_cost_per_token": 0.0,
+ "output_cost_per_token": 0.0,
+ },
+ )
+
+ results: OpenAIRealtimeStreamList = [
+ {"type": "session.created", "session": {"model": "free-live-model"}},
+ ]
+ combined_usage_object = Usage(prompt_tokens=8, completion_tokens=25, total_tokens=33)
+
+ cost = handle_realtime_stream_cost_calculation(
+ results=results,
+ combined_usage_object=combined_usage_object,
+ custom_llm_provider="vertex_ai",
+ litellm_model_name="vertex_ai/gemini-live-2.5-flash-preview-native-audio-09-2025",
+ )
+
+ assert cost == 0.0