From 62aa21e810eb8d88c6c925176e084c7a5ce31022 Mon Sep 17 00:00:00 2001 From: kerry Date: Tue, 15 Sep 2026 21:34:00 +0000 Subject: [PATCH 1/6] test: drop remaining tests that pin cost-map vendor facts Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../llm_cost_calc/test_llm_cost_calc_utils.py | 1820 ++--------------- .../test_get_model_cost_map.py | 105 - ...azure_ai_foundry_catalog_model_metadata.py | 54 +- ..._cross_region_inference_profile_mapping.py | 176 +- .../llms/cohere/ocr/test_cohere_parse_cost.py | 44 - .../test_databricks_cost_calculator.py | 52 - .../databricks/test_databricks_pricing.py | 51 - .../test_fireworks_ai_cost_calculator.py | 55 +- .../test_fireworks_ai_kimi_model_metadata.py | 65 - ...mini_audio_transcription_transformation.py | 13 - .../llms/mistral/ocr/test_mistral_ocr_cost.py | 128 -- .../llms/openai/test_cost_calculation.py | 6 - .../llms/openai_like/test_scx_ai_provider.py | 29 - .../test_perplexity_cost_calculator.py | 334 +-- .../perplexity/test_perplexity_integration.py | 184 +- .../llms/tencent/test_cost_calculator.py | 29 - ...artner_models_anthropic_messages_config.py | 236 +-- .../test_xai_responses_transformation.py | 74 +- .../llms/xai/test_xai_chat_transformation.py | 84 +- .../llms/xai/test_xai_cost_calculator.py | 373 +--- .../llms/xai/test_xai_model_registry.py | 75 - .../xai/test_xai_redirected_slug_pricing.py | 20 - .../proxy/spend_tracking/test_savings.py | 144 -- .../test_azure_ai_grok_4_3_model_metadata.py | 39 - .../test_azure_ai_grok_4_6_model_metadata.py | 50 - .../test_baseten_glm_5_3_model_metadata.py | 93 - ..._bedrock_marengo_embed_3_model_metadata.py | 85 - .../test_bedrock_usgov_pricing.py | 12 - .../test_claude_fable_5_config.py | 160 -- .../test_claude_haiku_4_5_config.py | 48 - .../test_litellm/test_claude_opus_5_config.py | 29 - .../test_claude_sonnet_5_config.py | 29 - ...st_cloudflare_workers_ai_model_metadata.py | 50 - .../test_litellm/test_command_r7b_pricing.py | 67 - tests/test_litellm/test_cost_calculator.py | 700 +------ .../test_daybreak_model_metadata.py | 15 - .../test_deepseek_model_metadata.py | 37 - .../test_fireworks_serverless_model_costs.py | 44 +- ...est_gemini_3_1_flash_lite_image_pricing.py | 126 -- .../test_gemini_tts_native_audio_pricing.py | 135 -- .../test_gpt_5_4_model_metadata.py | 44 - .../test_gpt_5_5_model_metadata.py | 19 - .../test_gpt_image_cost_calculator.py | 352 +--- tests/test_litellm/test_gpt_realtime_mode.py | 13 - .../test_mistral_medium_3_5_model_metadata.py | 34 - .../test_mistral_small_4_0_model_metadata.py | 26 - ...test_mistral_zai_glm_5_2_model_metadata.py | 74 - .../test_muse_spark_1_1_model_metadata.py | 29 - .../test_muse_spark_1_2_model_metadata.py | 29 - .../test_muse_spark_1_3_model_metadata.py | 20 - ...penai_service_tier_long_context_pricing.py | 24 - .../test_replicate_model_key_format.py | 15 - .../test_sambanova_model_metadata.py | 25 - .../test_together_ai_model_metadata.py | 9 - tests/test_litellm/test_utils.py | 907 ++------ .../test_xai_grok_4_3_model_metadata.py | 19 - 56 files changed, 512 insertions(+), 6997 deletions(-) delete mode 100644 tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py delete mode 100644 tests/test_litellm/llms/databricks/test_databricks_pricing.py delete mode 100644 tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py delete mode 100644 tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py delete mode 100644 tests/test_litellm/llms/tencent/test_cost_calculator.py delete mode 100644 tests/test_litellm/llms/xai/test_xai_model_registry.py delete mode 100644 tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py delete mode 100644 tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py delete mode 100644 tests/test_litellm/test_baseten_glm_5_3_model_metadata.py delete mode 100644 tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py delete mode 100644 tests/test_litellm/test_claude_haiku_4_5_config.py delete mode 100644 tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py delete mode 100644 tests/test_litellm/test_command_r7b_pricing.py delete mode 100644 tests/test_litellm/test_gemini_tts_native_audio_pricing.py delete mode 100644 tests/test_litellm/test_gpt_5_4_model_metadata.py delete mode 100644 tests/test_litellm/test_gpt_5_5_model_metadata.py delete mode 100644 tests/test_litellm/test_mistral_medium_3_5_model_metadata.py delete mode 100644 tests/test_litellm/test_mistral_small_4_0_model_metadata.py delete mode 100644 tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py delete mode 100644 tests/test_litellm/test_muse_spark_1_1_model_metadata.py delete mode 100644 tests/test_litellm/test_sambanova_model_metadata.py delete mode 100644 tests/test_litellm/test_xai_grok_4_3_model_metadata.py diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py index a315b7003ad..7a72c9d3af0 100644 --- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py +++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py @@ -1,34 +1,9 @@ -import json +from collections.abc import Mapping from datetime import datetime, timezone import pytest -from collections.abc import Mapping -from fastapi.testclient import TestClient import litellm -from litellm._internal_context import pinned_billing_time -from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import ( - StandardBuiltInToolCostTracking, -) -from litellm.llms.gemini.image_generation.cost_calculator import ( - cost_calculator as gemini_image_generation_cost_calculator, -) -from litellm.llms.vertex_ai.image_generation.cost_calculator import ( - cost_calculator as vertex_image_generation_cost_calculator, -) -from litellm.types.llms.openai import FileSearchTool, WebSearchOptions -from litellm.types.utils import ( - CompletionTokensDetailsWrapper, - ImageObject, - ImageResponse, - ImageUsage, - ImageUsageInputTokensDetails, - ModelInfo, - ModelResponse, - PromptTokensDetailsWrapper, - StandardBuiltInToolsParams, -) - from litellm.litellm_core_utils.llm_cost_calc.utils import ( BilledTokenRates, CostCalculatorUtils, @@ -44,7 +19,23 @@ from litellm.litellm_core_utils.llm_cost_calc.utils import ( get_billed_token_rates, get_token_type_cost_breakdown, ) -from litellm.types.utils import CacheCreationTokenDetails, Usage +from litellm.llms.gemini.image_generation.cost_calculator import ( + cost_calculator as gemini_image_generation_cost_calculator, +) +from litellm.llms.vertex_ai.image_generation.cost_calculator import ( + cost_calculator as vertex_image_generation_cost_calculator, +) +from litellm.types.utils import ( + CacheCreationTokenDetails, + CompletionTokensDetailsWrapper, + ImageObject, + ImageResponse, + ImageUsage, + ImageUsageInputTokensDetails, + ModelInfo, + PromptTokensDetailsWrapper, + Usage, +) @pytest.fixture @@ -68,7 +59,9 @@ def test_missing_cache_read_policy_preserves_billing(prompt_tokens, read_rate, s usage = Usage(prompt_tokens=prompt_tokens, prompt_tokens_details={"cached_tokens": 100}) billed = _get_token_base_cost(info, usage, service_tier=service_tier) savings = _get_token_base_cost(info, usage, service_tier=service_tier, missing_cache_read_uses_input=True) - prompt_cost, _ = generic_cost_per_token("policy-fixture", usage, "openai", service_tier=service_tier, model_info=info) + prompt_cost, _ = generic_cost_per_token( + "policy-fixture", usage, "openai", service_tier=service_tier, model_info=info + ) assert billed[4] == pytest.approx(read_rate or 0.0) assert savings[:4] == billed[:4] assert savings[4] == pytest.approx(billed[0] if read_rate is None else read_rate) @@ -197,7 +190,6 @@ def test_reasoning_tokens_no_price_set(_local_model_cost_map): # Use o1 - o1-mini was deprecated/renamed; o1 has same reasoning-token semantics # (no separate output_cost_per_reasoning_token, so all completion tokens use output_cost_per_token) model = "o1" - custom_llm_provider = "openai" model_cost_map = litellm.model_cost[model] usage = Usage( completion_tokens=1578, @@ -224,9 +216,7 @@ def test_reasoning_tokens_no_price_set(_local_model_cost_map): 10, ) print(f"completion_cost: {completion_cost}") - expected_completion_cost = ( - model_cost_map["output_cost_per_token"] * usage.completion_tokens - ) + expected_completion_cost = model_cost_map["output_cost_per_token"] * usage.completion_tokens print(f"expected_completion_cost: {expected_completion_cost}") assert round(completion_cost, 10) == round( expected_completion_cost, @@ -265,14 +255,8 @@ def test_reasoning_tokens_gemini(_local_model_cost_map): 10, ) assert round(completion_cost, 10) == round( - ( - model_cost_map["output_cost_per_token"] - * usage.completion_tokens_details.text_tokens - ) - + ( - model_cost_map["output_cost_per_reasoning_token"] - * usage.completion_tokens_details.reasoning_tokens - ), + (model_cost_map["output_cost_per_token"] * usage.completion_tokens_details.text_tokens) + + (model_cost_map["output_cost_per_reasoning_token"] * usage.completion_tokens_details.reasoning_tokens), 10, ) @@ -309,14 +293,8 @@ def test_reasoning_tokens_gemini_3_1_flash_lite(_local_model_cost_map): 10, ) assert round(completion_cost, 10) == round( - ( - model_cost_map["output_cost_per_token"] - * usage.completion_tokens_details.text_tokens - ) - + ( - model_cost_map["output_cost_per_reasoning_token"] - * usage.completion_tokens_details.reasoning_tokens - ), + (model_cost_map["output_cost_per_token"] * usage.completion_tokens_details.text_tokens) + + (model_cost_map["output_cost_per_reasoning_token"] * usage.completion_tokens_details.reasoning_tokens), 10, ) @@ -413,44 +391,6 @@ def test_image_tokens_fallback_to_base_cost(): assert round(completion_cost, 12) == round(expected_completion_cost, 12) -def test_video_output_tokens_gemini_omni_flash_preview(_local_model_cost_map): - """Video output tokens are billed at output_cost_per_video_token, not the text rate and not zero.""" - model = "gemini-omni-flash-preview" - - text_tokens = 100 - video_tokens = 46336 - usage = Usage( - completion_tokens=text_tokens + video_tokens, - prompt_tokens=20, - total_tokens=20 + text_tokens + video_tokens, - completion_tokens_details=CompletionTokensDetailsWrapper( - text_tokens=text_tokens, - video_tokens=video_tokens, - ), - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=20), - ) - model_cost_map = litellm.model_cost[f"gemini/{model}"] - assert model_cost_map["input_cost_per_token"] == 1.5e-06 - assert model_cost_map["output_cost_per_token"] == 9e-06 - assert model_cost_map["output_cost_per_video_token"] == 1.75e-05 - - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider="gemini", - ) - - assert round(prompt_cost, 10) == round( - model_cost_map["input_cost_per_token"] * usage.prompt_tokens, - 10, - ) - assert round(completion_cost, 10) == round( - (model_cost_map["output_cost_per_token"] * text_tokens) - + (model_cost_map["output_cost_per_video_token"] * video_tokens), - 10, - ) - - def test_video_input_tokens_gemini_omni_flash_preview(_local_model_cost_map): """Video input tokens are billed at the standard input rate instead of being dropped.""" model = "gemini-omni-flash-preview" @@ -531,8 +471,7 @@ def test_generic_cost_per_token_above_200k_tokens(_local_model_cost_map): 10, ) assert round(completion_cost, 10) == round( - model_cost_map["output_cost_per_token_above_200k_tokens"] - * usage.completion_tokens, + model_cost_map["output_cost_per_token_above_200k_tokens"] * usage.completion_tokens, 10, ) @@ -586,9 +525,9 @@ def test_is_within_off_peak_window_equal_start_and_end_covers_whole_day(): for window in ("00:00-00:00", "10:00-10:00"): for hour in range(24): - assert ( - _is_within_off_peak_window(window, datetime(2026, 1, 1, hour, 0, tzinfo=timezone.utc)) is True - ), f"{window} should cover {hour:02d}:00" + assert _is_within_off_peak_window(window, datetime(2026, 1, 1, hour, 0, tzinfo=timezone.utc)) is True, ( + f"{window} should cover {hour:02d}:00" + ) def test_is_within_off_peak_window_multiple_windows(): @@ -1198,12 +1137,8 @@ def test_generic_cost_per_token_gpt54_above_272k_tokens(_local_model_cost_map): usage=usage, custom_llm_provider=custom_llm_provider, ) - expected_prompt = ( - model_cost_map["input_cost_per_token_above_272k_tokens"] * prompt_tokens - ) - expected_completion = ( - model_cost_map["output_cost_per_token_above_272k_tokens"] * completion_tokens - ) + expected_prompt = model_cost_map["input_cost_per_token_above_272k_tokens"] * prompt_tokens + expected_completion = model_cost_map["output_cost_per_token_above_272k_tokens"] * completion_tokens assert round(prompt_cost, 10) == round(expected_prompt, 10) assert round(completion_cost, 10) == round(expected_completion, 10) @@ -1229,148 +1164,14 @@ def test_generic_cost_per_token_minimax_m3_above_512k_tokens(_local_model_cost_m custom_llm_provider=custom_llm_provider, ) expected_prompt = ( - model_cost_map["input_cost_per_token_above_512k_tokens"] - * (prompt_tokens - cached_tokens) - + model_cost_map["cache_read_input_token_cost_above_512k_tokens"] - * cached_tokens - ) - expected_completion = ( - model_cost_map["output_cost_per_token_above_512k_tokens"] * completion_tokens + model_cost_map["input_cost_per_token_above_512k_tokens"] * (prompt_tokens - cached_tokens) + + model_cost_map["cache_read_input_token_cost_above_512k_tokens"] * cached_tokens ) + expected_completion = model_cost_map["output_cost_per_token_above_512k_tokens"] * completion_tokens assert round(prompt_cost, 10) == round(expected_prompt, 10) assert round(completion_cost, 10) == round(expected_completion, 10) -@pytest.mark.parametrize( - "model", - [ - "bedrock_mantle/openai.gpt-5.6-sol", - "bedrock_mantle/openai.gpt-5.6-terra", - "bedrock_mantle/openai.gpt-5.6-luna", - ], -) -def test_generic_cost_per_token_bedrock_mantle_gpt56_long_context(_local_model_cost_map, model): - """Bedrock GPT-5.6 enforces a 1,050,000-token context window, billed at the long-context rates above 272K.""" - - model_cost_map = litellm.model_cost[model] - assert model_cost_map["max_input_tokens"] == 1050000 - - cached_tokens = 100000 - completion_tokens = 1000 - - short_prompt_tokens = 272000 - short_usage = Usage( - prompt_tokens=short_prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=short_prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=cached_tokens), - ) - short_prompt_cost, short_completion_cost = generic_cost_per_token( - model=model, - usage=short_usage, - custom_llm_provider="bedrock_mantle", - ) - assert round(short_prompt_cost, 10) == round( - model_cost_map["input_cost_per_token"] * (short_prompt_tokens - cached_tokens) - + model_cost_map["cache_read_input_token_cost"] * cached_tokens, - 10, - ) - assert round(short_completion_cost, 10) == round( - model_cost_map["output_cost_per_token"] * completion_tokens, 10 - ) - - long_prompt_tokens = 900000 - long_usage = Usage( - prompt_tokens=long_prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=long_prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=cached_tokens), - ) - long_prompt_cost, long_completion_cost = generic_cost_per_token( - model=model, - usage=long_usage, - custom_llm_provider="bedrock_mantle", - ) - assert round(long_prompt_cost, 10) == round( - model_cost_map["input_cost_per_token_above_272k_tokens"] - * (long_prompt_tokens - cached_tokens) - + model_cost_map["cache_read_input_token_cost_above_272k_tokens"] - * cached_tokens, - 10, - ) - assert round(long_completion_cost, 10) == round( - model_cost_map["output_cost_per_token_above_272k_tokens"] * completion_tokens, 10 - ) - - -@pytest.mark.parametrize( - "model,input_rate,cache_read_rate,output_rate,long_input_rate,long_cache_read_rate,long_output_rate", - [ - ("bedrock_mantle/openai.gpt-5.5", 5.5e-06, 5.5e-07, 3.3e-05, 1.1e-05, 1.1e-06, 4.95e-05), - ("bedrock_mantle/openai.gpt-5.4", 2.75e-06, 2.75e-07, 1.65e-05, 5.5e-06, 5.5e-07, 2.475e-05), - ("bedrock_mantle/openai.gpt-5.6-sol", 5.5e-06, 5.5e-07, 3.3e-05, 1.1e-05, 1.1e-06, 4.95e-05), - ], -) -def test_generic_cost_per_token_bedrock_mantle_gpt5_matches_aws_invoiced_rates( - _local_model_cost_map, - model, - input_rate, - cache_read_rate, - output_rate, - long_input_rate, - long_cache_read_rate, - long_output_rate, -): - """AWS bills a Bedrock GPT-5.x prompt past 272K under its long-context usage types, the whole prompt at - 2x input, 2x cache read, and 1.5x output. The flat rates undercounted a 300K gpt-5.5 prompt by half and - sol's base rates sat 20% under the invoice.""" - - cached_tokens = 100000 - completion_tokens = 1000 - - invoiced_prompt_tokens = 300238 - long_usage = Usage( - prompt_tokens=invoiced_prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=invoiced_prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=cached_tokens), - ) - long_prompt_cost, long_completion_cost = generic_cost_per_token( - model=model, - usage=long_usage, - custom_llm_provider="bedrock_mantle", - ) - assert long_prompt_cost == pytest.approx( - long_input_rate * (invoiced_prompt_tokens - cached_tokens) + long_cache_read_rate * cached_tokens - ) - assert long_completion_cost == pytest.approx(long_output_rate * completion_tokens) - - threshold_prompt_tokens = 272000 - short_usage = Usage( - prompt_tokens=threshold_prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=threshold_prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=cached_tokens), - ) - short_prompt_cost, short_completion_cost = generic_cost_per_token( - model=model, - usage=short_usage, - custom_llm_provider="bedrock_mantle", - ) - assert short_prompt_cost == pytest.approx( - input_rate * (threshold_prompt_tokens - cached_tokens) + cache_read_rate * cached_tokens - ) - assert short_completion_cost == pytest.approx(output_rate * completion_tokens) - - -def test_bedrock_mantle_gpt56_sol_cache_write_matches_aws_invoiced_rate(_local_model_cost_map): - """The invoice bills sol 30-minute cache writes at $6.88 per million tokens, 1.25x the $5.50 input rate.""" - - sol = litellm.model_cost["bedrock_mantle/openai.gpt-5.6-sol"] - assert sol["cache_creation_input_token_cost"] == pytest.approx(6.875e-06) - assert sol["cache_creation_input_token_cost_above_272k_tokens"] == pytest.approx(1.375e-05) - - def test_generic_cost_per_token_honors_non_standard_above_threshold(): """Regression for #30344: get_model_info must keep arbitrary input/output_cost_per_token_above__tokens thresholds, not only the hard-coded @@ -1444,9 +1245,7 @@ def test_generic_cost_per_token_tiered_pricing_charges_cache_creation_at_tier_ra prompt_tokens=300000, # 200k new + 60k cache creation + 40k cache read completion_tokens=1000, total_tokens=301000, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=40000, cache_creation_tokens=60000 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=40000, cache_creation_tokens=60000), ) prompt_cost, completion_cost = generic_cost_per_token( model=model, @@ -1454,9 +1253,7 @@ def test_generic_cost_per_token_tiered_pricing_charges_cache_creation_at_tier_ra custom_llm_provider=custom_llm_provider, ) - expected_prompt = ( - (200000 * 6.5e-07) + (60000 * 8.125e-07) + (40000 * 6.5e-08) - ) + expected_prompt = (200000 * 6.5e-07) + (60000 * 8.125e-07) + (40000 * 6.5e-08) assert round(prompt_cost, 10) == round(expected_prompt, 10) assert round(completion_cost, 10) == round(1000 * 3.9e-06, 10) finally: @@ -1588,9 +1385,7 @@ def test_generic_cost_per_token_tier_without_cache_rates_bills_cache_at_the_tier prompt_tokens=40000, completion_tokens=100, total_tokens=40100, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=5000, cache_creation_tokens=15000 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=5000, cache_creation_tokens=15000), ) uncached_prompt_cost, _ = generic_cost_per_token( model=model, @@ -1779,138 +1574,6 @@ def test_generic_cost_per_token_tiered_pricing_bills_reasoning_at_tier_rate(): litellm.model_cost.pop(model, None) -def test_generic_cost_per_token_gpt55(_local_model_cost_map): - """gpt-5.5: base pricing — $5/1M input, $30/1M output, $0.50/1M cached input.""" - model = "gpt-5.5" - custom_llm_provider = "openai" - - model_cost_map = litellm.model_cost[model] - - # Sanity-check the map values match OpenAI's published pricing. - assert model_cost_map["input_cost_per_token"] == 5e-6 - assert model_cost_map["output_cost_per_token"] == 3e-5 - assert model_cost_map["cache_read_input_token_cost"] == 5e-7 - assert model_cost_map["litellm_provider"] == "openai" - assert model_cost_map["mode"] == "chat" - # gpt-5.5 inherits GPT-5.4's long-context window + tiered pricing. - assert model_cost_map["max_input_tokens"] == 1050000 - assert model_cost_map["input_cost_per_token_above_272k_tokens"] == 1e-5 - assert model_cost_map["output_cost_per_token_above_272k_tokens"] == 4.5e-5 - - prompt_tokens = 1000 - completion_tokens = 500 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - ) - assert round(prompt_cost, 10) == round( - model_cost_map["input_cost_per_token"] * prompt_tokens, 10 - ) - assert round(completion_cost, 10) == round( - model_cost_map["output_cost_per_token"] * completion_tokens, 10 - ) - - -def test_generic_cost_per_token_gpt55_pro(_local_model_cost_map): - """gpt-5.5-pro: responses-only model, $30/1M input, $180/1M output, no cached input rate published.""" - model = "gpt-5.5-pro" - custom_llm_provider = "openai" - - model_cost_map = litellm.model_cost[model] - - # Sanity-check the map values match OpenAI's published pricing. - assert model_cost_map["input_cost_per_token"] == 3e-5 - assert model_cost_map["output_cost_per_token"] == 1.8e-4 - assert "cache_read_input_token_cost" not in model_cost_map - assert model_cost_map["litellm_provider"] == "openai" - # gpt-5.5-pro is a responses-only model (no /v1/chat/completions endpoint). - assert model_cost_map["mode"] == "responses" - assert "/v1/chat/completions" not in model_cost_map["supported_endpoints"] - assert "/v1/responses" in model_cost_map["supported_endpoints"] - # Inherits GPT-5.4-pro's long-context window + tiered pricing. - assert model_cost_map["max_input_tokens"] == 1050000 - assert model_cost_map["input_cost_per_token_above_272k_tokens"] == 6e-5 - assert model_cost_map["output_cost_per_token_above_272k_tokens"] == 2.7e-4 - - prompt_tokens = 1000 - completion_tokens = 500 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - ) - assert round(prompt_cost, 10) == round( - model_cost_map["input_cost_per_token"] * prompt_tokens, 10 - ) - assert round(completion_cost, 10) == round( - model_cost_map["output_cost_per_token"] * completion_tokens, 10 - ) - - -@pytest.mark.parametrize( - "model,input_cost,output_cost,cache_read_cost,cache_write_cost", - [ - ("gpt-5.6", 4e-6, 2e-5, 4e-7, 5e-6), - ("gpt-5.6-sol", 4e-6, 2e-5, 4e-7, 5e-6), - ("gpt-5.6-terra", 2e-6, 1.2e-5, 2e-7, 2.5e-6), - ("gpt-5.6-luna", 2e-7, 1.2e-6, 2e-8, 2.5e-7), - ], -) -def test_generic_cost_per_token_gpt56(_local_model_cost_map, - model, input_cost, output_cost, cache_read_cost, cache_write_cost -): - """gpt-5.6 (sol/terra/luna): base pricing + new cache-write cost. - - Cache writes are billed at 1.25x the uncached input rate for this family. - """ - custom_llm_provider = "openai" - - model_cost_map = litellm.model_cost[model] - - assert model_cost_map["input_cost_per_token"] == input_cost - assert model_cost_map["output_cost_per_token"] == output_cost - assert model_cost_map["cache_read_input_token_cost"] == cache_read_cost - assert model_cost_map["cache_creation_input_token_cost"] == cache_write_cost - assert model_cost_map["litellm_provider"] == "openai" - assert model_cost_map["mode"] == "chat" - assert model_cost_map["cache_creation_input_token_cost"] == pytest.approx( - input_cost * 1.25 - ) - assert model_cost_map["max_input_tokens"] == 922000 - assert model_cost_map["input_cost_per_token_above_272k_tokens"] == pytest.approx( - input_cost * 2 - ) - assert model_cost_map["output_cost_per_token_above_272k_tokens"] == pytest.approx( - output_cost * 1.5 - ) - - prompt_tokens = 1000 - completion_tokens = 500 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - ) - assert round(prompt_cost, 10) == round(input_cost * prompt_tokens, 10) - assert round(completion_cost, 10) == round(output_cost * completion_tokens, 10) - - def test_gpt_5_6_alias_prices_match_sol(local_model_cost_map): """Regression: the bare gpt-5.6 alias routes to GPT-5.6 Sol, so every cost field on the two entries has to hold the same value. They drifted once before, when Sol took @@ -1926,327 +1589,6 @@ def test_gpt_5_6_alias_prices_match_sol(local_model_cost_map): assert alias.get(field) == sol.get(field), field -@pytest.mark.parametrize( - "model,flex_long_input_cost,flex_long_output_cost", - [ - ("gpt-5.6", 4e-6, 1.5e-5), - ("gpt-5.6-sol", 4e-6, 1.5e-5), - ("gpt-5.6-terra", 2e-6, 9e-6), - ("gpt-5.6-luna", 2e-7, 9e-7), - ], -) -def test_generic_cost_per_token_gpt56_flex_above_272k(_local_model_cost_map, - model, flex_long_input_cost, flex_long_output_cost -): - """A >272K flex request bills the flex long-context rate, not the standard one. - - Flex long-context is half the standard long-context rate. Without the - ``*_above_272k_tokens_flex`` keys these requests silently fell back to the - standard long-context price, billing 2x what OpenAI charges. - """ - - prompt_tokens = 300000 - completion_tokens = 1000 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider="openai", - service_tier="flex", - ) - - assert prompt_cost == pytest.approx(flex_long_input_cost * prompt_tokens) - assert completion_cost == pytest.approx(flex_long_output_cost * completion_tokens) - - standard_long_prompt_cost, standard_long_completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider="openai", - service_tier=None, - ) - assert prompt_cost == pytest.approx(standard_long_prompt_cost / 2) - assert completion_cost == pytest.approx(standard_long_completion_cost / 2) - - -@pytest.mark.parametrize( - "service_tier,prompt_tokens,input_rate,cache_write_rate,cache_read_rate", - [ - (None, 100000, 2e-6, 2.5e-6, 2e-7), - ("flex", 100000, 1e-6, 1.25e-6, 1e-7), - ("priority", 100000, 4e-6, 5e-6, 4e-7), - (None, 300000, 4e-6, 5e-6, 4e-7), - ("flex", 300000, 2e-6, 2.5e-6, 2e-7), - ], -) -def test_generic_cost_per_token_gpt56_terra_cache_costs_by_tier_and_context(_local_model_cost_map, - service_tier, prompt_tokens, input_rate, cache_write_rate, cache_read_rate -): - - cached_tokens = 50000 - cache_write_tokens = 40000 - text_tokens = prompt_tokens - cached_tokens - cache_write_tokens - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=100, - total_tokens=prompt_tokens + 100, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=cached_tokens, cache_write_tokens=cache_write_tokens - ), - ) - - prompt_cost, _ = generic_cost_per_token( - model="gpt-5.6-terra", - usage=usage, - custom_llm_provider="openai", - service_tier=service_tier, - ) - - expected_prompt_cost = ( - text_tokens * input_rate - + cached_tokens * cache_read_rate - + cache_write_tokens * cache_write_rate - ) - assert prompt_cost == pytest.approx(expected_prompt_cost) - - -@pytest.mark.parametrize("model", ["gpt-5.6-cyber", "daybreak-red-latest"]) -@pytest.mark.parametrize( - "prompt_tokens,input_rate,cache_write_rate,cache_read_rate,output_rate", - [ - (100000, 1.25e-5, 1.5625e-5, 1.25e-6, 7.5e-5), - (300000, 2.5e-5, 3.125e-5, 2.5e-6, 1.125e-4), - ], -) -def test_generic_cost_per_token_gpt56_cyber( - model, - prompt_tokens, - input_rate, - cache_write_rate, - cache_read_rate, - output_rate, - monkeypatch, -): - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) - - cached_tokens = 50000 - cache_write_tokens = 40000 - text_tokens = prompt_tokens - cached_tokens - cache_write_tokens - completion_tokens = 1000 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=cached_tokens, cache_write_tokens=cache_write_tokens - ), - ) - - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider="openai", - ) - - assert prompt_cost == pytest.approx( - text_tokens * input_rate - + cached_tokens * cache_read_rate - + cache_write_tokens * cache_write_rate - ) - assert completion_cost == pytest.approx(completion_tokens * output_rate) - - -@pytest.mark.parametrize( - "service_tier,tier_multiplier", - [(None, 1.0), ("flex", 0.5), ("priority", 2.0), ("fast", 2.0)], -) -@pytest.mark.parametrize( - "prompt_tokens,input_side_multiplier,output_multiplier", - [(100000, 1.0, 1.0), (300000, 2.0, 1.5)], -) -def test_generic_cost_per_token_gpt_6_astra_price_sheet( - _local_model_cost_map, - service_tier, - tier_multiplier, - prompt_tokens, - input_side_multiplier, - output_multiplier, -): - """gpt-6-astra launch price sheet: $10 input, $1 cache read, $12.50 cache write, $50 output per 1M tokens. - - Above 272K prompt tokens the input-side rates double and the output rate is 1.5x on the whole - request. Flex is half the applicable rate and fast mode, billed as priority, is double it. - """ - cached_tokens = 50000 - cache_write_tokens = 40000 - text_tokens = prompt_tokens - cached_tokens - cache_write_tokens - completion_tokens = 1000 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=cached_tokens, cache_write_tokens=cache_write_tokens - ), - ) - - prompt_cost, completion_cost = generic_cost_per_token( - model="gpt-6-astra", - usage=usage, - custom_llm_provider="openai", - service_tier=service_tier, - ) - - input_side = tier_multiplier * input_side_multiplier - assert prompt_cost == pytest.approx( - input_side * (text_tokens * 1e-5 + cached_tokens * 1e-6 + cache_write_tokens * 1.25e-5) - ) - assert completion_cost == pytest.approx(tier_multiplier * output_multiplier * completion_tokens * 5e-5) - - -@pytest.mark.parametrize( - "model,input_cost,output_cost,cache_read_cost", - [ - ("azure/gpt-5.6", 5e-6, 3e-5, 5e-7), - ("azure/gpt-5.6-sol", 5e-6, 3e-5, 5e-7), - ("azure/gpt-5.6-terra", 2e-6, 1.2e-5, 2e-7), - ("azure/gpt-5.6-luna", 2e-7, 1.2e-6, 2e-8), - ("azure/us/gpt-5.6", 5.5e-6, 3.3e-5, 5.5e-7), - ("azure/eu/gpt-5.6-terra", 2.2e-6, 1.32e-5, 2.2e-7), - ("azure/eu/gpt-5.6-luna", 2.2e-7, 1.32e-6, 2.2e-8), - ], -) -def test_generic_cost_per_token_azure_gpt56(_local_model_cost_map, - model, input_cost, output_cost, cache_read_cost -): - """Azure gpt-5.6 (global + us/eu regional): Azure prices this family on its own - schedule and carries the standard 10% regional uplift on top. It did not take the - promotional cut OpenAI applied to gpt-5.6-sol, so these rates deliberately sit - above the openai ones and must not be lowered to match them. - """ - - model_cost_map = litellm.model_cost[model] - assert model_cost_map["litellm_provider"] == "azure" - assert model_cost_map["input_cost_per_token"] == input_cost - assert model_cost_map["output_cost_per_token"] == output_cost - assert model_cost_map["cache_read_input_token_cost"] == cache_read_cost - assert model_cost_map["max_input_tokens"] == 922000 - - prompt_tokens = 1000 - completion_tokens = 500 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider="azure", - ) - assert round(prompt_cost, 10) == round(input_cost * prompt_tokens, 10) - assert round(completion_cost, 10) == round(output_cost * completion_tokens, 10) - - -@pytest.mark.parametrize( - "model,custom_llm_provider,zone_multiplier", - [ - ("azure/gpt-6-astra", "azure", 1.0), - ("azure/us/gpt-6-astra", "azure", 1.1), - ("azure_ai/gpt-6-astra", "azure_ai", 1.0), - ], -) -@pytest.mark.parametrize( - "prompt_tokens,input_side_multiplier,output_multiplier", - [(100000, 1.0, 1.0), (300000, 2.0, 1.5)], -) -def test_generic_cost_per_token_azure_gpt_6_astra_foundry_price_sheet( - _local_model_cost_map, - model, - custom_llm_provider, - zone_multiplier, - prompt_tokens, - input_side_multiplier, - output_multiplier, -): - """Microsoft Foundry sells gpt-6-astra at the OpenAI rates: $10 input, $1 cache read, $12.50 cache write, - $50 output per 1M tokens on Standard Global, with the input side doubling and output 1.5x above 272K - prompt tokens. Standard US Data Zone carries the usual 10% uplift on every rate. A Foundry - deployment reached through the azure_ai route bills the same Standard Global sheet. - """ - cached_tokens = 50000 - cache_write_tokens = 40000 - text_tokens = prompt_tokens - cached_tokens - cache_write_tokens - completion_tokens = 1000 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=cached_tokens, cache_write_tokens=cache_write_tokens - ), - ) - - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - ) - - input_side = zone_multiplier * input_side_multiplier - assert prompt_cost == pytest.approx( - input_side * (text_tokens * 1e-5 + cached_tokens * 1e-6 + cache_write_tokens * 1.25e-5) - ) - assert completion_cost == pytest.approx(zone_multiplier * output_multiplier * completion_tokens * 5e-5) - - -@pytest.mark.parametrize( - "model,input_rate,cache_read_rate,output_rate", - [ - ("azure/gpt-chat-latest", 5e-6, 5e-7, 3e-5), - ("azure/chat-latest", 5e-6, 5e-7, 3e-5), - ("azure/us/gpt-chat-latest", 5.5e-6, 5.5e-7, 3.3e-5), - ], -) -def test_generic_cost_per_token_azure_gpt_chat_latest_price_sheet( - _local_model_cost_map, model, input_rate, cache_read_rate, output_rate -): - """The Azure OpenAI price sheet lists GPT-Chat Latest at $5 input, $0.50 cached input and $30 output per 1M - tokens on Global, and $5.50, $0.55 and $33 on Data Zone. Foundry names the product gpt-chat-latest and the - OpenAI API names the same model chat-latest, so both spellings bill the Global sheet. - """ - prompt_tokens = 100000 - cached_tokens = 40000 - completion_tokens = 1000 - usage = Usage( - prompt_tokens=prompt_tokens, - completion_tokens=completion_tokens, - total_tokens=prompt_tokens + completion_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=cached_tokens), - ) - - prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="azure") - - assert prompt_cost == pytest.approx((prompt_tokens - cached_tokens) * input_rate + cached_tokens * cache_read_rate) - assert completion_cost == pytest.approx(completion_tokens * output_rate) - - -def test_generic_cost_per_token_azure_ai_gpt_6_astra_flex_bills_the_standard_rate(_local_model_cost_map): - usage = Usage(prompt_tokens=1000, completion_tokens=100, total_tokens=1100) - - standard = generic_cost_per_token(model="azure_ai/gpt-6-astra", usage=usage, custom_llm_provider="azure_ai") - flex = generic_cost_per_token( - model="azure_ai/gpt-6-astra", usage=usage, custom_llm_provider="azure_ai", service_tier="flex" - ) - - assert flex == standard - assert standard == pytest.approx((1000 * 1e-05, 100 * 5e-05)) - - @pytest.mark.parametrize( "model,expected_none,expected_xhigh,expected_minimal", [ @@ -2263,8 +1605,8 @@ def test_generic_cost_per_token_azure_ai_gpt_6_astra_flex_bills_the_standard_rat ("gpt-5.5-pro-2026-04-23", False, True, False), ], ) -def test_gpt55_reasoning_effort_flags_match_live_openai_api(_local_model_cost_map, - model, expected_none, expected_xhigh, expected_minimal +def test_gpt55_reasoning_effort_flags_match_live_openai_api( + _local_model_cost_map, model, expected_none, expected_xhigh, expected_minimal ): """Pin reasoning_effort capability flags to OpenAI's actual API contract. @@ -2274,15 +1616,15 @@ def test_gpt55_reasoning_effort_flags_match_live_openai_api(_local_model_cost_ma """ m = litellm.model_cost[model] - assert ( - m.get("supports_none_reasoning_effort") is expected_none - ), f"{model}: supports_none_reasoning_effort expected {expected_none}" - assert ( - m.get("supports_xhigh_reasoning_effort") is expected_xhigh - ), f"{model}: supports_xhigh_reasoning_effort expected {expected_xhigh}" - assert ( - m.get("supports_minimal_reasoning_effort") is expected_minimal - ), f"{model}: supports_minimal_reasoning_effort expected {expected_minimal}" + assert m.get("supports_none_reasoning_effort") is expected_none, ( + f"{model}: supports_none_reasoning_effort expected {expected_none}" + ) + assert m.get("supports_xhigh_reasoning_effort") is expected_xhigh, ( + f"{model}: supports_xhigh_reasoning_effort expected {expected_xhigh}" + ) + assert m.get("supports_minimal_reasoning_effort") is expected_minimal, ( + f"{model}: supports_minimal_reasoning_effort expected {expected_minimal}" + ) @pytest.mark.parametrize( @@ -2292,9 +1634,7 @@ def test_gpt55_reasoning_effort_flags_match_live_openai_api(_local_model_cost_ma ("gpt-5.5-pro", "gpt-5.5-pro-2026-04-23"), ], ) -def test_gpt55_dated_variants_match_base_reasoning_effort_capabilities(_local_model_cost_map, - base_model, dated_model -): +def test_gpt55_dated_variants_match_base_reasoning_effort_capabilities(_local_model_cost_map, base_model, dated_model): """Dated snapshots must carry the same reasoning_effort capability flags as their non-dated counterparts. @@ -2333,8 +1673,8 @@ def test_gpt55_dated_variants_match_base_reasoning_effort_capabilities(_local_mo ("azure/gpt-5.5-pro", False, False, True), ], ) -def test_azure_gpt55_reasoning_effort_flags_match_live_openai_api(_local_model_cost_map, - model, expected_none, expected_minimal, expected_xhigh +def test_azure_gpt55_reasoning_effort_flags_match_live_openai_api( + _local_model_cost_map, model, expected_none, expected_minimal, expected_xhigh ): """Azure entries pin reasoning_effort flags to OpenAI's actual API contract.""" @@ -2344,38 +1684,6 @@ def test_azure_gpt55_reasoning_effort_flags_match_live_openai_api(_local_model_c assert m.get("supports_xhigh_reasoning_effort") is expected_xhigh -def test_generic_cost_per_token_anthropic_prompt_caching(): - model = "claude-sonnet-4@20250514" - usage = Usage( - completion_tokens=90, - prompt_tokens=28436, - total_tokens=28526, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=None, - audio_tokens=None, - reasoning_tokens=0, - rejected_prediction_tokens=None, - text_tokens=None, - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - audio_tokens=None, cached_tokens=0, text_tokens=None, image_tokens=None - ), - cache_creation_input_tokens=118, - cache_read_input_tokens=28432, - ) - - custom_llm_provider = "vertex_ai" - - prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - ) - - print(f"prompt_cost: {prompt_cost}") - assert prompt_cost < 0.085 - - def test_generic_cost_per_token_anthropic_prompt_caching_with_cache_creation(): model = "claude-haiku-4-5-20251001" usage = Usage( @@ -2488,14 +1796,10 @@ def test_generic_cost_per_token_overlapping_cached_and_image_tokens(): prompt_tokens=100, completion_tokens=10, total_tokens=110, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=None, cached_tokens=90, image_tokens=80 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=None, cached_tokens=90, image_tokens=80), ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, usage=usage, custom_llm_provider="openai" - ) + prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai") # 90 cached at 1e-7, the remaining 10 uncached tokens once at 1e-6 assert prompt_cost == pytest.approx(90 * 1e-7 + 10 * 1e-6) @@ -2524,14 +1828,10 @@ def test_generic_cost_per_token_warm_prefix_cache_spanning_text_and_image_tokens prompt_tokens=2461, completion_tokens=440, total_tokens=2901, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=1319, cached_tokens=2432, image_tokens=1142 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1319, cached_tokens=2432, image_tokens=1142), ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, usage=usage, custom_llm_provider="openai" - ) + prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai") # 2432 cached at the cache-read rate, the 29 uncached tokens once at the input rate assert prompt_cost == pytest.approx(2432 * 5e-7 + 29 * 2e-6) @@ -2782,181 +2082,10 @@ def test_cache_writing_cost_with_zero_creation_tokens_and_ephemeral_details(): # Expected: (100 * 3.75e-06) + (200 * 6e-06) = 0.000375 + 0.0012 = 0.001575 expected = (100 * cache_creation_cost) + (200 * cache_creation_cost_above_1hr) - assert ( - result > 0 - ), "Cost should not be zero when ephemeral token details are present" + assert result > 0, "Cost should not be zero when ephemeral token details are present" assert round(result, 6) == round(expected, 6) -def test_service_tier_flex_pricing(_local_model_cost_map): - """Test that flex service tier uses correct pricing (approximately 50% of standard).""" - # Set up environment for local model cost map - - # Test with gpt-5-nano which has flex pricing - model = "gpt-5-nano" - custom_llm_provider = "openai" - - # Create usage object - usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - - # Test standard pricing - std_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - service_tier=None, - ) - std_total = std_cost[0] + std_cost[1] - - # Test flex pricing - flex_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - service_tier="flex", - ) - flex_total = flex_cost[0] + flex_cost[1] - - # Verify flex is approximately 50% of standard - assert std_total > 0, "Standard cost should be greater than 0" - assert flex_total > 0, "Flex cost should be greater than 0" - - flex_ratio = flex_total / std_total - assert ( - 0.45 <= flex_ratio <= 0.55 - ), f"Flex pricing should be ~50% of standard, got {flex_ratio:.2f}" - - # Verify specific costs match expected values - # gpt-5-nano flex: input=2.5e-08, output=2e-07 - expected_flex_prompt = 1000 * 2.5e-08 # 0.000025 - expected_flex_completion = 500 * 2e-07 # 0.0001 - expected_flex_total = expected_flex_prompt + expected_flex_completion - - assert ( - abs(flex_cost[0] - expected_flex_prompt) < 1e-10 - ), f"Flex prompt cost mismatch: {flex_cost[0]} vs {expected_flex_prompt}" - assert ( - abs(flex_cost[1] - expected_flex_completion) < 1e-10 - ), f"Flex completion cost mismatch: {flex_cost[1]} vs {expected_flex_completion}" - assert ( - abs(flex_total - expected_flex_total) < 1e-10 - ), f"Flex total cost mismatch: {flex_total} vs {expected_flex_total}" - - -def test_service_tier_default_pricing(_local_model_cost_map): - """Test that when no service tier is provided, standard pricing is used.""" - # Set up environment for local model cost map - - # Test with gpt-5-nano - model = "gpt-5-nano" - custom_llm_provider = "openai" - - # Create usage object - usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - - # Test with no service tier (should use standard) - default_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - service_tier=None, - ) - - # Test with explicit standard service tier - standard_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - service_tier="standard", - ) - - # Both should be identical - assert ( - abs(default_cost[0] - standard_cost[0]) < 1e-10 - ), "Default and standard prompt costs should be identical" - assert ( - abs(default_cost[1] - standard_cost[1]) < 1e-10 - ), "Default and standard completion costs should be identical" - - # Verify specific costs match expected standard values - # gpt-5-nano standard: input=5e-08, output=4e-07 - expected_standard_prompt = 1000 * 5e-08 # 0.00005 - expected_standard_completion = 500 * 4e-07 # 0.0002 - expected_standard_total = expected_standard_prompt + expected_standard_completion - - assert ( - abs(default_cost[0] - expected_standard_prompt) < 1e-10 - ), f"Standard prompt cost mismatch: {default_cost[0]} vs {expected_standard_prompt}" - assert ( - abs(default_cost[1] - expected_standard_completion) < 1e-10 - ), f"Standard completion cost mismatch: {default_cost[1]} vs {expected_standard_completion}" - - -def test_service_tier_fallback_pricing(_local_model_cost_map): - """Test that when service tier is provided but model doesn't have those keys, it falls back to standard pricing.""" - # Set up environment for local model cost map - - # Test with gpt-4 which doesn't have flex pricing keys - model = "gpt-4" - custom_llm_provider = "openai" - - # Create usage object - usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - - # Test standard pricing - std_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - service_tier=None, - ) - std_total = std_cost[0] + std_cost[1] - - # Test flex pricing (should fall back to standard since gpt-4 doesn't have flex keys) - flex_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - service_tier="flex", - ) - flex_total = flex_cost[0] + flex_cost[1] - - # Test priority pricing (should fall back to standard since gpt-4 doesn't have priority keys) - priority_cost = generic_cost_per_token( - model=model, - usage=usage, - custom_llm_provider=custom_llm_provider, - service_tier="priority", - ) - priority_total = priority_cost[0] + priority_cost[1] - - # All should be identical (fallback to standard) - assert ( - abs(std_total - flex_total) < 1e-10 - ), f"Standard and flex costs should be identical (fallback): {std_total} vs {flex_total}" - assert ( - abs(std_total - priority_total) < 1e-10 - ), f"Standard and priority costs should be identical (fallback): {std_total} vs {priority_total}" - - # Verify costs are reasonable (not zero) - assert std_total > 0, "Standard cost should be greater than 0" - assert flex_total > 0, "Flex cost should be greater than 0 (fallback)" - assert priority_total > 0, "Priority cost should be greater than 0 (fallback)" - - # Verify specific costs match expected gpt-4 values - # gpt-4 standard: input=3e-05, output=6e-05 - expected_standard_prompt = 1000 * 3e-05 # 0.03 - expected_standard_completion = 500 * 6e-05 # 0.03 - expected_standard_total = expected_standard_prompt + expected_standard_completion - - assert ( - abs(std_cost[0] - expected_standard_prompt) < 1e-10 - ), f"Standard prompt cost mismatch: {std_cost[0]} vs {expected_standard_prompt}" - assert ( - abs(std_cost[1] - expected_standard_completion) < 1e-10 - ), f"Standard completion cost mismatch: {std_cost[1]} vs {expected_standard_completion}" - - def test_service_tier_ultrafast_pricing(): """An ultrafast request bills the *_ultrafast rates for all token types. @@ -2995,9 +2124,7 @@ def test_service_tier_ultrafast_pricing(): model_info=model_info, ) - expected_prompt_cost = ( - text_tokens * 5e-05 + cached_tokens * 5e-06 + cache_write_tokens * 6.25e-05 - ) + expected_prompt_cost = text_tokens * 5e-05 + cached_tokens * 5e-06 + cache_write_tokens * 6.25e-05 assert prompt_cost == pytest.approx(expected_prompt_cost) assert completion_cost == pytest.approx(400 * 3e-04) @@ -3086,9 +2213,7 @@ def test_gemini_image_generation_cost_with_zero_text_tokens(_local_model_cost_ma output_cost_per_token = model_cost_map.get("output_cost_per_token", 0) expected_image_cost = 1120 * output_cost_per_image_token - expected_reasoning_cost = ( - 225 * output_cost_per_token - ) # reasoning uses base token cost + expected_reasoning_cost = 225 * output_cost_per_token # reasoning uses base token cost expected_completion_cost = expected_image_cost + expected_reasoning_cost # The bug was: all completion tokens were treated as text tokens only. @@ -3097,9 +2222,9 @@ def test_gemini_image_generation_cost_with_zero_text_tokens(_local_model_cost_ma f"Completion cost should be significantly larger than text-only bugged path. " f"Expected > {bugged_text_only_cost * 2:.6f}, got {completion_cost:.6f}" ) - assert round(completion_cost, 4) == round( - expected_completion_cost, 4 - ), f"Expected completion cost ${expected_completion_cost:.6f}, got ${completion_cost:.6f}" + assert round(completion_cost, 4) == round(expected_completion_cost, 4), ( + f"Expected completion cost ${expected_completion_cost:.6f}, got ${completion_cost:.6f}" + ) def test_vertex_image_generation_cost_prefers_token_usage_metadata(_local_model_cost_map): @@ -3135,9 +2260,7 @@ def test_vertex_image_generation_cost_prefers_token_usage_metadata(_local_model_ ) expected_prompt_cost = prompt_tokens * model_info["input_cost_per_token"] - expected_completion_cost = ( - output_image_tokens * model_info["output_cost_per_image_token"] - ) + expected_completion_cost = output_image_tokens * model_info["output_cost_per_image_token"] expected_total_cost = expected_prompt_cost + expected_completion_cost assert round(cost, 10) == round(expected_total_cost, 10) @@ -3154,9 +2277,7 @@ def test_vertex_image_generation_cost_falls_back_to_flat_image_pricing(_local_mo model = "gemini-3.1-flash-image-preview" model_info = litellm.get_model_info(model=model, custom_llm_provider="vertex_ai") - image_response = ImageResponse( - data=[ImageObject(b64_json="img1"), ImageObject(b64_json="img2")] - ) + image_response = ImageResponse(data=[ImageObject(b64_json="img1"), ImageObject(b64_json="img2")]) cost = vertex_image_generation_cost_calculator( model=model, @@ -3200,9 +2321,7 @@ def test_gemini_image_generation_cost_prefers_token_usage_metadata(_local_model_ ) expected_prompt_cost = prompt_tokens * model_info["input_cost_per_token"] - expected_completion_cost = ( - output_image_tokens * model_info["output_cost_per_image_token"] - ) + expected_completion_cost = output_image_tokens * model_info["output_cost_per_image_token"] expected_total_cost = expected_prompt_cost + expected_completion_cost assert round(cost, 10) == round(expected_total_cost, 10) @@ -3219,9 +2338,7 @@ def test_gemini_image_generation_cost_falls_back_to_flat_image_pricing(_local_mo model = "gemini/gemini-3-pro-image-preview" model_info = litellm.get_model_info(model=model, custom_llm_provider="gemini") - image_response = ImageResponse( - data=[ImageObject(b64_json="img1"), ImageObject(b64_json="img2")] - ) + image_response = ImageResponse(data=[ImageObject(b64_json="img1"), ImageObject(b64_json="img2")]) cost = gemini_image_generation_cost_calculator( model=model, @@ -3296,19 +2413,19 @@ def test_reasoning_tokens_without_text_tokens_gpt5_nano(): expected_prompt_cost = 17 * 0.05 / 1_000_000 expected_completion_cost = 977 * 0.40 / 1_000_000 # ALL tokens, not just reasoning - assert ( - abs(prompt_cost - expected_prompt_cost) < 1e-10 - ), f"Prompt cost incorrect: {prompt_cost} vs {expected_prompt_cost}" + assert abs(prompt_cost - expected_prompt_cost) < 1e-10, ( + f"Prompt cost incorrect: {prompt_cost} vs {expected_prompt_cost}" + ) - assert ( - abs(completion_cost - expected_completion_cost) < 1e-10 - ), f"Completion cost incorrect: {completion_cost} vs {expected_completion_cost}" + assert abs(completion_cost - expected_completion_cost) < 1e-10, ( + f"Completion cost incorrect: {completion_cost} vs {expected_completion_cost}" + ) # Verify it's NOT using only reasoning_tokens (the bug) wrong_cost = 768 * 0.40 / 1_000_000 # Only reasoning tokens - assert ( - abs(completion_cost - wrong_cost) > 1e-6 - ), "Bug detected: Cost calculation is using only reasoning_tokens instead of all completion_tokens!" + assert abs(completion_cost - wrong_cost) > 1e-6, ( + "Bug detected: Cost calculation is using only reasoning_tokens instead of all completion_tokens!" + ) def test_image_count_prevents_text_tokens_fallback(_local_model_cost_map): @@ -3423,13 +2540,9 @@ def test_data_residency_no_uplift_for_pre_march_2026_models(model, _local_model_ usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) base = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai") - regional = generic_cost_per_token( - model=model, usage=usage, custom_llm_provider="openai", data_residency="eu" - ) + regional = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai", data_residency="eu") - assert base == regional, ( - f"{model} should not have a regional uplift, but cost changed with data_residency" - ) + assert base == regional, f"{model} should not have a regional uplift, but cost changed with data_residency" def test_data_residency_no_uplift_for_unmarked_model(_local_model_cost_map): @@ -3537,9 +2650,7 @@ def test_vertex_global_or_absent_location_no_uplift(vertex_location, _local_mode usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - base = generic_cost_per_token( - model="claude-haiku-4-5@20251001", usage=usage, custom_llm_provider="vertex_ai" - ) + base = generic_cost_per_token(model="claude-haiku-4-5@20251001", usage=usage, custom_llm_provider="vertex_ai") located = generic_cost_per_token( model="claude-haiku-4-5@20251001", usage=usage, @@ -3576,10 +2687,7 @@ def test_vertex_uplift_invalid_multiplier_defaults_to_one(): ) assert ( - get_vertex_regional_endpoint_uplift( - {"regional_endpoint_uplift_multiplier": "not-a-number"}, "us-east5" - ) - == 1.0 + get_vertex_regional_endpoint_uplift({"regional_endpoint_uplift_multiplier": "not-a-number"}, "us-east5") == 1.0 ) @@ -3594,9 +2702,7 @@ def test_priority_service_tier_above_threshold_uses_priority_tier_rates_for_cach prompt_tokens=250_000, completion_tokens=1_000, total_tokens=251_000, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=200_000, text_tokens=50_000 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=200_000, text_tokens=50_000), completion_tokens_details=CompletionTokensDetailsWrapper(text_tokens=1_000), ) @@ -3615,52 +2721,13 @@ def test_priority_service_tier_above_threshold_uses_priority_tier_rates_for_cach assert completion_cost == pytest.approx(expected_completion, rel=1e-9) -def test_priority_service_tier_above_threshold_falls_back_to_standard_for_cache_creation( - _local_model_cost_map, -): - """Regression: priority requests against models that publish standard above-threshold - cache_creation rates but no priority variant must fall back to the standard - above-threshold rate, not the priority-base rate. vertex_ai/claude-sonnet-4-5 - has cache_creation_input_token_cost_above_200k_tokens but no _priority sibling.""" - usage = Usage( - prompt_tokens=350_000, - completion_tokens=1_000, - total_tokens=351_000, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=200_000, - cache_creation_tokens=100_000, - text_tokens=50_000, - ), - completion_tokens_details=CompletionTokensDetailsWrapper(text_tokens=1_000), - ) - - prompt_cost, completion_cost = generic_cost_per_token( - model="vertex_ai/claude-sonnet-4-5", - usage=usage, - custom_llm_provider="vertex_ai", - service_tier="priority", - ) - - # vertex_ai/claude-sonnet-4-5 above_200k (no _priority variants): - # input 6e-6, output 2.25e-5, cache_read 6e-7, cache_creation 7.5e-6 - # text 50_000 * 6e-6 = 0.30 - # cache_read 200_000 * 6e-7 = 0.12 - # cache_creation 100_000 * 7.5e-6 = 0.75 - expected_prompt = 50_000 * 6e-6 + 200_000 * 6e-7 + 100_000 * 7.5e-6 - expected_completion = 1_000 * 2.25e-5 - assert prompt_cost == pytest.approx(expected_prompt, rel=1e-9) - assert completion_cost == pytest.approx(expected_completion, rel=1e-9) - - def test_service_tier_suffixes_constant_in_sync_with_enum(): from litellm.litellm_core_utils.llm_cost_calc.utils import _SERVICE_TIER_SUFFIXES from litellm.types.utils import ServiceTier assert set(_SERVICE_TIER_SUFFIXES) == {f"_{st.value}" for st in ServiceTier} # longest-first so a substring match resolves "_ultrafast" before "_fast" - assert list(_SERVICE_TIER_SUFFIXES) == sorted( - _SERVICE_TIER_SUFFIXES, key=len, reverse=True - ) + assert list(_SERVICE_TIER_SUFFIXES) == sorted(_SERVICE_TIER_SUFFIXES, key=len, reverse=True) def test_get_cost_per_unit_falls_back_from_service_tier_key_to_base(): @@ -3674,9 +2741,7 @@ def test_get_cost_per_unit_falls_back_from_service_tier_key_to_base(): "input_cost_per_token_priority": 5e-6, "input_cost_per_token": 2e-6, } - assert ( - _get_cost_per_unit(model_info_direct, "input_cost_per_token_priority") == 5e-6 - ) + assert _get_cost_per_unit(model_info_direct, "input_cost_per_token_priority") == 5e-6 def test_threshold_keys_exclude_service_tier_variants(): @@ -3715,8 +2780,8 @@ def test_threshold_keys_exclude_service_tier_variants(): ("cerebras/qwen-3-32b", "cerebras", 250, 0), ], ) -def test_token_type_cost_breakdown_is_provider_agnostic(_local_model_cost_map, - model, custom_llm_provider, reasoning_tokens, cached_tokens +def test_token_type_cost_breakdown_is_provider_agnostic( + _local_model_cost_map, model, custom_llm_provider, reasoning_tokens, cached_tokens ): """ Reasoning and cache-read costs must be surfaced for every provider that reports @@ -3735,136 +2800,19 @@ def test_token_type_cost_breakdown_is_provider_agnostic(_local_model_cost_map, completion_tokens_details=CompletionTokensDetailsWrapper( reasoning_tokens=reasoning_tokens, text_tokens=2000 - reasoning_tokens ), - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=cached_tokens, text_tokens=1000 - cached_tokens - ), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=cached_tokens, text_tokens=1000 - cached_tokens), ) - breakdown = get_token_type_cost_breakdown( - model=model, custom_llm_provider=custom_llm_provider, usage=usage - ) + breakdown = get_token_type_cost_breakdown(model=model, custom_llm_provider=custom_llm_provider, usage=usage) - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) - reasoning_rate = ( - model_info.get("output_cost_per_reasoning_token") - or model_info["output_cost_per_token"] - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) + reasoning_rate = model_info.get("output_cost_per_reasoning_token") or model_info["output_cost_per_token"] cache_read_rate = model_info.get("cache_read_input_token_cost") or 0.0 assert breakdown.reasoning_cost == pytest.approx(reasoning_tokens * reasoning_rate) assert breakdown.cache_read_cost == pytest.approx(cached_tokens * cache_read_rate) -def test_token_type_cost_breakdown_matches_real_gemini_numbers(_local_model_cost_map): - """Hard-coded against the exact gemini-2.5-flash response that exposed the gap.""" - - usage = Usage( - prompt_tokens=209, - completion_tokens=3996, - total_tokens=4205, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=3114, text_tokens=882 - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=100, text_tokens=109 - ), - ) - - breakdown = get_token_type_cost_breakdown( - model="gemini-2.5-flash", custom_llm_provider="vertex_ai", usage=usage - ) - - assert breakdown.reasoning_cost == pytest.approx(3114 * 2.5e-06) - assert breakdown.cache_read_cost == pytest.approx(100 * 3e-08) - assert breakdown.cache_creation_cost == 0.0 - - -def test_token_type_cost_breakdown_flex_tier_prices_reasoning_at_flex_rate(_local_model_cost_map): - """Regression for the flex-tier breakdown drift: gemini-3.5-flash defines a flat - output_cost_per_reasoning_token (9e-06, the standard output rate) but no _flex - variant, so the breakdown priced reasoning at the standard rate on flex requests - while the total billed it at the flex output rate (4.5e-06). The reasoning - sub-cost then exceeded the entire flex completion cost.""" - - usage = Usage( - prompt_tokens=7, - completion_tokens=320, - total_tokens=327, - completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=315, text_tokens=5), - ) - - breakdown = get_token_type_cost_breakdown( - model="gemini-3.5-flash", - custom_llm_provider="vertex_ai", - usage=usage, - service_tier="flex", - ) - - assert breakdown.reasoning_cost == pytest.approx(315 * 4.5e-06) - - _, flex_completion_cost = generic_cost_per_token( - model="gemini-3.5-flash", - usage=usage, - custom_llm_provider="vertex_ai", - service_tier="flex", - ) - assert breakdown.reasoning_cost <= flex_completion_cost - - standard_breakdown = get_token_type_cost_breakdown( - model="gemini-3.5-flash", - custom_llm_provider="vertex_ai", - usage=usage, - service_tier=None, - ) - assert standard_breakdown.reasoning_cost == pytest.approx(315 * 9e-06) - - -def test_token_type_cost_breakdown_xai_at_exactly_200k_uses_higher_tier_rates(_local_model_cost_map): - - usage = Usage( - prompt_tokens=200_000, - completion_tokens=2_000, - total_tokens=202_000, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=1_500, text_tokens=500 - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=50_000, text_tokens=150_000 - ), - ) - - breakdown = get_token_type_cost_breakdown( - model="grok-4.20-0309-reasoning", custom_llm_provider="xai", usage=usage - ) - - assert breakdown.reasoning_cost == pytest.approx(1_500 * 5e-06) - assert breakdown.cache_read_cost == pytest.approx(50_000 * 4e-07) - - -def test_token_type_cost_breakdown_xai_just_below_200k_uses_base_tier_rates(_local_model_cost_map): - - usage = Usage( - prompt_tokens=199_999, - completion_tokens=2_000, - total_tokens=201_999, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=1_500, text_tokens=500 - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=50_000, text_tokens=149_999 - ), - ) - - breakdown = get_token_type_cost_breakdown( - model="grok-4.20-0309-reasoning", custom_llm_provider="xai", usage=usage - ) - - assert breakdown.reasoning_cost == pytest.approx(1_500 * 2.5e-06) - assert breakdown.cache_read_cost == pytest.approx(50_000 * 2e-07) - - def test_token_type_cost_breakdown_includes_cache_creation_from_top_level_usage(_local_model_cost_map): """ Bedrock/Anthropic report cache tokens as top-level usage fields; the Usage @@ -3881,17 +2829,11 @@ def test_token_type_cost_breakdown_includes_cache_creation_from_top_level_usage( cache_read_input_tokens=120, ) - breakdown = get_token_type_cost_breakdown( - model=model, custom_llm_provider="bedrock", usage=usage - ) + breakdown = get_token_type_cost_breakdown(model=model, custom_llm_provider="bedrock", usage=usage) model_info = litellm.get_model_info(model=model, custom_llm_provider="bedrock") - assert breakdown.cache_creation_cost == pytest.approx( - 300 * model_info["cache_creation_input_token_cost"] - ) - assert breakdown.cache_read_cost == pytest.approx( - 120 * model_info["cache_read_input_token_cost"] - ) + assert breakdown.cache_creation_cost == pytest.approx(300 * model_info["cache_creation_input_token_cost"]) + assert breakdown.cache_read_cost == pytest.approx(120 * model_info["cache_read_input_token_cost"]) def test_token_type_cost_breakdown_reads_cache_write_tokens(_local_model_cost_map): @@ -3906,18 +2848,12 @@ def test_token_type_cost_breakdown_reads_cache_write_tokens(_local_model_cost_ma prompt_tokens=500, completion_tokens=50, total_tokens=550, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=0, cache_write_tokens=300 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=0, cache_write_tokens=300), ) - breakdown = get_token_type_cost_breakdown( - model=model, custom_llm_provider="bedrock", usage=usage - ) + breakdown = get_token_type_cost_breakdown(model=model, custom_llm_provider="bedrock", usage=usage) model_info = litellm.get_model_info(model=model, custom_llm_provider="bedrock") - assert breakdown.cache_creation_cost == pytest.approx( - 300 * model_info["cache_creation_input_token_cost"] - ) + assert breakdown.cache_creation_cost == pytest.approx(300 * model_info["cache_creation_input_token_cost"]) def test_generic_cost_per_token_openai_cache_write_tokens_gpt_5_6(_local_model_cost_map): @@ -3961,9 +2897,7 @@ def test_generic_cost_per_token_backs_out_cache_write_tokens_from_text_tokens(_l prompt_tokens=1000, completion_tokens=10, total_tokens=1010, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=0, cache_write_tokens=800, text_tokens=1000 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=0, cache_write_tokens=800, text_tokens=1000), ) prompt_cost, _ = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai") @@ -3987,24 +2921,16 @@ def test_token_type_cost_breakdown_reconciles_with_generic_total(_local_model_co prompt_tokens=1000, completion_tokens=2000, total_tokens=3000, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=1200, text_tokens=800 - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=300, text_tokens=700 - ), + completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=1200, text_tokens=800), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=300, text_tokens=700), ) prompt_cost, completion_cost = generic_cost_per_token( model=model, usage=usage, custom_llm_provider=custom_llm_provider ) - breakdown = get_token_type_cost_breakdown( - model=model, custom_llm_provider=custom_llm_provider, usage=usage - ) + breakdown = get_token_type_cost_breakdown(model=model, custom_llm_provider=custom_llm_provider, usage=usage) - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) text_output_cost = 800 * model_info["output_cost_per_token"] text_input_cost = 700 * model_info["input_cost_per_token"] @@ -4118,46 +3044,6 @@ def test_billed_token_rates_follow_the_token_tier_the_breakdown_bills_at(monkeyp assert breakdown.reasoning_cost == pytest.approx(200 * rates.output_cost_per_reasoning_token) -def test_a_pinned_billing_time_prices_the_totals_and_the_reported_rates_at_one_moment(monkeypatch): - """Totals and reported rates resolve off-peak pricing on separate paths that each read the - clock, so a window opening between the two reads used to leave them describing one request - at two different prices. Pinned, both must answer for the pinned moment.""" - monkeypatch.setitem( - litellm.model_cost, - "off-peak-model", - { - "input_cost_per_token": 3e-6, - "output_cost_per_token": 15e-6, - "off_peak_pricing": { - "hours_utc": "02:00-03:00", - "input_cost_per_token": 1e-6, - "output_cost_per_token": 5e-6, - }, - "litellm_provider": "openai", - "mode": "chat", - }, - ) - usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - - with pinned_billing_time(datetime(2026, 1, 1, 2, 30, tzinfo=timezone.utc)): - off_peak_prompt_cost, off_peak_completion_cost = generic_cost_per_token( - model="off-peak-model", usage=usage, custom_llm_provider="openai" - ) - off_peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) - with pinned_billing_time(datetime(2026, 1, 1, 12, 30, tzinfo=timezone.utc)): - peak_prompt_cost, peak_completion_cost = generic_cost_per_token( - model="off-peak-model", usage=usage, custom_llm_provider="openai" - ) - peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) - - assert off_peak_rates.input_cost_per_token == pytest.approx(1e-6) - assert peak_rates.input_cost_per_token == pytest.approx(3e-6) - assert off_peak_prompt_cost == pytest.approx(1000 * off_peak_rates.input_cost_per_token) - assert off_peak_completion_cost == pytest.approx(500 * off_peak_rates.output_cost_per_token) - assert peak_prompt_cost == pytest.approx(1000 * peak_rates.input_cost_per_token) - assert peak_completion_cost == pytest.approx(500 * peak_rates.output_cost_per_token) - - def test_the_token_type_breakdown_carries_the_rates_it_billed_at(monkeypatch): """Callers that report both the lines and the rates read the rates off the breakdown rather than resolving them a second time, so the breakdown has to hand back exactly what it billed at.""" @@ -4184,9 +3070,7 @@ def test_the_token_type_breakdown_carries_the_rates_it_billed_at(monkeypatch): breakdown = get_token_type_cost_breakdown(model="xai/tiered-model", custom_llm_provider="xai", usage=usage) - assert breakdown.rates == get_billed_token_rates( - model="xai/tiered-model", custom_llm_provider="xai", usage=usage - ) + assert breakdown.rates == get_billed_token_rates(model="xai/tiered-model", custom_llm_provider="xai", usage=usage) assert breakdown.rates.cache_read_input_token_cost == pytest.approx(6e-7) assert breakdown.cache_read_cost == pytest.approx(100_000 * breakdown.rates.cache_read_input_token_cost) @@ -4194,9 +3078,7 @@ def test_the_token_type_breakdown_carries_the_rates_it_billed_at(monkeypatch): def test_the_token_type_breakdown_reports_no_rates_for_an_unpriced_model(): usage = Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15) - breakdown = get_token_type_cost_breakdown( - model="no-such-model-anywhere", custom_llm_provider="openai", usage=usage - ) + breakdown = get_token_type_cost_breakdown(model="no-such-model-anywhere", custom_llm_provider="openai", usage=usage) assert breakdown.rates is None @@ -4210,9 +3092,7 @@ def test_billed_token_rates_are_none_for_an_unpriced_model(): def test_token_type_cost_breakdown_zero_without_special_tokens(_local_model_cost_map): usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) - breakdown = get_token_type_cost_breakdown( - model="gpt-4o", custom_llm_provider="openai", usage=usage - ) + breakdown = get_token_type_cost_breakdown(model="gpt-4o", custom_llm_provider="openai", usage=usage) assert (breakdown.reasoning_cost, breakdown.cache_read_cost, breakdown.cache_creation_cost) == (0.0, 0.0, 0.0) @@ -4242,8 +3122,8 @@ def test_token_type_cost_breakdown_zero_without_special_tokens(_local_model_cost ), ], ) -def test_token_type_cost_breakdown_openai_responses_api_cache_write_read(_local_model_cost_map, - raw_usage, expect_read, expect_write +def test_token_type_cost_breakdown_openai_responses_api_cache_write_read( + _local_model_cost_map, raw_usage, expect_read, expect_write ): """Regression for #34309: OpenAI Responses API reports cache tokens under input_tokens_details.{cached_tokens, cache_write_tokens}, not the Anthropic-style @@ -4251,25 +3131,18 @@ def test_token_type_cost_breakdown_openai_responses_api_cache_write_read(_local_ cache_read_cost / cache_creation_cost from the transformed usage.""" from litellm.responses.utils import ResponseAPILoggingUtils - model = "gpt-5.6" usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(raw_usage) - breakdown = get_token_type_cost_breakdown( - model=model, custom_llm_provider="openai", usage=usage - ) + breakdown = get_token_type_cost_breakdown(model=model, custom_llm_provider="openai", usage=usage) info = litellm.get_model_info(model=model, custom_llm_provider="openai") if expect_write: - assert breakdown.cache_creation_cost == pytest.approx( - 4012 * info["cache_creation_input_token_cost"] - ) + assert breakdown.cache_creation_cost == pytest.approx(4012 * info["cache_creation_input_token_cost"]) assert breakdown.cache_creation_cost > 0 assert breakdown.cache_read_cost == 0.0 if expect_read: - assert breakdown.cache_read_cost == pytest.approx( - 4012 * info["cache_read_input_token_cost"] - ) + assert breakdown.cache_read_cost == pytest.approx(4012 * info["cache_read_input_token_cost"]) assert breakdown.cache_read_cost > 0 assert breakdown.cache_creation_cost == 0.0 @@ -4303,23 +3176,15 @@ def test_token_type_cost_breakdown_applies_regional_uplift(_local_model_cost_map prompt_tokens=1000, completion_tokens=500, total_tokens=1500, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=200, text_tokens=300 - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=400, text_tokens=600 - ), + completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=200, text_tokens=300), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=400, text_tokens=600), ) - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) uplift = model_info["regional_processing_uplift_multiplier_eu"] assert uplift > 1.0 - base = get_token_type_cost_breakdown( - model=model, custom_llm_provider=custom_llm_provider, usage=usage - ) + base = get_token_type_cost_breakdown(model=model, custom_llm_provider=custom_llm_provider, usage=usage) eu = get_token_type_cost_breakdown( model=model, custom_llm_provider=custom_llm_provider, @@ -4357,20 +3222,14 @@ def test_token_type_cost_breakdown_applies_vertex_regional_uplift(_local_model_c prompt_tokens=1000, completion_tokens=500, total_tokens=1500, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=400, text_tokens=600 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=400, text_tokens=600), ) - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) uplift = model_info["regional_endpoint_uplift_multiplier"] assert uplift > 1.0 - base = get_token_type_cost_breakdown( - model=model, custom_llm_provider=custom_llm_provider, usage=usage - ) + base = get_token_type_cost_breakdown(model=model, custom_llm_provider=custom_llm_provider, usage=usage) regional = get_token_type_cost_breakdown( model=model, custom_llm_provider=custom_llm_provider, @@ -4392,128 +3251,6 @@ def test_token_type_cost_breakdown_applies_vertex_regional_uplift(_local_model_c assert text_input_cost + regional.cache_read_cost == pytest.approx(prompt_cost) -def test_token_type_cost_breakdown_applies_anthropic_geo_multiplier(_local_model_cost_map, monkeypatch): - """ - Anthropic's regional (geo) uplift lives in provider_specific_entry and is - applied to every token type in the totals, so the per-type breakdown must - scale its cache and reasoning line items by it too. Otherwise the logged - cache costs stay at the base rate and the cache uplift is misattributed to - plain input for exactly the cache-heavy regional traffic the uplift targets. - """ - from litellm.llms.anthropic.cost_calculation import ( - cost_per_token as anthropic_cost_per_token, - ) - - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - - model = "claude-test-geo-breakdown-model" - litellm.register_model( - model_cost={ - model: { - "input_cost_per_token": 5e-6, - "output_cost_per_token": 25e-6, - "cache_creation_input_token_cost": 6.25e-6, - "cache_read_input_token_cost": 0.5e-6, - "litellm_provider": "anthropic", - "max_tokens": 8192, - "provider_specific_entry": {"us": 1.1}, - } - } - ) - - def make_usage() -> Usage: - return Usage( - prompt_tokens=10_000, - completion_tokens=500, - total_tokens=10_500, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=2_000, - cache_creation_tokens=6_000, - ), - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=200, text_tokens=300 - ), - ) - - base_usage = make_usage() - geo_usage = make_usage() - geo_usage.inference_geo = "us" - - base = get_token_type_cost_breakdown( - model=model, custom_llm_provider="anthropic", usage=base_usage - ) - geo = get_token_type_cost_breakdown( - model=model, custom_llm_provider="anthropic", usage=geo_usage - ) - - assert base.cache_read_cost == pytest.approx(2_000 * 0.5e-6) - assert base.cache_creation_cost == pytest.approx(6_000 * 6.25e-6) - assert geo.cache_read_cost == pytest.approx(base.cache_read_cost * 1.1) - assert geo.cache_creation_cost == pytest.approx(base.cache_creation_cost * 1.1) - assert geo.reasoning_cost == pytest.approx(base.reasoning_cost * 1.1) - - # The uplifted breakdown must still reconcile with the uplifted totals. - prompt_cost, completion_cost = anthropic_cost_per_token(model=model, usage=geo_usage) - text_input_cost = 2_000 * 5e-6 * 1.1 - text_output_cost = 300 * 25e-6 * 1.1 - assert text_input_cost + geo.cache_read_cost + geo.cache_creation_cost == pytest.approx(prompt_cost) - assert text_output_cost + geo.reasoning_cost == pytest.approx(completion_cost) - - -@pytest.mark.parametrize("details_as_dict", [True, False]) -def test_image_response_input_image_tokens_priced_at_image_rate(details_as_dict): - """ - Image input tokens must be priced at input_cost_per_image_token even when - input_tokens_details is a plain dict, as in OpenAI image edit responses. - - Regression test: dict-shaped input_tokens_details was read with getattr(), - which returns None for dicts, so image input tokens silently fell back to - the text input rate (e.g. $5/M instead of $8/M for gpt-image-2). - """ - from unittest.mock import patch - - from litellm.litellm_core_utils.llm_cost_calc.utils import ( - calculate_image_response_cost_from_usage, - ) - from litellm.types.utils import Usage - - mock_model_info = { - "input_cost_per_token": 5e-6, - "input_cost_per_image_token": 8e-6, - "output_cost_per_image_token": 3e-5, - } - - input_details = {"text_tokens": 19, "image_tokens": 512} - image_response = ImageResponse(data=[ImageObject(b64_json="x")]) - # Mirror the usage shape of a real OpenAI images.edit response: - # a Usage object carrying input_tokens/output_tokens with detail dicts. - image_response.usage = Usage( - prompt_tokens=0, - completion_tokens=0, - total_tokens=689, - input_tokens=531, - input_tokens_details=( - input_details - if details_as_dict - else ImageUsageInputTokensDetails(**input_details) - ), - output_tokens=158, - output_tokens_details={"image_tokens": 158, "text_tokens": 0}, - ) - - with patch( - "litellm.litellm_core_utils.llm_cost_calc.utils.get_model_info", - return_value=mock_model_info, - ): - cost = calculate_image_response_cost_from_usage( - model="gpt-image-2", - image_response=image_response, - custom_llm_provider="openai", - ) - - expected = 19 * 5e-6 + 512 * 8e-6 + 158 * 3e-5 - assert cost is not None - assert round(cost, 12) == round(expected, 12) GEMINI_DAY0_LAUNCH_PRICING = [ ("gemini-3.6-flash", 7.5e-07, 3.75e-06, 7.5e-08), ("gemini/gemini-3.6-flash", 7.5e-07, 3.75e-06, 7.5e-08), @@ -4524,27 +3261,6 @@ GEMINI_DAY0_LAUNCH_PRICING = [ ] -def test_generic_cost_per_token_gemini_36_flash(_local_model_cost_map): - - usage = Usage( - prompt_tokens=1000, - completion_tokens=500, - total_tokens=1500, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=200, - text_tokens=300, - ), - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1000), - ) - prompt_cost, completion_cost = generic_cost_per_token( - model="gemini-3.6-flash", - usage=usage, - custom_llm_provider="gemini", - ) - assert prompt_cost == pytest.approx(0.00075) - assert completion_cost == pytest.approx(0.001875) - - GEMINI_36_FLASH_SERVICE_TIER_PRICING = [ (None, 7.5e-07, 3.75e-06, 7.5e-08), ("flex", 3.75e-07, 1.875e-06, 3.75e-08), @@ -4552,27 +3268,6 @@ GEMINI_36_FLASH_SERVICE_TIER_PRICING = [ ] -def test_generic_cost_per_token_gemini_35_flash_lite(_local_model_cost_map): - - usage = Usage( - prompt_tokens=1000, - completion_tokens=500, - total_tokens=1500, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=200, - text_tokens=300, - ), - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1000), - ) - prompt_cost, completion_cost = generic_cost_per_token( - model="gemini-3.5-flash-lite", - usage=usage, - custom_llm_provider="gemini", - ) - assert prompt_cost == pytest.approx(0.0003) - assert completion_cost == pytest.approx(0.00125) - - GEMINI_35_FLASH_LITE_TIER_RATES_BY_SURFACE = [ ("gemini", None, 3e-07, 2.5e-06, 3e-08), ("gemini", "flex", 1.5e-07, 1.25e-06, 2e-08), @@ -4583,80 +3278,6 @@ GEMINI_35_FLASH_LITE_TIER_RATES_BY_SURFACE = [ ] -@pytest.mark.parametrize( - "service_tier,input_rate,cache_read_rate,cache_write_rate,output_rate", - [ - ("flex", 2e-6, 2e-7, 2.5e-6, 1e-5), - ("priority", 8e-6, 8e-7, 1e-5, 4e-5), - ], -) -def test_service_tier_cache_creation_rates_for_gpt_5_6( - _local_model_cost_map, - service_tier, - input_rate, - cache_read_rate, - cache_write_rate, - output_rate, -): - """Regression: gpt-5.6 publishes cache_creation_input_token_cost_flex/_priority, so a - flex or priority request must bill cache writes at that tier's rate instead of falling - back to the standard cache-write rate.""" - usage = Usage( - prompt_tokens=10_000, - completion_tokens=500, - total_tokens=10_500, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=6_000, - cache_write_tokens=3_000, - text_tokens=1_000, - ), - ) - - prompt_cost, completion_cost = generic_cost_per_token( - model="gpt-5.6-sol", - usage=usage, - custom_llm_provider="openai", - service_tier=service_tier, - ) - - expected_prompt = 1_000 * input_rate + 6_000 * cache_read_rate + 3_000 * cache_write_rate - assert prompt_cost == pytest.approx(expected_prompt, rel=1e-9) - assert completion_cost == pytest.approx(500 * output_rate, rel=1e-9) - - -def test_fast_service_tier_bills_at_the_priority_rate(_local_model_cost_map): - """Regression: OpenAI's Fast mode replaced Priority Processing and costs 2x standard. - - Before the fix "fast" fell through to standard pricing, so a Fast mode request - was billed at half of what it actually costs.""" - from litellm.types.utils import Usage - - usage = Usage( - prompt_tokens=1_000, - completion_tokens=500, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=200), - ) - - standard = generic_cost_per_token( - model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier=None - ) - priority = generic_cost_per_token( - model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier="priority" - ) - fast = generic_cost_per_token( - model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier="fast" - ) - - expected_prompt = 800 * 8e-06 + 200 * 8e-07 - expected_completion = 500 * 4e-05 - - assert fast == priority - assert fast[0] == pytest.approx(expected_prompt, rel=1e-9) - assert fast[1] == pytest.approx(expected_completion, rel=1e-9) - assert fast[0] == pytest.approx(standard[0] * 2, rel=1e-9) - assert fast[1] == pytest.approx(standard[1] * 2, rel=1e-9) - - def test_fast_service_tier_is_case_insensitive(_local_model_cost_map): from litellm.types.utils import Usage @@ -4664,27 +3285,7 @@ def test_fast_service_tier_is_case_insensitive(_local_model_cost_map): assert generic_cost_per_token( model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier="FAST" - ) == generic_cost_per_token( - model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier="fast" - ) - - -def test_fast_service_tier_matches_priority_above_the_context_threshold(_local_model_cost_map): - """The above-threshold branch resolves its own cost keys, so the alias has to hold there too.""" - from litellm.types.utils import Usage - - usage = Usage(prompt_tokens=300_000, completion_tokens=1_000) - - fast = generic_cost_per_token( - model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier="fast" - ) - priority = generic_cost_per_token( - model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier="priority" - ) - - assert fast == priority - assert fast[0] == pytest.approx(300_000 * 1.6e-05, rel=1e-9) - assert fast[1] == pytest.approx(1_000 * 6e-05, rel=1e-9) + ) == generic_cost_per_token(model="gpt-5.6-sol", usage=usage, custom_llm_provider="openai", service_tier="fast") def test_priority_reasoning_tokens_bill_at_the_priority_output_rate(_local_model_cost_map): @@ -4811,26 +3412,6 @@ GEMINI_37_FLASH_LAUNCH_PRICING = [ ] -def test_generic_cost_per_token_gemini_37_flash(_local_model_cost_map): - usage = Usage( - prompt_tokens=1000, - completion_tokens=500, - total_tokens=1500, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=200, - text_tokens=300, - ), - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1000), - ) - prompt_cost, completion_cost = generic_cost_per_token( - model="gemini-3.7-flash", - usage=usage, - custom_llm_provider="gemini", - ) - assert prompt_cost == pytest.approx(0.00075) - assert completion_cost == pytest.approx(0.001875) - - GEMINI_38_FLASH_LAUNCH_PRICING = [ ("gemini-3.8-flash", 7.5e-07, 3.75e-06, 7.5e-08), ("gemini/gemini-3.8-flash", 7.5e-07, 3.75e-06, 7.5e-08), @@ -4878,60 +3459,6 @@ def test_gemini_38_flash_matches_37_flash_promotional_pricing(prefix, _local_mod assert new_model[field] == old_model[field], field -def test_generic_cost_per_token_gemini_38_flash(_local_model_cost_map): - usage = Usage( - prompt_tokens=1000, - completion_tokens=500, - total_tokens=1500, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=200, - text_tokens=300, - ), - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1000), - ) - prompt_cost, completion_cost = generic_cost_per_token( - model="gemini-3.8-flash", - usage=usage, - custom_llm_provider="gemini", - ) - assert prompt_cost == pytest.approx(0.00075) - assert completion_cost == pytest.approx(0.001875) - - -def test_generic_cost_per_token_grok_46(_local_model_cost_map): - usage = Usage( - prompt_tokens=1_000, - completion_tokens=500, - total_tokens=1_500, - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=1_000), - ) - prompt_cost, completion_cost = generic_cost_per_token( - model="grok-4.6", - usage=usage, - custom_llm_provider="xai", - ) - assert prompt_cost == pytest.approx(1_000 * 2e-06) - assert completion_cost == pytest.approx(500 * 6e-06) - - -def test_generic_cost_per_token_grok_46_long_context(_local_model_cost_map): - usage = Usage( - prompt_tokens=250_000, - completion_tokens=1_000, - total_tokens=251_000, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=50_000, text_tokens=200_000 - ), - ) - prompt_cost, completion_cost = generic_cost_per_token( - model="grok-4.6", - usage=usage, - custom_llm_provider="xai", - ) - assert prompt_cost == pytest.approx(200_000 * 4e-06 + 50_000 * 1e-06) - assert completion_cost == pytest.approx(1_000 * 1.2e-05) - - @pytest.mark.parametrize( ("model", "provider", "image_token_rate"), [ @@ -5041,9 +3568,7 @@ def test_generic_cost_per_token_bills_reasoning_nested_in_text_tokens_once(_loca prompt_tokens_details=PromptTokensDetailsWrapper( text_tokens=152, image_tokens=194, audio_tokens=0, cached_tokens=128 ), - completion_tokens_details=CompletionTokensDetailsWrapper( - text_tokens=29, audio_tokens=0, reasoning_tokens=19 - ), + completion_tokens_details=CompletionTokensDetailsWrapper(text_tokens=29, audio_tokens=0, reasoning_tokens=19), ) prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai") @@ -5069,9 +3594,7 @@ def test_generic_cost_per_token_keeps_billing_reasoning_reported_beside_text_tok prompt_tokens=100, completion_tokens=44, total_tokens=144, - completion_tokens_details=CompletionTokensDetailsWrapper( - text_tokens=25, audio_tokens=0, reasoning_tokens=19 - ), + completion_tokens_details=CompletionTokensDetailsWrapper(text_tokens=25, audio_tokens=0, reasoning_tokens=19), ) _, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai") @@ -5124,45 +3647,6 @@ def test_generic_cost_per_token_bills_nested_reasoning_once_beside_audio_output( ) -def test_cached_realtime_audio_tokens_billed_at_audio_cache_read_rate( - _local_model_cost_map: None, -) -> None: - usage = Usage( - prompt_tokens=283, - completion_tokens=0, - total_tokens=283, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=116, - audio_tokens=167, - cached_tokens=192, - cached_tokens_details={"text_tokens": 64, "audio_tokens": 128}, - ), - ) - - prompt_cost, _ = generic_cost_per_token( - model="gpt-realtime-2", usage=usage, custom_llm_provider="openai" - ) - assert prompt_cost == pytest.approx(0.0015328) - - -def test_prompt_tokens_details_without_cached_tokens_details_unchanged( - _local_model_cost_map: None, -) -> None: - usage = Usage( - prompt_tokens=283, - completion_tokens=0, - total_tokens=283, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=116, audio_tokens=167, cached_tokens=192 - ), - ) - - prompt_cost, _ = generic_cost_per_token( - model="gpt-realtime-2", usage=usage, custom_llm_provider="openai" - ) - assert prompt_cost == pytest.approx(0.0029888) - - def test_cached_audio_tokens_fall_back_to_cache_read_input_token_cost() -> None: model_info: ModelInfo = { "input_cost_per_token": 4e-6, @@ -5191,43 +3675,6 @@ def test_cached_audio_tokens_fall_back_to_cache_read_input_token_cost() -> None: assert prompt_cost == pytest.approx(expected) -def test_cached_audio_tokens_capped_at_cached_tokens(_local_model_cost_map: None) -> None: - """Nested cached_tokens_details exceeding cached_tokens must not over-subtract the audio bucket.""" - usage = Usage( - prompt_tokens=283, - completion_tokens=0, - total_tokens=283, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=116, - audio_tokens=167, - cached_tokens=100, - cached_tokens_details={"audio_tokens": 128}, - ), - ) - - prompt_cost, _ = generic_cost_per_token( - model="gpt-realtime-2", usage=usage, custom_llm_provider="openai" - ) - assert prompt_cost == pytest.approx(116 * 4e-6 + (167 - 100) * 32e-6 + 100 * 4e-7) - - -def test_cached_audio_tokens_billed_at_audio_cache_rate_through_model_info_lookup(_local_model_cost_map: None) -> None: - usage = Usage( - prompt_tokens=1000, - completion_tokens=0, - total_tokens=1000, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=400, - audio_tokens=600, - cached_tokens=500, - cached_tokens_details={"text_tokens": 100, "audio_tokens": 400}, - ), - ) - - prompt_cost, _ = generic_cost_per_token(model="gpt-realtime-2.1-mini", usage=usage, custom_llm_provider="openai") - assert prompt_cost == pytest.approx(300 * 6e-7 + 100 * 6e-8 + 200 * 1e-5 + 400 * 3e-7) - - def test_cache_read_breakdown_splits_cached_audio_at_the_audio_cache_rate(_local_model_cost_map: None) -> None: usage = Usage( prompt_tokens=4863, @@ -5250,34 +3697,6 @@ def test_cache_read_breakdown_splits_cached_audio_at_the_audio_cache_rate(_local assert prompt_cost == pytest.approx((1693 - 896) * 6e-7 + (3170 - 1920) * 1e-5 + breakdown.cache_read_cost) -@pytest.mark.parametrize( - ("model", "custom_llm_provider", "expected_prompt_cost"), - ( - pytest.param("azure/gpt-realtime-2025-08-28", "azure", 300 * 4e-6 + 100 * 4e-7 + 200 * 3.2e-5 + 400 * 4e-7, id="azure-gpt-realtime"), - pytest.param("azure/gpt-realtime-1.5-2026-02-23", "azure", 300 * 4e-6 + 100 * 4e-7 + 200 * 3.2e-5 + 400 * 4e-7, id="azure-gpt-realtime-1.5"), - pytest.param("azure/gpt-realtime-mini", "azure", 300 * 6e-7 + 100 * 6e-8 + 200 * 1e-5 + 400 * 3e-7, id="azure-gpt-realtime-mini"), - pytest.param("gpt-realtime-mini", "openai", 300 * 6e-7 + 100 * 6e-8 + 200 * 1e-5 + 400 * 3e-7, id="openai-gpt-realtime-mini"), - ), -) -def test_realtime_models_bill_cached_text_and_audio_at_their_cache_read_rates( - _local_model_cost_map: None, model: str, custom_llm_provider: str, expected_prompt_cost: float -) -> None: - usage = Usage( - prompt_tokens=1000, - completion_tokens=0, - total_tokens=1000, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=400, - audio_tokens=600, - cached_tokens=500, - cached_tokens_details={"text_tokens": 100, "audio_tokens": 400}, - ), - ) - - prompt_cost, _ = generic_cost_per_token(model=model, usage=usage, custom_llm_provider=custom_llm_provider) - assert prompt_cost == pytest.approx(expected_prompt_cost) - - def test_generic_cost_per_token_bills_cache_creation_at_the_input_rate_without_a_write_price(): """Azure and OpenAI publish no cache-write price and bill cache writes as ordinary input. A deployment priced with only input, output, and cache-read rates must bill the creation @@ -5307,7 +3726,9 @@ def test_generic_cost_per_token_bills_cache_creation_at_the_input_rate_without_a ("cache_rates", "current_time", "expected_creation", "expected_creation_1h"), ( pytest.param({}, None, 2e-7, 2e-7, id="no-write-price-uses-the-input-rate"), - pytest.param({"cache_creation_input_token_cost": 2.5e-7}, None, 2.5e-7, 2.5e-7, id="no-1h-price-uses-the-write-price"), + pytest.param( + {"cache_creation_input_token_cost": 2.5e-7}, None, 2.5e-7, 2.5e-7, id="no-1h-price-uses-the-write-price" + ), pytest.param({"cache_creation_input_token_cost": 0.0}, None, 0.0, 0.0, id="explicit-zero-stays-zero"), pytest.param( {"off_peak_pricing": {"hours_utc": "00:00-23:59", "input_cost_per_token": 1e-7}}, @@ -5344,4 +3765,3 @@ def test_get_token_base_cost_resolves_missing_cache_write_rates_like_the_tiered_ assert creation == pytest.approx(expected_creation) assert creation_1h == pytest.approx(expected_creation_1h) - diff --git a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py index 53fee36b3a8..76467dfb7b1 100644 --- a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py +++ b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py @@ -86,21 +86,6 @@ def test_validation_accepts_healthy_file_with_meta_keys(): ) -def test_validation_rejects_significant_shrink_vs_backup(): - # 600 real models vs a 2000-model backup is below the 50% shrink threshold. - shrunk = _make_models(600) - shrunk[FALLBACK_GENERALIZATIONS_KEY] = {"rules": []} - assert ( - GetModelCostMap.validate_model_cost_map( - fetched_map=shrunk, - backup_model_count=2000, - min_model_count=50, - max_shrink_ratio=0.5, - ) - is False - ) - - def test_finalize_pops_key_and_installs_rules(): previous = list(get_fallback_generalization_rules()) try: @@ -134,24 +119,6 @@ def test_finalize_with_no_block_clears_rules(): set_fallback_generalizations(previous) -def test_shipped_backup_carries_the_claude_routing_rules(): - """The bundled backup must ship the Claude routing rules so a fresh install - (or an offline fallback) routes unknown Claude models without code changes. - Bedrock-syntax ids must hit the bedrock rule before the bare-id Anthropic rule.""" - backup = GetModelCostMap.load_local_model_cost_map() - rules = backup.get(FALLBACK_GENERALIZATIONS_KEY, {}).get("rules", []) - names = [r.get("name") for r in rules] - assert names.index("bedrock-claude-ids") < names.index("anthropic-claude-ids") - - previous = list(get_fallback_generalization_rules()) - try: - set_fallback_generalizations(rules) - assert match_routing_generalization("claude-opus-4-9") == "anthropic" - assert match_routing_generalization("global.anthropic.claude-opus-4-9") == "bedrock" - finally: - set_fallback_generalizations(previous) - - def test_shipped_routing_rules_never_match_through_an_unrecognized_namespace(): """Routing rules decide ``litellm_provider`` for otherwise-unknown ids, and the proxy's wildcard access check (``can_key_call_model`` with a ``bedrock/*`` key) @@ -188,43 +155,6 @@ def test_shipped_routing_rules_never_match_through_an_unrecognized_namespace(): set_fallback_generalizations(previous) -def test_shipped_backup_marks_claude_4_6_plus_adaptive_not_4_0(): - """Adaptive thinking is data, not code. The bundled backup must carry - supports_adaptive_thinking on genuine Claude >= 4.6 entries (every provider - route) and on the version-gated anthropic-claude-adaptive-thinking rule for - unmapped future Claudes, while leaving the dated Claude 4.0 names - ("...-4-20250514") unflagged so a date can never be mistaken for a 4.6+ minor - version. The version-neutral claude-family-baseline capability rule must not flag - it, so an unmapped sub-4.6 name resolves but stays non-adaptive. The adaptive rule - carries only its delta; capability unioning stacks it onto the baseline, so the - baseline block is never duplicated across rules and no rule needs ``extends``.""" - backup = GetModelCostMap.load_local_model_cost_map() - - rules = backup[FALLBACK_GENERALIZATIONS_KEY]["rules"] - baseline_rule = next(r for r in rules if r.get("name") == "claude-family-baseline") - adaptive_rule = next(r for r in rules if r.get("name") == "claude-adaptive-thinking") - assert "supports_adaptive_thinking" not in baseline_rule["model_info"] - assert "litellm_provider" not in baseline_rule["model_info"] - assert adaptive_rule["model_info"] == {"supports_adaptive_thinking": True} - assert all("extends" not in r for r in rules) - - for adaptive in [ - "anthropic.claude-opus-4-8", - "vertex_ai/claude-opus-4-6@default", - "us.anthropic.claude-sonnet-4-6", - "openrouter/anthropic/claude-opus-4.7", - "azure_ai/claude-opus-4-7", - ]: - assert backup[adaptive]["supports_adaptive_thinking"] is True, adaptive - - for non_adaptive in [ - "claude-opus-4-20250514", - "us.anthropic.claude-opus-4-20250514-v1:0", - "claude-opus-4-5", - ]: - assert "supports_adaptive_thinking" not in backup[non_adaptive], non_adaptive - - # OpenRouter headline rates from GET https://openrouter.ai/api/v1/models. # These were the catalog values that disagreed with that API (and, for the # two spotlight models, the public model pages that their source fields cite). @@ -659,41 +589,6 @@ def test_boot_load_records_the_blob_id_of_the_bytes_served_and_the_fetch_etag(): assert source["loaded_at"] is not None -def test_boot_load_fallback_to_the_backup_reports_its_blob_id_and_drops_the_remote_etag(): - remote, _ = _mock_client( - [httpx.Response(200, headers={"ETag": 'W/"boot"'}, content=_real_map_bytes())], client_cls=httpx.Client - ) - get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=remote) - failing, _ = _mock_client([httpx.Response(404)], client_cls=httpx.Client) - - get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=failing) - - source = get_model_cost_map_source_info() - assert source["source"] == "local" - assert source["etag"] is None - assert source["source_revision"] == _bundled_blob_id() - - -def test_boot_load_that_fails_the_integrity_check_reports_the_backup_not_the_rejected_fetch(): - remote, _ = _mock_client( - [httpx.Response(200, headers={"ETag": 'W/"boot"'}, content=_real_map_bytes())], client_cls=httpx.Client - ) - get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=remote) - shrunk_body = b'{"gpt-5.4-mini": {"mode": "chat", "input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06}}' - shrunk, _ = _mock_client( - [httpx.Response(200, headers={"ETag": 'W/"shrunk"'}, content=shrunk_body)], client_cls=httpx.Client - ) - - get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=shrunk) - - source = get_model_cost_map_source_info() - assert source["source"] == "local" - assert source["fallback_reason"] == "Remote data failed integrity validation" - assert source["etag"] is None - assert source["source_revision"] == _bundled_blob_id() - assert source["source_revision"] != git_blob_id(shrunk_body) - - @pytest.mark.parametrize( ("argv0", "request_count"), [ diff --git a/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py b/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py index 9b20192c3f2..c9721aea7fd 100644 --- a/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py +++ b/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py @@ -4,7 +4,7 @@ from typing import Final import pytest from pydantic import TypeAdapter -from litellm import completion_cost, cost_per_token, get_model_info +from litellm import completion_cost from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider from litellm.types.utils import TranscriptionResponse @@ -52,58 +52,6 @@ def test_azure_ai_catalog_name_routes_to_azure_ai(catalog_name: str) -> None: assert (routed_model, provider) == (catalog_name, "azure_ai") -@pytest.mark.usefixtures("local_model_cost_map") -@pytest.mark.parametrize("catalog_name", TOKEN_PRICED_NAMES) -def test_azure_ai_catalog_name_charges_its_own_entry_per_token(catalog_name: str) -> None: - entry: Final = get_model_info(f"azure_ai/{catalog_name}") - prompt_cost, completion_cost_usd = cost_per_token( - model=f"azure_ai/{catalog_name}", prompt_tokens=A_MILLION, completion_tokens=A_MILLION - ) - assert prompt_cost > 0 - assert prompt_cost == pytest.approx(A_MILLION * entry["input_cost_per_token"]) - assert completion_cost_usd == pytest.approx(A_MILLION * entry["output_cost_per_token"]) - - -@pytest.mark.usefixtures("local_model_cost_map") -@pytest.mark.parametrize("catalog_name", TOKEN_PRICED_NAMES) -def test_azure_ai_catalog_name_prices_the_same_in_any_casing(catalog_name: str) -> None: - lowercase_cost = cost_per_token(model=f"azure_ai/{catalog_name}", prompt_tokens=A_MILLION, completion_tokens=0) - upper_cost = cost_per_token(model=f"azure_ai/{catalog_name.upper()}", prompt_tokens=A_MILLION, completion_tokens=0) - assert upper_cost == lowercase_cost - - -@pytest.mark.usefixtures("local_model_cost_map") -@pytest.mark.parametrize("catalog_name", GROK_4_20_NAMES) -def test_azure_ai_grok_4_20_bills_cached_prompt_tokens_at_the_input_price(catalog_name: str) -> None: - uncached_prompt_cost, _ = cost_per_token( - model=f"azure_ai/{catalog_name}", prompt_tokens=A_MILLION, completion_tokens=0 - ) - cached_prompt_cost, _ = cost_per_token( - model=f"azure_ai/{catalog_name}", - prompt_tokens=A_MILLION, - completion_tokens=0, - cache_read_input_tokens=A_MILLION, - ) - assert uncached_prompt_cost > 0 - assert cached_prompt_cost == pytest.approx(uncached_prompt_cost) - - -@pytest.mark.usefixtures("local_model_cost_map") -def test_azure_ai_whisper_catalog_name_is_priced_per_second() -> None: - one_second_cost: Final = _whisper_transcription_cost(1) - one_hour_cost: Final = _whisper_transcription_cost(AN_HOUR_IN_SECONDS) - assert one_second_cost > 0 - assert one_hour_cost == pytest.approx(AN_HOUR_IN_SECONDS * one_second_cost) - - -@pytest.mark.parametrize("catalog_name", CATALOG_NAMES) -def test_azure_ai_catalog_entry_source_and_backup_match(catalog_name: str) -> None: - main_entry = _cost_map_entry(MAIN_COST_MAP, catalog_name) - backup_entry = _cost_map_entry(BACKUP_COST_MAP, catalog_name) - - assert backup_entry == main_entry - - def test_azure_ai_model_router_spellings_share_one_entry() -> None: underscore_entry = _cost_map_entry(MAIN_COST_MAP, "model_router") hyphen_entry = _cost_map_entry(MAIN_COST_MAP, "model-router") diff --git a/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py b/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py index fda3c8ceb8f..3f54b695fef 100644 --- a/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py +++ b/tests/test_litellm/llms/bedrock/test_cross_region_inference_profile_mapping.py @@ -4,18 +4,13 @@ from typing import NamedTuple import pytest - import litellm from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig from litellm.llms.bedrock.common_utils import BedrockModelInfo -from litellm.utils import _get_model_info_helper -from litellm.cost_calculator import completion_cost from litellm.types.utils import ( Choices, Message, ModelResponse, - PromptTokensDetailsWrapper, - Usage, ) @@ -31,8 +26,7 @@ def local_model_cost_map(monkeypatch): litellm.bedrock_converse_models.update( key for key, value in litellm.model_cost.items() - if isinstance(value, dict) - and value.get("litellm_provider") == "bedrock_converse" + if isinstance(value, dict) and value.get("litellm_provider") == "bedrock_converse" ) yield finally: @@ -56,45 +50,69 @@ class GptProfile(NamedTuple): GPT_5_6_PROFILES = [ GptProfile( model_id="us.openai.gpt-5.6-sol", - input_cost=4.4e-06, input_cost_above_272k=8.8e-06, - cache_write=5.5e-06, cache_write_above_272k=1.1e-05, - cache_read=4.4e-07, cache_read_above_272k=8.8e-07, - output_cost=2.2e-05, output_cost_above_272k=3.3e-05, + input_cost=4.4e-06, + input_cost_above_272k=8.8e-06, + cache_write=5.5e-06, + cache_write_above_272k=1.1e-05, + cache_read=4.4e-07, + cache_read_above_272k=8.8e-07, + output_cost=2.2e-05, + output_cost_above_272k=3.3e-05, ), GptProfile( model_id="global.openai.gpt-5.6-sol", - input_cost=4e-06, input_cost_above_272k=8e-06, - cache_write=5e-06, cache_write_above_272k=1e-05, - cache_read=4e-07, cache_read_above_272k=8e-07, - output_cost=2e-05, output_cost_above_272k=3e-05, + input_cost=4e-06, + input_cost_above_272k=8e-06, + cache_write=5e-06, + cache_write_above_272k=1e-05, + cache_read=4e-07, + cache_read_above_272k=8e-07, + output_cost=2e-05, + output_cost_above_272k=3e-05, ), GptProfile( model_id="us.openai.gpt-5.6-terra", - input_cost=2.2e-06, input_cost_above_272k=4.4e-06, - cache_write=2.75e-06, cache_write_above_272k=5.5e-06, - cache_read=2.2e-07, cache_read_above_272k=4.4e-07, - output_cost=1.32e-05, output_cost_above_272k=1.98e-05, + input_cost=2.2e-06, + input_cost_above_272k=4.4e-06, + cache_write=2.75e-06, + cache_write_above_272k=5.5e-06, + cache_read=2.2e-07, + cache_read_above_272k=4.4e-07, + output_cost=1.32e-05, + output_cost_above_272k=1.98e-05, ), GptProfile( model_id="global.openai.gpt-5.6-terra", - input_cost=2e-06, input_cost_above_272k=4e-06, - cache_write=2.5e-06, cache_write_above_272k=5e-06, - cache_read=2e-07, cache_read_above_272k=4e-07, - output_cost=1.2e-05, output_cost_above_272k=1.8e-05, + input_cost=2e-06, + input_cost_above_272k=4e-06, + cache_write=2.5e-06, + cache_write_above_272k=5e-06, + cache_read=2e-07, + cache_read_above_272k=4e-07, + output_cost=1.2e-05, + output_cost_above_272k=1.8e-05, ), GptProfile( model_id="us.openai.gpt-5.6-luna", - input_cost=2.2e-07, input_cost_above_272k=4.4e-07, - cache_write=2.75e-07, cache_write_above_272k=5.5e-07, - cache_read=2.2e-08, cache_read_above_272k=4.4e-08, - output_cost=1.32e-06, output_cost_above_272k=1.98e-06, + input_cost=2.2e-07, + input_cost_above_272k=4.4e-07, + cache_write=2.75e-07, + cache_write_above_272k=5.5e-07, + cache_read=2.2e-08, + cache_read_above_272k=4.4e-08, + output_cost=1.32e-06, + output_cost_above_272k=1.98e-06, ), GptProfile( model_id="global.openai.gpt-5.6-luna", - input_cost=2e-07, input_cost_above_272k=4e-07, - cache_write=2.5e-07, cache_write_above_272k=5e-07, - cache_read=2e-08, cache_read_above_272k=4e-08, - output_cost=1.2e-06, output_cost_above_272k=1.8e-06, + input_cost=2e-07, + input_cost_above_272k=4e-07, + cache_write=2.5e-07, + cache_write_above_272k=5e-07, + cache_read=2e-08, + cache_read_above_272k=4e-08, + output_cost=1.2e-06, + output_cost_above_272k=1.8e-06, ), ] @@ -116,112 +134,18 @@ def _bedrock_response(model, usage): ) -def test_proxy_cost_calculation_scenario(): - """Test exact GitHub issue scenario: proxy cost calculation""" - model = "litellm_proxy/bedrock/us.anthropic.claude-3-5-haiku-20241022-v1:0" - - # Test model info lookup works - model_info = _get_model_info_helper( - model=model, custom_llm_provider="litellm_proxy" - ) - assert model_info is not None - - # Test cost calculation works - response = ModelResponse( - id="test", - created=1234567890, - model=model, - object="chat.completion", - choices=[ - Choices( - finish_reason="stop", - index=0, - message=Message(content="Test", role="assistant"), - ) - ], - usage=Usage(total_tokens=150, prompt_tokens=100, completion_tokens=50), - ) - - cost = completion_cost( - completion_response=response, model=model, custom_llm_provider="litellm_proxy" - ) - expected_cost = (100 * 8e-07) + (50 * 4e-06) - assert cost == expected_cost - - @pytest.mark.parametrize("profile", GPT_5_6_PROFILES, ids=lambda p: p.model_id) def test_bedrock_gpt_5_6_profiles_route_to_converse(profile, local_model_cost_map): """GPT-5.6 is served by Converse on bedrock-runtime, never by Invoke.""" assert BedrockModelInfo.get_bedrock_route(f"bedrock/{profile.model_id}") == "converse" -def test_bedrock_gpt_5_6_above_272k_tier_applies_to_cost(local_model_cost_map): - """A prompt over 272K tokens is billed at the long-context rate, not the base rate.""" - response = _bedrock_response( - "bedrock/us.openai.gpt-5.6-sol", - Usage(prompt_tokens=300000, completion_tokens=1000, total_tokens=301000), - ) - - cost = completion_cost( - completion_response=response, - model="bedrock/us.openai.gpt-5.6-sol", - custom_llm_provider="bedrock", - ) - - assert cost == pytest.approx((300000 * 8.8e-06) + (1000 * 3.3e-05), rel=1e-9) - - -def test_bedrock_gpt_5_6_bills_cache_read_tokens(local_model_cost_map): - """Bedrock caches long prefixes implicitly and reports them, so a cache-read turn - must be billed at the cache rate rather than dropped to zero.""" - usage = Usage( - prompt_tokens=15611, - completion_tokens=5, - total_tokens=15616, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=15609), - ) - response = _bedrock_response("bedrock/us.openai.gpt-5.6-sol", usage) - - cost = completion_cost( - completion_response=response, - model="bedrock/us.openai.gpt-5.6-sol", - custom_llm_provider="bedrock", - ) - - expected = (2 * 4.4e-06) + (15609 * 4.4e-07) + (5 * 2.2e-05) - assert cost == pytest.approx(expected, rel=1e-9) - # Without cache_read_input_token_cost the cached prefix bills at zero. - assert cost > (15611 * 4.4e-06) * 0.1 - - -def test_bedrock_gpt_5_6_bills_cache_write_tokens(local_model_cost_map): - """The write side of the same cache cycle is billed at the 30m cache-write rate.""" - usage = Usage( - prompt_tokens=15611, - completion_tokens=5, - total_tokens=15616, - cache_creation_input_tokens=15609, - ) - response = _bedrock_response("bedrock/us.openai.gpt-5.6-sol", usage) - - cost = completion_cost( - completion_response=response, - model="bedrock/us.openai.gpt-5.6-sol", - custom_llm_provider="bedrock", - ) - - expected = (2 * 4.4e-06) + (15609 * 5.5e-06) + (5 * 2.2e-05) - assert cost == pytest.approx(expected, rel=1e-9) - - @pytest.mark.parametrize("profile", GPT_5_6_PROFILES, ids=lambda p: p.model_id) def test_bedrock_gpt_5_6_offers_tools_and_reasoning_effort_but_not_thinking(profile, local_model_cost_map): """GPT-5.x on Converse maps reasoning_effort to reasoning.effort, so reasoning_effort is offered while the Anthropic-only thinking/output_config are not, alongside the tool params these models accept.""" - supported = AmazonConverseConfig().get_supported_openai_params( - model=f"bedrock/{profile.model_id}" - ) + supported = AmazonConverseConfig().get_supported_openai_params(model=f"bedrock/{profile.model_id}") assert "tools" in supported assert "tool_choice" in supported diff --git a/tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py b/tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py deleted file mode 100644 index 1f878930207..00000000000 --- a/tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py +++ /dev/null @@ -1,44 +0,0 @@ -from pathlib import Path - -import pytest - -import litellm -from litellm.cost_calculator import completion_cost -from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo - -COST_PER_PAGE = 0.0015 -REPO_ROOT = Path(__file__).parents[5] -COST_MAPS = [ - REPO_ROOT / "model_prices_and_context_window.json", - REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json", -] -MODELS = [("cohere/parse-v5.0", "cohere"), ("azure_ai/Cohere-parse-v5", "azure_ai")] - - -def _ocr_response(model: str, pages_processed: int) -> OCRResponse: - return OCRResponse( - pages=[OCRPage(index=i, markdown=f"page {i}") for i in range(pages_processed)], - model=model, - usage_info=OCRUsageInfo(pages_processed=pages_processed), - ) - - -@pytest.mark.parametrize("model, provider", MODELS) -def test_model_info_resolves_ocr_mode_and_price(local_model_cost_map, model: str, provider: str) -> None: - info = litellm.get_model_info(model=model, custom_llm_provider=provider) - - assert info["mode"] == "ocr" - assert info["ocr_cost_per_page"] == COST_PER_PAGE - - -@pytest.mark.parametrize("model, provider", MODELS) -@pytest.mark.parametrize("pages_processed", [1, 3]) -def test_cost_scales_with_billed_pages(local_model_cost_map, model: str, provider: str, pages_processed: int) -> None: - cost = completion_cost( - completion_response=_ocr_response(model.split("/", 1)[1], pages_processed), - model=model, - custom_llm_provider=provider, - call_type="ocr", - ) - - assert cost == pytest.approx(COST_PER_PAGE * pages_processed) diff --git a/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py b/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py index 904a625ef86..f5d60dd0d32 100644 --- a/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py +++ b/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py @@ -1,4 +1,3 @@ -import json from decimal import Decimal from pathlib import Path from typing import Final @@ -163,29 +162,6 @@ def test_legacy_endpoint_names_still_resolve(local_model_cost_map: None) -> None assert completion_cost == pytest.approx(100 * info["output_cost_per_token"]) -@pytest.mark.parametrize("model", NEW_MODELS) -def test_new_models_carry_cache_pricing(local_model_cost_map: None, model: str) -> None: - info: Final = _model_info(model) - - assert info["input_cost_per_token"] > 0 - assert info["output_cost_per_token"] > 0 - assert info["cache_creation_input_token_cost"] > info["input_cost_per_token"] - assert info["cache_read_input_token_cost"] < info["input_cost_per_token"] - assert info["supports_prompt_caching"] is True - - -def test_every_priced_databricks_model_declares_cache_rates(local_model_cost_map: None) -> None: - undeclared: Final = [ - model - for model, info in litellm.model_cost.items() - if model.startswith("databricks/") - and info.get("input_cost_per_token") is not None - and any(info.get(field) is None for field in CACHE_FIELDS) - ] - - assert undeclared == [] - - def test_models_without_a_cache_discount_bill_cache_tokens_at_the_input_rate( local_model_cost_map: None, ) -> None: @@ -204,34 +180,6 @@ def test_models_without_a_cache_discount_bill_cache_tokens_at_the_input_rate( assert prompt_cost > 8000 * info["input_cost_per_token"] -def test_every_model_without_published_cache_dbu_bills_cache_at_its_own_input_rate( - local_model_cost_map: None, -) -> None: - without_published_rates: Final = [ - model - for model, info in litellm.model_cost.items() - if model.startswith("databricks/") - and info.get("input_cost_per_token") - and model not in PUBLISHED_DBU_PER_MILLION - ] - - assert len(without_published_rates) == 14 - for model in without_published_rates: - info = _model_info(model) - for field in CACHE_FIELDS: - assert info[field] == pytest.approx(info["input_cost_per_token"]), (model, field) - - -@pytest.mark.parametrize("model", NEW_MODELS) -def test_backup_price_map_matches_main(model: str) -> None: - main_cost: Final = json.loads(MAIN_PRICES.read_text()) - backup_cost: Final = json.loads(BACKUP_PRICES.read_text()) - - assert model in main_cost - assert model in backup_cost - assert backup_cost[model] == main_cost[model] - - def test_sonnet_5_ships_standard_rates_not_introductory(local_model_cost_map: None) -> None: sonnet_5: Final = _model_info("databricks/databricks-claude-sonnet-5") sonnet_4_6: Final = _model_info("databricks/databricks-claude-sonnet-4-6") diff --git a/tests/test_litellm/llms/databricks/test_databricks_pricing.py b/tests/test_litellm/llms/databricks/test_databricks_pricing.py deleted file mode 100644 index 1f8816f5076..00000000000 --- a/tests/test_litellm/llms/databricks/test_databricks_pricing.py +++ /dev/null @@ -1,51 +0,0 @@ -import json -import os -import sys - - -def test_databricks_pricing_integrity(): - """ - Verifies that for all Databricks models in model_prices_and_context_window.json: - USD Price == DBU Price * 0.07 - """ - json_path = os.path.join( - os.path.dirname(__file__), "../../../../model_prices_and_context_window.json" - ) - - # Verify file exists - assert os.path.exists( - json_path - ), f"Could not find model_prices_and_context_window.json at {json_path}" - - with open(json_path, "r") as f: - data = json.load(f) - - conversion_rate = 0.07 # 1 DBU = 0.07 USD - errors = [] - - for model, info in data.items(): - if info.get("litellm_provider") == "databricks": - # Check Input Cost - input_usd = info.get("input_cost_per_token") - input_dbu = info.get("input_dbu_cost_per_token") - - if input_usd is not None and input_dbu is not None: - expected = input_dbu * conversion_rate - # Allow small floating point difference - if abs(input_usd - expected) > 1e-9: - errors.append( - f"{model} input mismatch: USD={input_usd}, DBU={input_dbu}, Expected={expected}" - ) - - # Check Output Cost - output_usd = info.get("output_cost_per_token") - output_dbu = info.get("output_dbu_cost_per_token") - - if output_usd is not None and output_dbu is not None: - expected = output_dbu * conversion_rate - if abs(output_usd - expected) > 1e-9: - errors.append( - f"{model} output mismatch: USD={output_usd}, DBU={output_dbu}, Expected={expected}" - ) - - assert not errors, "\n" + "\n".join(errors) diff --git a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py index c2e42da1b4c..f6018626bd0 100644 --- a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py +++ b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py @@ -1,10 +1,6 @@ - import math from datetime import datetime, timezone -import pytest - - import litellm from litellm.llms.fireworks_ai.cost_calculator import cost_per_token from litellm.types.utils import OffPeakPricing, PromptTokensDetailsWrapper, Usage @@ -26,49 +22,6 @@ def _usage(prompt_tokens: int, cached_tokens: int, completion_tokens: int) -> Us ) -def test_cached_prompt_tokens_billed_at_cache_read_rate(): - prompt_tokens = 7036 - cached_tokens = 7020 - completion_tokens = 8 - - prompt_cost, completion_cost = cost_per_token( - model=MODEL, usage=_usage(prompt_tokens, cached_tokens, completion_tokens) - ) - - expected_prompt_cost = (prompt_tokens - cached_tokens) * INPUT_COST + cached_tokens * CACHE_READ_COST - assert prompt_cost == pytest.approx(expected_prompt_cost) - assert completion_cost == pytest.approx(completion_tokens * OUTPUT_COST) - - full_rate_cost = prompt_tokens * INPUT_COST - assert prompt_cost < full_rate_cost - - -def test_warm_call_cheaper_than_cold_call(): - prompt_tokens = 7036 - completion_tokens = 8 - - cold_prompt_cost, _ = cost_per_token( - model=MODEL, usage=_usage(prompt_tokens, 16, completion_tokens) - ) - warm_prompt_cost, _ = cost_per_token( - model=MODEL, usage=_usage(prompt_tokens, 7020, completion_tokens) - ) - - assert warm_prompt_cost < cold_prompt_cost - - -def test_no_cached_tokens_matches_full_input_rate(): - prompt_tokens = 100 - completion_tokens = 10 - - prompt_cost, completion_cost = cost_per_token( - model=MODEL, usage=_usage(prompt_tokens, 0, completion_tokens) - ) - - assert prompt_cost == pytest.approx(prompt_tokens * INPUT_COST) - assert completion_cost == pytest.approx(completion_tokens * OUTPUT_COST) - - OFF_PEAK_MODEL = "accounts/fireworks/models/off-peak-test" OFF_PEAK_WINDOW = "14:00-00:00" INSIDE_WINDOW = datetime(2026, 9, 3, 17, 25, tzinfo=timezone.utc) @@ -78,7 +31,9 @@ STANDARD_OUTPUT_COST = 6e-07 STANDARD_CACHE_READ_COST = 1.5e-08 -def _register_off_peak_model(off_peak_pricing: OffPeakPricing, cache_read_cost: float | None = STANDARD_CACHE_READ_COST) -> None: +def _register_off_peak_model( + off_peak_pricing: OffPeakPricing, cache_read_cost: float | None = STANDARD_CACHE_READ_COST +) -> None: litellm.model_cost[f"fireworks_ai/{OFF_PEAK_MODEL}"] = { "litellm_provider": "fireworks_ai", "mode": "chat", @@ -151,7 +106,9 @@ def test_off_peak_window_bills_cached_tokens_at_the_off_peak_input_rate_without_ def test_off_peak_defaults_to_the_current_time(): """The proxy's cost dispatch passes no clock, so an all-day window has to apply on the default current time.""" - _register_off_peak_model({"hours_utc": "00:00-00:00", "input_cost_per_token": 1e-08, "output_cost_per_token": 2e-08}) + _register_off_peak_model( + {"hours_utc": "00:00-00:00", "input_cost_per_token": 1e-08, "output_cost_per_token": 2e-08} + ) usage = _usage(prompt_tokens=1000, cached_tokens=0, completion_tokens=200) prompt_cost, completion_cost = cost_per_token(model=OFF_PEAK_MODEL, usage=usage) diff --git a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py deleted file mode 100644 index 41f6ad9d99d..00000000000 --- a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py +++ /dev/null @@ -1,65 +0,0 @@ -""" -Regression test for Fireworks Kimi K2.5 / K2.6 / K2.7 context and output limits. - -Fireworks publishes a 262144-token context window for every Kimi K2.5, K2.6 and -K2.7 model, but caps generation well below that. A previous bulk edit had flattened -max_output_tokens/max_tokens to 262144 (equal to the context window), which let the -pre-call context-window check admit requests asking for a full 262144-token -completion that Fireworks then rejects. These assertions pin the corrected per-alias -limits so a future bulk edit can't silently flatten them again. -""" - -import json -from importlib.resources import files - -import pytest - -CONTEXT_WINDOW = 262144 -OUTPUT_LIMIT = 32768 - -KIMI_ALIASES = ( - "fireworks_ai/kimi-k2p5", - "fireworks_ai/kimi-k2p6", - "fireworks_ai/kimi-k2p6-fast", - "fireworks_ai/kimi-k2p7-code", - "fireworks_ai/kimi-k2p7-code-fast", - "fireworks_ai/accounts/fireworks/models/kimi-k2p5", - "fireworks_ai/accounts/fireworks/models/kimi-k2p6", - "fireworks_ai/accounts/fireworks/models/kimi-k2p7-code", - "fireworks_ai/accounts/fireworks/routers/kimi-k2p6-fast", - "fireworks_ai/accounts/fireworks/routers/kimi-k2p7-code-fast", -) - - -@pytest.fixture(scope="module") -def use_local_model_cost_map(): - monkeypatch = pytest.MonkeyPatch() - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - - import litellm - from litellm.utils import _invalidate_model_cost_lowercase_map - - original_model_cost = litellm.model_cost - litellm.model_cost = json.loads( - files("litellm") - .joinpath("model_prices_and_context_window_backup.json") - .read_text(encoding="utf-8") - ) - litellm.get_model_info.cache_clear() - _invalidate_model_cost_lowercase_map() - try: - yield litellm - finally: - litellm.model_cost = original_model_cost - litellm.get_model_info.cache_clear() - _invalidate_model_cost_lowercase_map() - monkeypatch.undo() - - -@pytest.mark.parametrize("alias", KIMI_ALIASES) -def test_fireworks_kimi_get_model_info_limits(use_local_model_cost_map, alias): - model_info = use_local_model_cost_map.get_model_info(model=alias) - - assert model_info["max_input_tokens"] == CONTEXT_WINDOW - assert model_info["max_output_tokens"] == OUTPUT_LIMIT - assert model_info["max_tokens"] == OUTPUT_LIMIT diff --git a/tests/test_litellm/llms/gemini/audio_transcription/test_gemini_audio_transcription_transformation.py b/tests/test_litellm/llms/gemini/audio_transcription/test_gemini_audio_transcription_transformation.py index 8b48ac0b467..8863258ff76 100644 --- a/tests/test_litellm/llms/gemini/audio_transcription/test_gemini_audio_transcription_transformation.py +++ b/tests/test_litellm/llms/gemini/audio_transcription/test_gemini_audio_transcription_transformation.py @@ -4,7 +4,6 @@ import json import httpx import pytest - import litellm from litellm.llms.gemini.audio_transcription.transformation import ( GeminiAudioTranscriptionConfig, @@ -318,15 +317,3 @@ class TestCostRegression: assert live_entry["input_cost_per_token"] == 3.5e-06 assert live_entry["output_cost_per_token"] == 2.1e-05 assert live_entry["supported_endpoints"] == ["/v1/realtime"] - - def test_completion_cost_bills_provider_reported_tokens(self, config, local_cost_map): - payload = json.loads(json.dumps(COMPLETED_RESPONSE)) - payload["usage"]["total_output_tokens"] = 10 - payload["usage"]["total_tokens"] = 210 - response = config.transform_audio_transcription_response(make_response(payload)) - cost = litellm.completion_cost( - completion_response=response, - model="gemini/gemini-3.5-transcribe", - call_type="transcription", - ) - assert cost == pytest.approx(199 * 2e-06 + 1 * 2e-06 + 10 * 1.2e-05) diff --git a/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py b/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py deleted file mode 100644 index c894f92148d..00000000000 --- a/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py +++ /dev/null @@ -1,128 +0,0 @@ -""" -Cost tests for Mistral OCR models against the real litellm cost map -(no monkeypatching of get_model_info). These regress the pricing entries -for mistral-ocr-4-0 and mistral-ocr-latest, which now both resolve to -OCR 4 at $4 / 1000 pages. -""" - -from pathlib import Path - -import pytest - -import litellm -from litellm.cost_calculator import completion_cost -from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo - -OCR4_COST_PER_PAGE = 0.004 -OCR4_ANNOTATION_COST_PER_PAGE = 0.005 - -REPO_ROOT = Path(__file__).parents[5] -MAIN_COST_MAP = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_COST_MAP = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -OCR3_MODEL = "mistral/mistral-ocr-2512" -OCR3_COST_PER_PAGE = 0.002 -OCR3_ANNOTATION_COST_PER_PAGE = 0.003 - -AZURE_DOC_AI_MODEL = "azure_ai/mistral-document-ai-2512" -AZURE_DOC_AI_COST_PER_PAGE = 0.003 - - -def _ocr_response(model: str, pages_processed: int) -> OCRResponse: - return OCRResponse( - pages=[OCRPage(index=i, markdown=f"page {i}") for i in range(pages_processed)], - model=model, - usage_info=OCRUsageInfo(pages_processed=pages_processed), - ) - - -def _annotated_ocr_response(model: str, pages_processed: int | None, annotation_pages: int) -> OCRResponse: - return OCRResponse( - pages=[], - model=model, - usage_info=OCRUsageInfo(pages_processed=pages_processed, pages_processed_annotation=annotation_pages), - ) - - -@pytest.mark.parametrize("model", ["mistral-ocr-4-0", "mistral-ocr-latest"]) -@pytest.mark.parametrize("pages_processed", [1, 3, 10]) -def test_ocr4_cost_scales_with_pages(model: str, pages_processed: int) -> None: - cost = completion_cost( - completion_response=_ocr_response(model, pages_processed), - model=f"mistral/{model}", - custom_llm_provider="mistral", - call_type="ocr", - ) - assert cost == pytest.approx(OCR4_COST_PER_PAGE * pages_processed) - - -def test_ocr3_model_info_price(local_model_cost_map) -> None: - info = litellm.get_model_info(model=OCR3_MODEL, custom_llm_provider="mistral") - assert info["ocr_cost_per_page"] == OCR3_COST_PER_PAGE - - -@pytest.mark.parametrize("pages_processed", [1, 3, 10]) -def test_ocr3_cost_scales_with_pages(local_model_cost_map, pages_processed: int) -> None: - cost = completion_cost( - completion_response=_ocr_response("mistral-ocr-2512", pages_processed), - model=OCR3_MODEL, - custom_llm_provider="mistral", - call_type="ocr", - ) - assert cost == pytest.approx(OCR3_COST_PER_PAGE * pages_processed) - - -def test_ocr3_bills_ocr_and_annotation_pages_at_their_own_rates(local_model_cost_map) -> None: - cost = completion_cost( - completion_response=_annotated_ocr_response("mistral-ocr-2512", 2, 3), - model=OCR3_MODEL, - custom_llm_provider="mistral", - call_type="ocr", - ) - assert cost == pytest.approx(2 * OCR3_COST_PER_PAGE + 3 * OCR3_ANNOTATION_COST_PER_PAGE) - - -def test_ocr3_bills_annotation_only_response(local_model_cost_map) -> None: - cost = completion_cost( - completion_response=_annotated_ocr_response("mistral-ocr-2512", 0, 3), - model=OCR3_MODEL, - custom_llm_provider="mistral", - call_type="ocr", - ) - assert cost == pytest.approx(3 * OCR3_ANNOTATION_COST_PER_PAGE) - - -def test_ocr3_bills_annotation_pages_when_pages_processed_missing(local_model_cost_map) -> None: - cost = completion_cost( - completion_response=_annotated_ocr_response("mistral-ocr-2512", None, 4), - model=OCR3_MODEL, - custom_llm_provider="mistral", - call_type="ocr", - ) - assert cost == pytest.approx(4 * OCR3_ANNOTATION_COST_PER_PAGE) - - -def test_azure_doc_ai_annotation_pages_fall_back_to_ocr_rate(local_model_cost_map) -> None: - info = litellm.get_model_info(model=AZURE_DOC_AI_MODEL, custom_llm_provider="azure_ai") - assert info.get("annotation_cost_per_page") is None - assert info["ocr_cost_per_page"] == AZURE_DOC_AI_COST_PER_PAGE - cost = completion_cost( - completion_response=_annotated_ocr_response("mistral-document-ai-2512", 0, 1), - model=AZURE_DOC_AI_MODEL, - custom_llm_provider="azure_ai", - call_type="ocr", - ) - assert cost == pytest.approx(AZURE_DOC_AI_COST_PER_PAGE) - - -def test_azure_ocr4_bills_ocr_and_annotation_pages_at_their_own_rates(local_model_cost_map) -> None: - info = litellm.get_model_info(model="azure_ai/mistral-ocr-4-0", custom_llm_provider="azure_ai") - assert info["ocr_cost_per_page"] == OCR4_COST_PER_PAGE - assert info["annotation_cost_per_page"] == OCR4_ANNOTATION_COST_PER_PAGE - cost = completion_cost( - completion_response=_annotated_ocr_response("mistral-ocr-4-0", 2, 3), - model="azure_ai/mistral-ocr-4-0", - custom_llm_provider="azure_ai", - call_type="ocr", - ) - assert cost == pytest.approx(2 * OCR4_COST_PER_PAGE + 3 * OCR4_ANNOTATION_COST_PER_PAGE) diff --git a/tests/test_litellm/llms/openai/test_cost_calculation.py b/tests/test_litellm/llms/openai/test_cost_calculation.py index 9b6aec1966c..6c168e61dfc 100644 --- a/tests/test_litellm/llms/openai/test_cost_calculation.py +++ b/tests/test_litellm/llms/openai/test_cost_calculation.py @@ -75,9 +75,3 @@ def test_shipped_per_second_models_bill_a_non_zero_cost(model, provider): prompt_cost, completion_cost = cost_per_second(model=model, custom_llm_provider=provider, duration=60.0) assert prompt_cost + completion_cost > 0.0 - - -def test_whisper_bills_its_documented_rate_once(): - prompt_cost, completion_cost = cost_per_second(model="whisper-1", custom_llm_provider="openai", duration=30.0) - - assert prompt_cost + completion_cost == pytest.approx(0.003) diff --git a/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py b/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py index 1ce2da65fef..80c06e4a1e0 100644 --- a/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py +++ b/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py @@ -154,35 +154,6 @@ class TestSCXAIModelMetadata: with open(json_path) as f: return json.load(f) - def test_scx_ai_models_registered_with_correct_metadata(self): - model_cost = self._load(("model_prices_and_context_window.json",)) - for model in self.SCX_MODELS: - info = model_cost.get(model) - assert info is not None, f"{model} missing from model_prices_and_context_window.json" - assert info["litellm_provider"] == "scx-ai" - assert info["mode"] == "chat" - assert info["input_cost_per_token"] > 0 - assert info["output_cost_per_token"] > 0 - assert info["supports_function_calling"] is True - assert info["supports_tool_choice"] is True - assert info["supports_reasoning"] is True - assert info["supports_response_schema"] is True - assert info.get("supports_vision", False) is (model in self.VISION_MODELS) - - assert info["supports_prompt_caching"] is True - assert 0 < info["cache_read_input_token_cost"] < info["input_cost_per_token"] - - assert info["max_output_tokens"] == 131072 - assert info["max_tokens"] == info["max_output_tokens"] - assert info["max_input_tokens"] >= 1_000_000 - - def test_scx_ai_models_synced_to_backup(self): - model_cost = self._load(("model_prices_and_context_window.json",)) - backup = self._load(("litellm", "model_prices_and_context_window_backup.json")) - for model in self.SCX_MODELS: - assert model in backup, f"{model} missing from backup json" - assert backup[model] == model_cost[model], f"{model} differs between root and backup json" - class TestSCXAIDashboardRegistration: @staticmethod diff --git a/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.py b/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.py index 7556b215e66..caca9e3c681 100644 --- a/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.py +++ b/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.py @@ -14,17 +14,15 @@ from unittest.mock import patch import pytest # Add the project root to Python path - import litellm -from litellm.cost_calculator import completion_cost, cost_per_token from litellm.llms.perplexity.cost_calculator import ( cost_per_token as perplexity_cost_per_token, ) from litellm.types.utils import ( CompletionTokensDetailsWrapper, OffPeakPricing, - Usage, PromptTokensDetailsWrapper, + Usage, ) @@ -64,167 +62,6 @@ class TestPerplexityCostCalculator: } } - def test_basic_cost_calculation(self): - """Test basic cost calculation without additional fields.""" - usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # Expected costs: - # Input: 100 tokens * $2e-6 = $0.0002 - # Output: 50 tokens * $8e-6 = $0.0004 - expected_prompt_cost = 100 * 2e-6 - expected_completion_cost = 50 * 8e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - - def test_citation_tokens_cost_calculation(self): - """Test cost calculation with citation tokens.""" - usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) - - # Add citation tokens - usage.citation_tokens = 25 - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # Expected costs: - # Input: 100 tokens * $2e-6 = $0.0002 - # Citation: 25 tokens * $2e-6 = $0.00005 - # Total prompt cost: $0.00025 - # Output: 50 tokens * $8e-6 = $0.0004 - expected_prompt_cost = (100 * 2e-6) + (25 * 2e-6) - expected_completion_cost = 50 * 8e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - - def test_search_queries_cost_calculation(self): - """Test cost calculation with search queries.""" - usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=3), - ) - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # Expected costs: - # Input: 100 tokens * $2e-6 = $0.0002 - # Output: 50 tokens * $8e-6 = $0.0004 - # Search: 3 queries * $0.005 per request = $0.015 - # Total completion cost: $0.0154 - expected_prompt_cost = 100 * 2e-6 - expected_completion_cost = (50 * 8e-6) + (3 * 0.005) - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - - def test_reasoning_tokens_from_direct_attribute(self): - """Test reasoning tokens cost calculation from direct attribute.""" - usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) - - # Set reasoning tokens directly - usage.reasoning_tokens = 20 - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # `completion_tokens` includes `reasoning_tokens` per the OpenAI/Perplexity - # convention codified in PR #18607. Non-reasoning portion = 50 - 20 = 30. - # Input: 100 tokens * $2e-6 = $0.0002 - # Output (text): 30 tokens * $8e-6 = $0.00024 - # Reasoning: 20 tokens * $3e-6 = $0.00006 - # Total completion cost = $0.0003 - expected_prompt_cost = 100 * 2e-6 - expected_completion_cost = ((50 - 20) * 8e-6) + (20 * 3e-6) - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - - def test_reasoning_tokens_from_completion_tokens_details(self): - """Test reasoning tokens cost calculation from completion_tokens_details.""" - usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - reasoning_tokens=20, # This should be stored in completion_tokens_details - ) - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # Same convention as the direct-attribute case above; reasoning is a subset of - # completion_tokens, so non-reasoning portion = 50 - 20 = 30. - expected_prompt_cost = 100 * 2e-6 - expected_completion_cost = ((50 - 20) * 8e-6) + (20 * 3e-6) - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - - def test_comprehensive_cost_calculation(self): - """Test cost calculation with all fields combined.""" - usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - reasoning_tokens=15, - prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=2), - ) - - # Add custom fields - usage.citation_tokens = 30 - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # Expected costs (reasoning is a subset of completion_tokens): - # Input: 100 tokens * $2e-6 = $0.0002 - # Citation: 30 tokens * $2e-6 = $0.00006 - # Total prompt cost = $0.00026 - # Output (text): (50 - 15) tokens * $8e-6 = $0.00028 - # Reasoning: 15 tokens * $3e-6 = $0.000045 - # Search: 2 queries * $0.005 per request = $0.01 - # Total completion cost = $0.010325 - expected_prompt_cost = (100 * 2e-6) + (30 * 2e-6) - expected_completion_cost = ((50 - 15) * 8e-6) + (15 * 3e-6) + (2 * 0.005) - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - - def test_zero_values_handling(self): - """Test that zero or missing values are handled correctly.""" - usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=0), - ) - - # These should not raise errors and should not affect cost - usage.citation_tokens = 0 - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # Should be same as basic calculation - expected_prompt_cost = 100 * 2e-6 - expected_completion_cost = 50 * 8e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - def test_missing_model_info_fields(self): """Test behavior when model info is missing some fields.""" usage = Usage( @@ -237,18 +74,14 @@ class TestPerplexityCostCalculator: usage.citation_tokens = 25 # Mock get_model_info to return incomplete model info - with patch( - "litellm.llms.perplexity.cost_calculator.get_model_info" - ) as mock_get_model_info: + with patch("litellm.llms.perplexity.cost_calculator.get_model_info") as mock_get_model_info: mock_get_model_info.return_value = { "input_cost_per_token": 2e-6, "output_cost_per_token": 8e-6, # Missing search_queries_cost_per_query } - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) + prompt_cost, completion_cost = perplexity_cost_per_token(model="sonar-deep-research", usage=usage) # Should only calculate basic costs when fields are missing expected_prompt_cost = 100 * 2e-6 @@ -257,104 +90,6 @@ class TestPerplexityCostCalculator: assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - def test_integration_with_main_cost_calculator(self): - """Test integration with the main LiteLLM cost calculator.""" - usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - reasoning_tokens=10, - prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=1), - ) - - usage.citation_tokens = 20 - - # Test main cost calculator - prompt_cost, completion_cost_val = cost_per_token( - model="sonar-deep-research", - custom_llm_provider="perplexity", - usage_object=usage, - ) - - # Should match direct call to perplexity cost calculator - expected_prompt, expected_completion = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - assert math.isclose(prompt_cost, expected_prompt, rel_tol=1e-6) - assert math.isclose(completion_cost_val, expected_completion, rel_tol=1e-6) - - def test_integration_with_completion_cost_function(self): - """Test integration with the completion_cost function.""" - from litellm import ModelResponse - - # Create a mock ModelResponse - usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - reasoning_tokens=10, - prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=1), - ) - usage.citation_tokens = 15 - - response = ModelResponse() - response.usage = usage - response.model = "sonar-deep-research" - - # Test completion_cost function - total_cost = completion_cost( - completion_response=response, custom_llm_provider="perplexity" - ) - - # Calculate expected total cost (reasoning is a subset of completion_tokens) - expected_prompt_cost = (100 * 2e-6) + (15 * 2e-6) # Input + citation - expected_completion_cost = ( - ((50 - 10) * 8e-6) + (10 * 3e-6) + (1 * 0.005) - ) # Output (text) + reasoning + search - expected_total = expected_prompt_cost + expected_completion_cost - - assert math.isclose(total_cost, expected_total, rel_tol=1e-6) - - @pytest.mark.parametrize("citation_tokens", [0, 10, 25, 100]) - @pytest.mark.parametrize("search_queries", [0, 1, 5, 10]) - @pytest.mark.parametrize("reasoning_tokens", [0, 15, 30]) - def test_cost_calculation_combinations( - self, citation_tokens, search_queries, reasoning_tokens - ): - """Test various combinations of citation tokens, search queries, and reasoning tokens.""" - usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - reasoning_tokens=reasoning_tokens, - prompt_tokens_details=PromptTokensDetailsWrapper( - web_search_requests=search_queries - ), - ) - - usage.citation_tokens = citation_tokens - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # Calculate expected costs. `completion_tokens` includes `reasoning_tokens`, - # so non-reasoning portion = 50 - reasoning_tokens. - expected_prompt_cost = (100 * 2e-6) + (citation_tokens * 2e-6) - expected_completion_cost = ( - ((50 - reasoning_tokens) * 8e-6) - + (reasoning_tokens * 3e-6) - + (search_queries * 0.005) - ) - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-6) - - # Ensure costs are non-negative - assert prompt_cost >= 0 - assert completion_cost >= 0 - def test_uses_perplexity_provided_cost_when_available(self): """ Test that when Perplexity provides pre-calculated cost in usage.cost.total_cost, @@ -374,9 +109,7 @@ class TestPerplexityCostCalculator: "total_cost": 0.008, } - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-pro", usage=usage - ) + prompt_cost, completion_cost = perplexity_cost_per_token(model="sonar-pro", usage=usage) # When Perplexity provides total_cost, we use it directly # prompt_cost should be 0, completion_cost should be total_cost @@ -402,9 +135,7 @@ class TestPerplexityCostCalculator: usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) usage.cost = 0.008 - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-pro", usage=usage - ) + prompt_cost, completion_cost = perplexity_cost_per_token(model="sonar-pro", usage=usage) assert prompt_cost == 0.0 assert completion_cost == 0.008 @@ -417,9 +148,7 @@ class TestPerplexityCostCalculator: usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) # No cost object - should use manual calculation - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) + prompt_cost, completion_cost = perplexity_cost_per_token(model="sonar-deep-research", usage=usage) # Should calculate manually: 100 * 2e-6 + 50 * 8e-6 expected_prompt = 100 * 2e-6 @@ -428,57 +157,6 @@ class TestPerplexityCostCalculator: assert math.isclose(prompt_cost, expected_prompt, rel_tol=1e-6) assert math.isclose(completion_cost, expected_completion, rel_tol=1e-6) - def test_reasoning_tokens_not_double_billed(self): - """ - Regression: `completion_tokens` includes `reasoning_tokens` per the - OpenAI/Perplexity usage convention (codified for the central path in PR #18607). - When `output_cost_per_reasoning_token` is configured the manual fallback must - subtract reasoning from completion before applying the output rate so the - reasoning tokens are not billed at BOTH the output rate and the reasoning rate. - - Uses the exact usage shape produced by the live response fixture in - `tests/llm_translation/test_perplexity_reasoning.py`. - """ - usage = Usage( - prompt_tokens=9, - completion_tokens=20, - total_tokens=29, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=15 - ), - ) - - prompt_cost, completion_cost = perplexity_cost_per_token( - model="sonar-deep-research", usage=usage - ) - - # sonar-deep-research rates: input 2e-6, output 8e-6, reasoning 3e-6. - # Non-reasoning portion of the 20 completion tokens = 20 - 15 = 5. - # Pre-fix this asserted 20 * 8e-6 + 15 * 3e-6 = 2.05e-4 (a 2.16x overcharge). - expected_prompt = 9 * 2e-6 - expected_completion = (20 - 15) * 8e-6 + 15 * 3e-6 - - assert math.isclose(prompt_cost, expected_prompt, rel_tol=1e-9) - assert math.isclose(completion_cost, expected_completion, rel_tol=1e-9) - - def test_agent_api_fallback_rates_price_a_response_without_metered_cost(self): - """Perplexity meters cost on the response, but when `usage.cost` is absent the - calculator falls back to the mapped per-token rates. Regression: that fallback - raised "This model isn't mapped yet" for every Agent API third-party model, - because the doubled cost-map key was unreachable from the resolution ladder. - """ - from litellm import ModelResponse - - response = ModelResponse() - response.usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - response.model = "perplexity/perplexity/glm-5.2" - - total_cost = completion_cost( - completion_response=response, custom_llm_provider="perplexity" - ) - - assert math.isclose(total_cost, 1000 * 1.4e-06 + 500 * 4.4e-06, rel_tol=1e-9) - OFF_PEAK_MODEL = "sonar-off-peak-test" OFF_PEAK_WINDOW = "14:00-00:00" INSIDE_WINDOW = datetime(2026, 9, 3, 17, 25, tzinfo=timezone.utc) diff --git a/tests/test_litellm/llms/perplexity/test_perplexity_integration.py b/tests/test_litellm/llms/perplexity/test_perplexity_integration.py index 990fa7eb464..bd72d9b4740 100644 --- a/tests/test_litellm/llms/perplexity/test_perplexity_integration.py +++ b/tests/test_litellm/llms/perplexity/test_perplexity_integration.py @@ -1,7 +1,7 @@ """ Integration tests for Perplexity cost calculation and transformation. -Tests the end-to-end functionality of Perplexity cost calculation +Tests the end-to-end functionality of Perplexity cost calculation including integration with the main LiteLLM cost calculator. """ @@ -12,13 +12,11 @@ import os import pytest # Add the project root to Python path - import litellm from litellm import ModelResponse -from litellm.cost_calculator import completion_cost, cost_per_token +from litellm.cost_calculator import cost_per_token from litellm.llms.perplexity.chat.transformation import PerplexityChatConfig from litellm.types.utils import PromptTokensDetailsWrapper, Usage -from litellm.utils import get_model_info class TestPerplexityIntegration: @@ -57,123 +55,6 @@ class TestPerplexityIntegration: } } - def test_end_to_end_cost_calculation_with_transformation(self): - """Test end-to-end cost calculation with response transformation.""" - # Create a Perplexity API response that includes citations and search queries - config = PerplexityChatConfig() - - # Create a ModelResponse with basic usage (before transformation) - model_response = ModelResponse() - model_response.model = "sonar-deep-research" - model_response.usage = Usage( - prompt_tokens=100, - completion_tokens=50, - total_tokens=150, - reasoning_tokens=10, - ) - - # Simulate raw response from Perplexity API - raw_response_dict = { - "choices": [{"message": {"content": "Test response with citations"}}], - "usage": { - "prompt_tokens": 100, - "completion_tokens": 50, - "total_tokens": 150, - "num_search_queries": 2, - }, - "citations": [ - "This is the first citation with important information about the topic", - "Another citation providing additional context for the response", - ], - } - - # Apply transformation to extract Perplexity-specific fields - config._enhance_usage_with_perplexity_fields(model_response, raw_response_dict) - - # Now calculate the cost with the enhanced usage - total_cost = completion_cost( - completion_response=model_response, custom_llm_provider="perplexity" - ) - - # Calculate expected cost - citation_chars = sum( - len(citation) for citation in raw_response_dict["citations"] - ) - citation_tokens = citation_chars // 4 - - expected_prompt_cost = (100 * 2e-6) + (citation_tokens * 2e-6) - expected_completion_cost = ( - ((50 - 10) * 8e-6) + (10 * 3e-6) + (2 * 0.005) - ) # Output (text) + reasoning + search - expected_total = expected_prompt_cost + expected_completion_cost - - assert math.isclose(total_cost, expected_total, rel_tol=1e-6) - - def test_cost_calculation_without_custom_fields(self): - """Test that cost calculation works normally when custom fields are absent.""" - # Create a standard response without Perplexity-specific fields - model_response = ModelResponse() - model_response.model = "sonar-deep-research" - model_response.usage = Usage( - prompt_tokens=100, completion_tokens=50, total_tokens=150 - ) - - # Calculate cost without custom fields - total_cost = completion_cost( - completion_response=model_response, custom_llm_provider="perplexity" - ) - - # Should only include basic input/output costs - expected_cost = (100 * 2e-6) + (50 * 8e-6) - - assert math.isclose(total_cost, expected_cost, rel_tol=1e-6) - - def test_main_cost_calculator_integration(self): - """Test integration with the main LiteLLM cost calculator.""" - # Create usage with all Perplexity fields - usage = Usage( - prompt_tokens=200, - completion_tokens=100, - total_tokens=300, - reasoning_tokens=25, - prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=3), - ) - usage.citation_tokens = 40 - - # Test main cost calculator - prompt_cost, completion_cost_val = cost_per_token( - model="sonar-deep-research", - custom_llm_provider="perplexity", - usage_object=usage, - ) - - expected_prompt_cost = (200 * 2e-6) + (40 * 2e-6) - expected_completion_cost = ( - ((100 - 25) * 8e-6) + (25 * 3e-6) + (3 * 0.005) - ) # Output (text) + reasoning + search - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost_val, expected_completion_cost, rel_tol=1e-6) - - def test_model_info_includes_custom_fields(self): - """Test that get_model_info returns the custom Perplexity cost fields.""" - model_info = get_model_info( - model="sonar-deep-research", custom_llm_provider="perplexity" - ) - - # Verify custom fields are included - required_fields = [ - "citation_cost_per_token", - "search_context_cost_per_query", - "input_cost_per_token", - "output_cost_per_token", - "output_cost_per_reasoning_token", - ] - - for field in required_fields: - assert field in model_info, f"Missing field: {field}" - assert model_info[field] is not None, f"Null value for field: {field}" - def test_various_citation_sizes(self): """Test cost calculation with various citation sizes.""" config = PerplexityChatConfig() @@ -192,9 +73,7 @@ class TestPerplexityIntegration: for citations, expected_approx_tokens in test_cases: model_response = ModelResponse() model_response.model = "sonar-deep-research" - model_response.usage = Usage( - prompt_tokens=100, completion_tokens=50, total_tokens=150 - ) + model_response.usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) raw_response_dict = { "usage": { @@ -205,9 +84,7 @@ class TestPerplexityIntegration: "citations": citations, } - config._enhance_usage_with_perplexity_fields( - model_response, raw_response_dict - ) + config._enhance_usage_with_perplexity_fields(model_response, raw_response_dict) citation_tokens = getattr(model_response.usage, "citation_tokens", 0) @@ -217,55 +94,6 @@ class TestPerplexityIntegration: else: assert abs(citation_tokens - expected_approx_tokens) <= 5 - def test_cost_calculation_with_zero_values(self): - """Test cost calculation handles zero values for custom fields correctly.""" - usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) - - # Set custom fields to zero - usage.citation_tokens = 0 - usage.prompt_tokens_details = PromptTokensDetailsWrapper(web_search_requests=0) - - # Should not add any extra cost - prompt_cost, completion_cost_val = cost_per_token( - model="sonar-deep-research", - custom_llm_provider="perplexity", - usage_object=usage, - ) - - expected_prompt_cost = 100 * 2e-6 - expected_completion_cost = 50 * 8e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6) - assert math.isclose(completion_cost_val, expected_completion_cost, rel_tol=1e-6) - - def test_high_volume_cost_calculation(self): - """Test cost calculation with high token and query counts.""" - usage = Usage( - prompt_tokens=50000, - completion_tokens=25000, - total_tokens=75000, - reasoning_tokens=10000, - ) - - usage.citation_tokens = 5000 - usage.prompt_tokens_details = PromptTokensDetailsWrapper( - web_search_requests=100 - ) - - total_cost = completion_cost( - completion_response=ModelResponse(usage=usage, model="sonar-deep-research"), - custom_llm_provider="perplexity", - ) - - expected_prompt_cost = (50000 * 2e-6) + (5000 * 2e-6) - expected_completion_cost = ( - ((25000 - 10000) * 8e-6) + (10000 * 3e-6) + (100 * 0.005) - ) # $0.65 - expected_total = expected_prompt_cost + expected_completion_cost # $0.76 - - assert math.isclose(total_cost, expected_total, rel_tol=1e-6) - assert total_cost > 0.25 - def test_transformation_preserves_existing_usage_fields(self): """Test that transformation doesn't overwrite existing standard usage fields.""" config = PerplexityChatConfig() @@ -305,9 +133,7 @@ class TestPerplexityIntegration: assert hasattr(model_response.usage, "citation_tokens") assert model_response.usage.prompt_tokens_details.web_search_requests == 3 - @pytest.mark.parametrize( - "provider_name", ["perplexity", "PERPLEXITY", "Perplexity"] - ) + @pytest.mark.parametrize("provider_name", ["perplexity", "PERPLEXITY", "Perplexity"]) def test_case_insensitive_provider_matching(self, provider_name): """Test that cost calculation works with different case variations of provider name.""" usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) diff --git a/tests/test_litellm/llms/tencent/test_cost_calculator.py b/tests/test_litellm/llms/tencent/test_cost_calculator.py deleted file mode 100644 index 7e710d6319c..00000000000 --- a/tests/test_litellm/llms/tencent/test_cost_calculator.py +++ /dev/null @@ -1,29 +0,0 @@ -import pytest - -import litellm -from litellm.llms.tencent.cost_calculator import cost_per_token -from litellm.types.utils import Usage - - - -def test_cost_per_token_uses_tencent_model_pricing(local_model_cost_map): - usage = Usage(prompt_tokens=1000, completion_tokens=2000, total_tokens=3000) - - prompt_cost, completion_cost = cost_per_token(model="tencent/deepseek-v4-pro", usage=usage) - - assert prompt_cost == pytest.approx(1000 * 4.35e-07) - assert completion_cost == pytest.approx(2000 * 8.7e-07) - - -def test_top_level_dispatcher_routes_tencent_to_wrapper(local_model_cost_map): - from litellm.cost_calculator import cost_per_token as dispatch_cost_per_token - - prompt_cost, completion_cost = dispatch_cost_per_token( - model="tencent/deepseek-v4-pro", - prompt_tokens=1000, - completion_tokens=1000, - custom_llm_provider="tencent", - ) - - assert prompt_cost == pytest.approx(1000 * 4.35e-07) - assert completion_cost == pytest.approx(1000 * 8.7e-07) diff --git a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py index f19e169dc9e..58a040bf019 100644 --- a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py +++ b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py @@ -1,10 +1,6 @@ import copy -import json -import os from unittest.mock import MagicMock, patch -import pytest - from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.experimental_pass_through.transformation import ( VertexAIPartnerModelsAnthropicMessagesConfig, ) @@ -23,12 +19,8 @@ def test_validate_environment_uses_vertex_ai_location(): optional_params = {} with ( - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-url" - ) as mock_get_url, + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), + patch.object(config, "get_complete_vertex_url", return_value="https://mock-url") as mock_get_url, ): config.validate_anthropic_messages_environment( headers=headers, @@ -51,17 +43,11 @@ def test_web_search_header_added_for_messages_endpoint(): "vertex_credentials": "{}", } # Include web search tool in optional_params - optional_params = { - "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}] - } + optional_params = {"tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}]} with ( - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-url" - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), + patch.object(config, "get_complete_vertex_url", return_value="https://mock-url"), ): updated_headers, api_base = config.validate_anthropic_messages_environment( headers=headers, @@ -73,12 +59,10 @@ def test_web_search_header_added_for_messages_endpoint(): ) # Assert that the anthropic-beta header with web-search is present - assert ( - "anthropic-beta" in updated_headers - ), "anthropic-beta header should be present" - assert ( - updated_headers["anthropic-beta"] == "web-search-2025-03-05" - ), f"anthropic-beta should be 'web-search-2025-03-05', got: {updated_headers['anthropic-beta']}" + assert "anthropic-beta" in updated_headers, "anthropic-beta header should be present" + assert updated_headers["anthropic-beta"] == "web-search-2025-03-05", ( + f"anthropic-beta should be 'web-search-2025-03-05', got: {updated_headers['anthropic-beta']}" + ) def test_web_search_header_not_added_without_tool(): @@ -94,12 +78,8 @@ def test_web_search_header_not_added_without_tool(): optional_params = {} with ( - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-url" - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), + patch.object(config, "get_complete_vertex_url", return_value="https://mock-url"), ): updated_headers, api_base = config.validate_anthropic_messages_environment( headers=headers, @@ -111,9 +91,9 @@ def test_web_search_header_not_added_without_tool(): ) # Assert that the anthropic-beta header is NOT present when no web search tool - assert ( - "anthropic-beta" not in updated_headers - ), "anthropic-beta header should not be present without web search tool" + assert "anthropic-beta" not in updated_headers, ( + "anthropic-beta header should not be present without web search tool" + ) def test_compact_context_management_header_added(): @@ -129,12 +109,8 @@ def test_compact_context_management_header_added(): optional_params = {"context_management": {"edits": [{"type": "compact_20260112"}]}} with ( - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-url" - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), + patch.object(config, "get_complete_vertex_url", return_value="https://mock-url"), ): updated_headers, api_base = config.validate_anthropic_messages_environment( headers=headers, @@ -146,12 +122,10 @@ def test_compact_context_management_header_added(): ) # Assert that the anthropic-beta header with compact-2026-01-12 is present - assert ( - "anthropic-beta" in updated_headers - ), "anthropic-beta header should be present" - assert ( - "compact-2026-01-12" in updated_headers["anthropic-beta"] - ), f"anthropic-beta should contain 'compact-2026-01-12', got: {updated_headers['anthropic-beta']}" + assert "anthropic-beta" in updated_headers, "anthropic-beta header should be present" + assert "compact-2026-01-12" in updated_headers["anthropic-beta"], ( + f"anthropic-beta should contain 'compact-2026-01-12', got: {updated_headers['anthropic-beta']}" + ) def test_context_management_header_added_for_other_edits(): @@ -167,12 +141,8 @@ def test_context_management_header_added_for_other_edits(): optional_params = {"context_management": {"edits": [{"type": "some_other_type"}]}} with ( - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-url" - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), + patch.object(config, "get_complete_vertex_url", return_value="https://mock-url"), ): updated_headers, api_base = config.validate_anthropic_messages_environment( headers=headers, @@ -184,12 +154,10 @@ def test_context_management_header_added_for_other_edits(): ) # Assert that the anthropic-beta header with context-management-2025-06-27 is present - assert ( - "anthropic-beta" in updated_headers - ), "anthropic-beta header should be present" - assert ( - "context-management-2025-06-27" in updated_headers["anthropic-beta"] - ), f"anthropic-beta should contain 'context-management-2025-06-27', got: {updated_headers['anthropic-beta']}" + assert "anthropic-beta" in updated_headers, "anthropic-beta header should be present" + assert "context-management-2025-06-27" in updated_headers["anthropic-beta"], ( + f"anthropic-beta should contain 'context-management-2025-06-27', got: {updated_headers['anthropic-beta']}" + ) def test_both_compact_and_context_management_headers_added(): @@ -202,19 +170,11 @@ def test_both_compact_and_context_management_headers_added(): "vertex_credentials": "{}", } # Include context_management with both compact and other edit types - optional_params = { - "context_management": { - "edits": [{"type": "compact_20260112"}, {"type": "some_other_type"}] - } - } + optional_params = {"context_management": {"edits": [{"type": "compact_20260112"}, {"type": "some_other_type"}]}} with ( - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-url" - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), + patch.object(config, "get_complete_vertex_url", return_value="https://mock-url"), ): updated_headers, api_base = config.validate_anthropic_messages_environment( headers=headers, @@ -226,15 +186,13 @@ def test_both_compact_and_context_management_headers_added(): ) # Assert that both beta headers are present - assert ( - "anthropic-beta" in updated_headers - ), "anthropic-beta header should be present" - assert ( - "compact-2026-01-12" in updated_headers["anthropic-beta"] - ), f"anthropic-beta should contain 'compact-2026-01-12', got: {updated_headers['anthropic-beta']}" - assert ( - "context-management-2025-06-27" in updated_headers["anthropic-beta"] - ), f"anthropic-beta should contain 'context-management-2025-06-27', got: {updated_headers['anthropic-beta']}" + assert "anthropic-beta" in updated_headers, "anthropic-beta header should be present" + assert "compact-2026-01-12" in updated_headers["anthropic-beta"], ( + f"anthropic-beta should contain 'compact-2026-01-12', got: {updated_headers['anthropic-beta']}" + ) + assert "context-management-2025-06-27" in updated_headers["anthropic-beta"], ( + f"anthropic-beta should contain 'context-management-2025-06-27', got: {updated_headers['anthropic-beta']}" + ) def test_validate_environment_always_refreshes_token_ignoring_stale_bearer(): @@ -248,12 +206,8 @@ def test_validate_environment_always_refreshes_token_ignoring_stale_bearer(): } with ( - patch.object( - config, "_ensure_access_token", return_value=("fresh-token", "test-project") - ) as mock_ensure, - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-vertex-url" - ), + patch.object(config, "_ensure_access_token", return_value=("fresh-token", "test-project")) as mock_ensure, + patch.object(config, "get_complete_vertex_url", return_value="https://mock-vertex-url"), ): updated_headers, api_base = config.validate_anthropic_messages_environment( headers=headers, @@ -286,9 +240,7 @@ def test_validate_environment_appends_stream_raw_predict_with_custom_api_base(): "get_complete_vertex_url", wraps=config.get_complete_vertex_url, ) as spy_get_url, - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), ): _, api_base = config.validate_anthropic_messages_environment( headers={}, @@ -318,9 +270,7 @@ def test_validate_environment_appends_raw_predict_with_custom_api_base(): "get_complete_vertex_url", wraps=config.get_complete_vertex_url, ) as spy_get_url, - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), ): _, api_base = config.validate_anthropic_messages_environment( headers={}, @@ -447,20 +397,14 @@ def test_validate_environment_does_not_mutate_caller_headers(): caller_headers: dict = {} with ( - patch.object( - config, "_ensure_access_token", return_value=("token", "test-project") - ), - patch.object( - config, "get_complete_vertex_url", return_value="https://mock-url" - ), + patch.object(config, "_ensure_access_token", return_value=("token", "test-project")), + patch.object(config, "get_complete_vertex_url", return_value="https://mock-url"), ): config.validate_anthropic_messages_environment( headers=caller_headers, model="claude-sonnet-4", messages=[], - optional_params={ - "tools": [{"type": "web_search_20250305", "name": "web_search"}] - }, + optional_params={"tools": [{"type": "web_search_20250305", "name": "web_search"}]}, litellm_params={ "vertex_ai_project": "p", "vertex_ai_location": "us-central1", @@ -468,9 +412,7 @@ def test_validate_environment_does_not_mutate_caller_headers(): api_base=None, ) - assert ( - caller_headers == {} - ), "validate_anthropic_messages_environment must not mutate the caller's headers dict" + assert caller_headers == {}, "validate_anthropic_messages_environment must not mutate the caller's headers dict" def test_vertex_claude_completion_does_not_mutate_shared_extra_headers(): @@ -483,12 +425,8 @@ def test_vertex_claude_completion_does_not_mutate_shared_extra_headers(): mock_response = MagicMock() with ( - patch.object( - handler, "_ensure_access_token", return_value=("ya29.fresh", "proj") - ), - patch.object( - handler, "get_complete_vertex_url", return_value="https://mock-url" - ), + patch.object(handler, "_ensure_access_token", return_value=("ya29.fresh", "proj")), + patch.object(handler, "get_complete_vertex_url", return_value="https://mock-url"), patch( "litellm.llms.anthropic.chat.AnthropicChatCompletion.completion", return_value=mock_response, @@ -509,50 +447,7 @@ def test_vertex_claude_completion_does_not_mutate_shared_extra_headers(): litellm_params={}, ) - assert ( - shared_extra_headers == {} - ), "extra_headers must not be mutated by completion()" - - - -def test_messages_thinking_shape_follows_exact_vertex_entry_flag(local_model_cost_map, monkeypatch): - """The Vertex messages config must probe capabilities under ``vertex_ai`` so an - operator setting ``supports_adaptive_thinking: false`` on the exact - ``vertex_ai/claude-opus-4-8`` entry beats the unmodified ``anthropic`` entry. - With the inherited ``"anthropic"`` provider default the flip was ignored and - the transform kept emitting ``thinking.type='adaptive'``.""" - import litellm - - config = VertexAIPartnerModelsAnthropicMessagesConfig() - - def transform(): - return config.transform_anthropic_messages_request( - model="claude-opus-4-8", - messages=[{"role": "user", "content": "Hello"}], - anthropic_messages_optional_request_params={ - "max_tokens": 4096, - "reasoning_effort": "medium", - }, - litellm_params=GenericLiteLLMParams(), - headers={}, - ) - - result = transform() - assert result.get("thinking") == {"type": "adaptive", "display": "summarized"} - assert result.get("output_config") == {"effort": "medium"} - - monkeypatch.setitem( - litellm.model_cost["vertex_ai/claude-opus-4-8"], "supports_adaptive_thinking", False - ) - litellm.get_model_info.cache_clear() - assert litellm.model_cost["claude-opus-4-8"]["supports_adaptive_thinking"] is True - - flipped = transform() - thinking = flipped.get("thinking") - assert isinstance(thinking, dict) - assert thinking.get("type") == "enabled" - assert isinstance(thinking.get("budget_tokens"), int) - assert "output_config" not in flipped + assert shared_extra_headers == {}, "extra_headers must not be mutated by completion()" def _vertex_transform(model, messages, system=None): @@ -614,9 +509,7 @@ class TestVertexAnthropicMidConversationSystem: {"role": "assistant", "content": "reading"}, {"role": "user", "content": "continue"}, ] - result = _vertex_transform( - "claude-sonnet-4-6", messages, system=[{"type": "text", "text": "Base."}] - ) + result = _vertex_transform("claude-sonnet-4-6", messages, system=[{"type": "text", "text": "Base."}]) assert result["messages"] == [ {"role": "user", "content": "read the file"}, { @@ -649,36 +542,3 @@ class TestVertexAnthropicMidConversationSystem: {"type": "text", "text": "You are terse."}, {"type": "text", "text": "Cite sources."}, ] - - -def test_vertex_claude_4_8_plus_cost_map_entries_carry_mid_conversation_system_flag(): - """Exact cost-map hits win over the ``claude-mid-conversation-system`` - fallback rule, so a ``vertex_ai`` Claude 4.8+/5 entry missing the flag would - be treated as unsupported and hoist every reminder, collapsing the prompt - cache. Every mapped vertex_ai entry the rule matches must carry the flag.""" - import re - - import litellm - - cost_map_path = os.path.join( - os.path.dirname(litellm.__file__), "model_prices_and_context_window_backup.json" - ) - with open(cost_map_path) as f: - cost_map = json.load(f) - rules = cost_map["fallback_generalizations"]["rules"] - rule_pattern = next( - (r["pattern"] for r in rules if r["name"] == "claude-mid-conversation-system"), - None, - ) - assert rule_pattern is not None, "claude-mid-conversation-system rule not found in fallback_generalizations" - pattern = re.compile(rule_pattern, re.IGNORECASE) - missing = [ - key - for key, info in cost_map.items() - if isinstance(info, dict) - and str(info.get("litellm_provider", "")).startswith("vertex_ai") - and "claude" in key - and pattern.search(key) - and info.get("supports_mid_conversation_system") is not True - ] - assert missing == [] diff --git a/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py b/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py index 4cff5c76b9e..f35b92a44b2 100644 --- a/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py +++ b/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py @@ -10,10 +10,7 @@ Source: litellm/llms/xai/responses/transformation.py from unittest.mock import MagicMock, Mock import httpx -import pytest -import litellm -from litellm.llms.xai.cost_calculator import cost_per_token from litellm.llms.xai.responses.transformation import XAIResponsesAPIConfig from litellm.responses.utils import ResponseAPILoggingUtils from litellm.types.llms.openai import ( @@ -305,12 +302,16 @@ class TestXAIResponsesWebSearchBilling: def _raw_response_json(self, include_web_search: bool) -> dict: web_search_output = ( - [{ - "type": "web_search_call", - "id": "ws_1", - "status": "completed", - "action": {"type": "search", "query": "grok"}, - }] if include_web_search else [] + [ + { + "type": "web_search_call", + "id": "ws_1", + "status": "completed", + "action": {"type": "search", "query": "grok"}, + } + ] + if include_web_search + else [] ) tool_usage = {"server_side_tool_usage_details": self._TOOL_DETAILS} if include_web_search else {} return { @@ -370,20 +371,6 @@ class TestXAIResponsesWebSearchBilling: assert bridged.completion_tokens == 20 assert getattr(bridged, "server_side_tool_usage_details") == self._TOOL_DETAILS - def test_completion_cost_bills_web_search_calls(self): - with_search = litellm.completion_cost( - completion_response=self._transform(include_web_search=True), - model="xai/grok-4", - custom_llm_provider="xai", - ) - without_search = litellm.completion_cost( - completion_response=self._transform(include_web_search=False), - model="xai/grok-4", - custom_llm_provider="xai", - ) - - assert with_search - without_search == pytest.approx(2 * 5.0 / 1000.0) - def test_streaming_terminal_event_keeps_schema_and_details(self): parsed_chunk = { "type": "response.completed", @@ -436,47 +423,8 @@ class TestXAIResponsesReportedCost: ) return response.usage - def test_reported_cost_reaches_the_cost_calculator(self): - usage = self._transformed_usage( - { - "input_tokens": 100, - "output_tokens": 200, - "total_tokens": 300, - "cost_in_usd_ticks": 37756000, - } - ) - - assert usage.cost == 0.0037756 - - chat_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage) - assert cost_per_token(model="grok-4-latest", usage=chat_usage) == (0.0, 0.0037756) - - def test_streamed_reported_cost_reaches_the_cost_calculator(self): - event = XAIResponsesAPIConfig().transform_streaming_response( - model="grok-4-latest", - parsed_chunk={ - "type": "response.completed", - "sequence_number": 7, - "response": self._response_body( - { - "input_tokens": 100, - "output_tokens": 200, - "total_tokens": 300, - "cost_in_usd_ticks": 37756000, - } - ), - }, - logging_obj=Mock(), - ) - - assert isinstance(event, ResponseCompletedEvent) - chat_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(event.response.usage) - assert cost_per_token(model="grok-4-latest", usage=chat_usage) == (0.0, 0.0037756) - def test_usage_without_a_reported_cost_is_left_alone(self): - usage = self._transformed_usage( - {"input_tokens": 100, "output_tokens": 200, "total_tokens": 300} - ) + usage = self._transformed_usage({"input_tokens": 100, "output_tokens": 200, "total_tokens": 300}) assert usage.cost is None diff --git a/tests/test_litellm/llms/xai/test_xai_chat_transformation.py b/tests/test_litellm/llms/xai/test_xai_chat_transformation.py index c67dca11a56..e91d4834f47 100644 --- a/tests/test_litellm/llms/xai/test_xai_chat_transformation.py +++ b/tests/test_litellm/llms/xai/test_xai_chat_transformation.py @@ -1,14 +1,10 @@ from unittest.mock import Mock import httpx -import pytest -import litellm from litellm.llms.xai.chat.transformation import ( - XAIChatCompletionStreamingHandler, XAIChatConfig, ) -from litellm.llms.xai.cost_calculator import cost_per_token from litellm.types.utils import ( CompletionTokensDetailsWrapper, ModelResponse, @@ -26,11 +22,7 @@ class TestXAIReasoningTokenFolding: total_tokens: int, reasoning_tokens: int = 0, ) -> ModelResponse: - details = ( - CompletionTokensDetailsWrapper(reasoning_tokens=reasoning_tokens) - if reasoning_tokens - else None - ) + details = CompletionTokensDetailsWrapper(reasoning_tokens=reasoning_tokens) if reasoning_tokens else None usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, @@ -176,31 +168,11 @@ class TestXAIChatWebSearchBilling: def test_enhance_noop_without_details(self): response = self._response_with_usage() - XAIChatConfig()._enhance_usage_with_xai_web_search_fields( - response, {"usage": {"prompt_tokens": 100}} - ) + XAIChatConfig()._enhance_usage_with_xai_web_search_fields(response, {"usage": {"prompt_tokens": 100}}) assert response.usage.prompt_tokens_details is None assert getattr(response.usage, "server_side_tool_usage_details", None) is None - def test_completion_cost_bills_chat_web_search_calls(self): - billed = self._response_with_usage() - XAIChatConfig()._enhance_usage_with_xai_web_search_fields( - billed, - {"usage": {"server_side_tool_usage_details": self._TOOL_DETAILS}}, - ) - - with_search = litellm.completion_cost( - completion_response=billed, model="xai/grok-4", custom_llm_provider="xai" - ) - without_search = litellm.completion_cost( - completion_response=self._response_with_usage(), - model="xai/grok-4", - custom_llm_provider="xai", - ) - - assert with_search - without_search == pytest.approx(3 * 5.0 / 1000.0) - class TestXAIReportedCost: """xAI reports what it charged; the transformation moves it to where litellm bills from. @@ -243,23 +215,8 @@ class TestXAIReportedCost: ) return response.usage - def test_reported_cost_reaches_the_cost_calculator(self): - usage = self._transformed_usage( - { - "prompt_tokens": 100, - "completion_tokens": 200, - "total_tokens": 300, - "cost_in_usd_ticks": 37756000, - } - ) - - assert usage.cost == 0.0037756 - assert cost_per_token(model="grok-4-latest", usage=usage) == (0.0, 0.0037756) - def test_usage_without_a_reported_cost_is_left_alone(self): - usage = self._transformed_usage( - {"prompt_tokens": 100, "completion_tokens": 200, "total_tokens": 300} - ) + usage = self._transformed_usage({"prompt_tokens": 100, "completion_tokens": 200, "total_tokens": 300}) assert getattr(usage, "cost", None) is None @@ -275,38 +232,3 @@ class TestXAIReportedCost: ) assert getattr(usage, "cost", None) is None - - def test_streamed_reported_cost_survives_chunk_aggregation(self): - """Streamed spend only matches if the conversion happens on the chunk. - - Chunk aggregation rebuilds usage from the fields it models plus ``cost``, so a - chunk still carrying only ``cost_in_usd_ticks`` loses the reported amount. - """ - handler = XAIChatCompletionStreamingHandler( - streaming_response=iter([]), sync_stream=True - ) - - parsed = handler.chunk_parser( - { - "id": "chatcmpl-xai", - "object": "chat.completion.chunk", - "created": 0, - "model": "grok-4-latest", - "choices": [], - "usage": { - "prompt_tokens": 100, - "completion_tokens": 200, - "total_tokens": 300, - "cost_in_usd_ticks": 37756000, - }, - } - ) - - assert parsed.usage.cost == 0.0037756 - - assembled = litellm.stream_chunk_builder(chunks=[parsed]) - assert assembled.usage.cost == 0.0037756 - assert cost_per_token(model="grok-4-latest", usage=assembled.usage) == ( - 0.0, - 0.0037756, - ) diff --git a/tests/test_litellm/llms/xai/test_xai_cost_calculator.py b/tests/test_litellm/llms/xai/test_xai_cost_calculator.py index 6503e956a51..cf3bc73a225 100644 --- a/tests/test_litellm/llms/xai/test_xai_cost_calculator.py +++ b/tests/test_litellm/llms/xai/test_xai_cost_calculator.py @@ -6,16 +6,6 @@ import math import os import litellm -from litellm.types.utils import ( - Choices, - CompletionTokensDetailsWrapper, - Message, - ModelResponse, - PromptTokensDetailsWrapper, - Usage, -) - - from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import ( StandardBuiltInToolCostTracking, ) @@ -26,6 +16,13 @@ from litellm.llms.xai.cost_calculator import ( cost_per_token, cost_per_web_search_request, ) +from litellm.types.utils import ( + Choices, + Message, + ModelResponse, + PromptTokensDetailsWrapper, + Usage, +) class TestXAICostCalculator: @@ -45,241 +42,6 @@ class TestXAICostCalculator: os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" litellm.model_cost = litellm.get_model_cost_map(url="") - def test_basic_cost_calculation(self): - """Test basic cost calculation without reasoning tokens.""" - usage = Usage(prompt_tokens=12, completion_tokens=125, total_tokens=137) - - prompt_cost, completion_cost = cost_per_token(model="grok-3-mini", usage=usage) - - # Expected costs for grok-3-mini: - # Input: 12 tokens * $3e-7 = $0.0000036 - # Output: 125 tokens * $5e-7 = $0.0000625 - expected_prompt_cost = 12 * 1.25e-6 - expected_completion_cost = 125 * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_reasoning_tokens_cost_calculation(self): - """Test cost calculation with reasoning tokens from completion_tokens_details.""" - usage = Usage( - prompt_tokens=12, - completion_tokens=125, - total_tokens=1086, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=949, - rejected_prediction_tokens=0, - text_tokens=None, # Not set, but doesn't matter for XAI billing - ), - ) - - prompt_cost, completion_cost = cost_per_token(model="grok-3-mini", usage=usage) - - # Expected costs for grok-3-mini: - # Input: 12 tokens * $3e-7 = $0.0000036 - # Completion: (125 + 949) tokens * $5e-7 = $0.000537 - expected_prompt_cost = 12 * 1.25e-6 - expected_completion_cost = (125 + 949) * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_reasoning_and_text_tokens_cost_calculation(self): - """Test cost calculation with both reasoning and text tokens.""" - usage = Usage( - prompt_tokens=12, - completion_tokens=125, - total_tokens=1086, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=949, - rejected_prediction_tokens=0, - text_tokens=76, # Explicitly set (but ignored in XAI billing) - ), - ) - - prompt_cost, completion_cost = cost_per_token(model="grok-3-mini", usage=usage) - - # Expected costs for grok-3-mini: - # Input: 12 tokens * $3e-7 = $0.0000036 - # Completion: (125 + 949) tokens * $5e-7 = $0.000537 - # Note: text_tokens field is ignored, only completion_tokens + reasoning_tokens matters - expected_prompt_cost = 12 * 1.25e-6 - expected_completion_cost = (125 + 949) * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_grok_4_cost_calculation(self): - """Test cost calculation for grok-4 model.""" - usage = Usage( - prompt_tokens=10, - completion_tokens=200, - total_tokens=360, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=150, - rejected_prediction_tokens=0, - text_tokens=50, # Ignored in XAI billing - ), - ) - - prompt_cost, completion_cost = cost_per_token(model="grok-4", usage=usage) - - # grok-4 was retired on 2026-05-15 and now redirects to grok-4.3, so it bills - # at grok-4.3's rates: - # Input: 10 tokens * $1.25e-6 - # Completion: (200 + 150) tokens * $2.5e-6 - expected_prompt_cost = 10 * 1.25e-6 - expected_completion_cost = (200 + 150) * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_grok_3_fast_beta_cost_calculation(self): - """Test cost calculation for grok-3-fast-beta model.""" - usage = Usage( - prompt_tokens=20, - completion_tokens=300, - total_tokens=520, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=200, - rejected_prediction_tokens=0, - text_tokens=100, # Ignored in XAI billing - ), - ) - - prompt_cost, completion_cost = cost_per_token( - model="grok-3-fast-beta", usage=usage - ) - - # Expected costs for grok-3-fast-beta: - # Input: 20 tokens * $5e-6 = $0.0001 - # Completion: (300 + 200) tokens * $2.5e-5 = $0.0125 - expected_prompt_cost = 20 * 1.25e-6 - expected_completion_cost = (300 + 200) * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - - def test_edge_case_large_reasoning_tokens(self): - """Test cost calculation when reasoning_tokens is larger than completion_tokens.""" - usage = Usage( - prompt_tokens=12, - completion_tokens=50, # Less than reasoning_tokens - total_tokens=162, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=100, # More than completion_tokens - rejected_prediction_tokens=0, - text_tokens=None, - ), - ) - - prompt_cost, completion_cost = cost_per_token(model="grok-3-mini", usage=usage) - - # Expected costs: - # Input: 12 tokens * $3e-7 = $0.0000036 - # Completion: (50 + 100) tokens * $5e-7 = $0.000075 - expected_prompt_cost = 12 * 1.25e-6 - expected_completion_cost = (50 + 100) * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_tiered_pricing_above_200k_tokens(self): - usage = Usage( - prompt_tokens=250000, - completion_tokens=100000, - total_tokens=400000, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=50000, - rejected_prediction_tokens=0, - text_tokens=None, - ), - ) - prompt_cost, completion_cost = cost_per_token(model="xai/grok-4.3", usage=usage) - expected_prompt_cost = 250000 * 2.5e-6 - expected_completion_cost = (100000 + 50000) * 5e-6 - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_tiered_pricing_below_200k_tokens(self): - usage = Usage( - prompt_tokens=100000, - completion_tokens=50000, - total_tokens=160000, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=10000, - rejected_prediction_tokens=0, - text_tokens=None, - ), - ) - prompt_cost, completion_cost = cost_per_token(model="xai/grok-4.3", usage=usage) - expected_prompt_cost = 100000 * 1.25e-6 - expected_completion_cost = (50000 + 10000) * 2.5e-6 - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_tiered_pricing_grok_4_latest(self): - """Test tiered pricing for grok-4-latest model.""" - usage = Usage( - prompt_tokens=250000, # Above the 200k threshold - completion_tokens=100000, - total_tokens=400000, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=50000, - rejected_prediction_tokens=0, - text_tokens=None, - ), - ) - - prompt_cost, completion_cost = cost_per_token( - model="xai/grok-4-latest", usage=usage - ) - - # grok-4-latest redirects to grok-4.3, which tiers at 200k rather than 128k: - # Input: 250000 tokens * $2.5e-6 (ALL tokens at tiered rate since input > 200k) - # Completion: (100000 + 50000) tokens * $5e-6 (tiered rate since input > 200k) - expected_prompt_cost = 250000 * 2.5e-6 - expected_completion_cost = (100000 + 50000) * 5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_tiered_pricing_output_tokens_below_200k(self): - usage = Usage( - prompt_tokens=250000, - completion_tokens=50000, - total_tokens=310000, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=10000, - rejected_prediction_tokens=0, - text_tokens=None, - ), - ) - prompt_cost, completion_cost = cost_per_token(model="xai/grok-4.3", usage=usage) - expected_prompt_cost = 250000 * 2.5e-6 - expected_completion_cost = (50000 + 10000) * 5e-6 - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - def test_tiered_pricing_model_without_tiered_pricing(self): litellm.model_cost["xai/flat-rate-fixture"] = { "input_cost_per_token": 3e-7, @@ -294,29 +56,6 @@ class TestXAICostCalculator: assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - def test_already_normalised_usage_does_not_double_count_reasoning(self): - """Cost calc must not double-bill when Usage is already OpenAI-normalised.""" - usage = Usage( - prompt_tokens=12, - completion_tokens=200, - total_tokens=212, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=0, - audio_tokens=0, - reasoning_tokens=100, - rejected_prediction_tokens=0, - text_tokens=None, - ), - ) - - prompt_cost, completion_cost = cost_per_token(model="grok-3-mini", usage=usage) - - expected_prompt_cost = 12 * 1.25e-6 - expected_completion_cost = 200 * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - def test_web_search_cost_via_server_side_tool_usage_details(self): """usage.server_side_tool_usage_details.web_search_calls at default $5/1k.""" usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150) @@ -344,9 +83,7 @@ class TestXAICostCalculator: "search_context_size_medium": 0.01, } } - web_search_cost = cost_per_web_search_request( - usage=usage, model_info=model_info - ) + web_search_cost = cost_per_web_search_request(usage=usage, model_info=model_info) assert math.isclose(web_search_cost, 0.02, rel_tol=1e-10) def test_web_search_cost_zero_without_details(self): @@ -355,9 +92,7 @@ class TestXAICostCalculator: def test_apply_details_sets_web_search_requests_for_cost_gate(self): usage = Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15) - apply_server_side_tool_usage_details_to_usage( - usage, {"web_search_calls": 2, "x_search_calls": 0} - ) + apply_server_side_tool_usage_details_to_usage(usage, {"web_search_calls": 2, "x_search_calls": 0}) assert usage.prompt_tokens_details is not None assert usage.prompt_tokens_details.web_search_requests == 2 assert StandardBuiltInToolCostTracking.response_object_includes_web_search_call( @@ -413,9 +148,7 @@ class TestXAICostCalculator: assert get_cost_for_web_search_request("xai", usage, {}) > 0.0 - reported = Usage( - prompt_tokens=100, completion_tokens=50, total_tokens=150, cost=0.0037756 - ) + reported = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150, cost=0.0037756) setattr(reported, "server_side_tool_usage_details", {"web_search_calls": 3}) assert get_cost_for_web_search_request("xai", reported, {}) == 0.0 @@ -503,82 +236,6 @@ class TestXAICostCalculator: assert cost_per_token(model="grok-4-latest", usage=usage) == (0.0, 0.0) - def test_grok_4_20_beta_reasoning_cost_calculation(self): - """Test cost calculation for grok-4.20-beta-0309-reasoning model.""" - usage = Usage(prompt_tokens=100, completion_tokens=200, total_tokens=300) - - prompt_cost, completion_cost = cost_per_token( - model="grok-4.20-beta-0309-reasoning", usage=usage - ) - - # Input: 100 tokens * $1.25e-6 = $0.000125 - # Output: 200 tokens * $2.5e-6 = $0.0005 - expected_prompt_cost = 100 * 1.25e-6 - expected_completion_cost = 200 * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_grok_4_20_beta_non_reasoning_cost_calculation(self): - """Test cost calculation for grok-4.20-beta-0309-non-reasoning model.""" - usage = Usage(prompt_tokens=50, completion_tokens=100, total_tokens=150) - - prompt_cost, completion_cost = cost_per_token( - model="grok-4.20-beta-0309-non-reasoning", usage=usage - ) - - # Input: 50 tokens * $1.25e-6 = $0.0000625 - # Output: 100 tokens * $2.5e-6 = $0.00025 - expected_prompt_cost = 50 * 1.25e-6 - expected_completion_cost = 100 * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_grok_4_20_at_exactly_200k_prompt_tokens_uses_higher_tier(self): - """xAI bills the >=200k tier once the prompt reaches 200k, so the boundary is inclusive.""" - usage = Usage(prompt_tokens=200_000, completion_tokens=1_000, total_tokens=201_000) - - prompt_cost, completion_cost = cost_per_token( - model="grok-4.20-0309-reasoning", usage=usage - ) - - expected_prompt_cost = 200_000 * 2.5e-6 - expected_completion_cost = 1_000 * 5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_grok_4_20_just_below_200k_prompt_tokens_uses_base_tier(self): - """One token under the boundary still bills at the base rates.""" - usage = Usage(prompt_tokens=199_999, completion_tokens=1_000, total_tokens=200_999) - - prompt_cost, completion_cost = cost_per_token( - model="grok-4.20-0309-reasoning", usage=usage - ) - - expected_prompt_cost = 199_999 * 1.25e-6 - expected_completion_cost = 1_000 * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - - def test_grok_4_20_multi_agent_cost_calculation(self): - """Test cost calculation for grok-4.20-multi-agent-beta-0309 model.""" - usage = Usage(prompt_tokens=200, completion_tokens=300, total_tokens=500) - - prompt_cost, completion_cost = cost_per_token( - model="grok-4.20-multi-agent-beta-0309", usage=usage - ) - - # Input: 200 tokens * $1.25e-6 = $0.00025 - # Output: 300 tokens * $2.5e-6 = $0.00075 - expected_prompt_cost = 200 * 1.25e-6 - expected_completion_cost = 300 * 2.5e-6 - - assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10) - assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10) - def test_custom_pricing_beats_the_reported_cost(self): response = ModelResponse( id="chatcmpl-xai", @@ -635,10 +292,7 @@ class TestXAIWebSearchCostHelpers: details = {"web_search_calls": 0, "x_search_calls": 3} apply_server_side_tool_usage_details_to_usage(usage, details) assert getattr(usage, "server_side_tool_usage_details") == details - assert ( - usage.prompt_tokens_details is None - or usage.prompt_tokens_details.web_search_requests is None - ) + assert usage.prompt_tokens_details is None or usage.prompt_tokens_details.web_search_requests is None def test_apply_details_skips_mirror_when_web_search_calls_invalid(self): usage = Usage(prompt_tokens=1, completion_tokens=1, total_tokens=2) @@ -660,10 +314,7 @@ class TestXAIWebSearchCostHelpers: assert usage.prompt_tokens_details.web_search_requests == 4 def test_web_search_cost_per_call_default_when_model_info_empty(self): - assert ( - _web_search_cost_per_call_from_model_info({}) - == _DEFAULT_WEB_SEARCH_COST_PER_CALL - ) + assert _web_search_cost_per_call_from_model_info({}) == _DEFAULT_WEB_SEARCH_COST_PER_CALL def test_web_search_cost_per_call_prefers_medium_over_low(self): model_info = { diff --git a/tests/test_litellm/llms/xai/test_xai_model_registry.py b/tests/test_litellm/llms/xai/test_xai_model_registry.py deleted file mode 100644 index 25b2002968d..00000000000 --- a/tests/test_litellm/llms/xai/test_xai_model_registry.py +++ /dev/null @@ -1,75 +0,0 @@ -""" -Registry regression tests for xAI entries in the model cost map. -""" - -from __future__ import annotations - -import json -from pathlib import Path - -import pytest - -REPO_ROOT = Path(__file__).parents[4] -PRICES_PATH = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PRICES_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -# Retired by xAI and no longer served: requests to these slugs 404 rather than -# redirecting, and they are absent from https://docs.x.ai/docs/models -RETIRED_MODELS = ( - "xai/grok-2", - "xai/grok-2-1212", - "xai/grok-2-latest", - "xai/grok-2-vision", - "xai/grok-2-vision-1212", - "xai/grok-2-vision-latest", - "xai/grok-beta", - "xai/grok-vision-beta", -) - -# https://docs.x.ai/developers/model-capabilities/text/multi-agent -# "The multi-agent model does not work with the OpenAI Chat Completions API." -RESPONSES_ONLY_MODELS = ( - "xai/grok-4.20-multi-agent-0309", - "xai/grok-4.20-multi-agent-beta-0309", -) - -MAP_PATHS = (PRICES_PATH, BACKUP_PRICES_PATH) - - -@pytest.fixture(scope="module", params=[p.name for p in MAP_PATHS]) -def cost_map(request: pytest.FixtureRequest) -> dict: - path = next(p for p in MAP_PATHS if p.name == request.param) - return json.loads(path.read_text(encoding="utf-8")) - - -@pytest.mark.parametrize("model", RETIRED_MODELS) -def test_retired_xai_models_are_not_advertised(cost_map: dict, model: str): - assert model not in cost_map - - -@pytest.mark.parametrize("model", RESPONSES_ONLY_MODELS) -def test_multi_agent_models_are_responses_only(cost_map: dict, model: str): - entry = cost_map[model] - assert entry["supported_endpoints"] == ["/v1/responses"] - assert entry["mode"] == "responses" - assert "/v1/chat/completions" not in entry["supported_endpoints"] - - -def test_surviving_xai_chat_models_still_serve_chat_completions(cost_map: dict): - """Guard against the removal above over-reaching into live models.""" - chat_models = [ - key - for key, value in cost_map.items() - if isinstance(value, dict) and value.get("litellm_provider") == "xai" and value.get("mode") == "chat" - ] - assert "xai/grok-4.3" in chat_models - assert "xai/grok-4.6" in chat_models - assert not any(key.startswith("xai/grok-2") for key in chat_models) - - -def test_both_cost_maps_agree_on_xai_entries(): - prices = json.loads(PRICES_PATH.read_text(encoding="utf-8")) - backup = json.loads(BACKUP_PRICES_PATH.read_text(encoding="utf-8")) - xai_keys = {k for k, v in prices.items() if isinstance(v, dict) and v.get("litellm_provider") == "xai"} - assert xai_keys - assert {k: prices[k] for k in xai_keys} == {k: backup[k] for k in xai_keys} diff --git a/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py b/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py index 4c8231d357e..9734ea3e545 100644 --- a/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py +++ b/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py @@ -98,23 +98,3 @@ def test_redirected_slug_carries_the_target_tier_rates(cost_map: dict, slug: str for field in TIER_COST_FIELDS: assert entry[field] == target[field], field assert {k for k in entry if "_above_" in k} == {k for k in target if "_above_" in k} - - -def test_both_cost_maps_agree_on_the_redirected_slugs(): - prices = json.loads(PRICES_PATH.read_text(encoding="utf-8")) - backup = json.loads(BACKUP_PRICES_PATH.read_text(encoding="utf-8")) - for slug in (*REDIRECTED_SLUGS, *CODE_SLUGS, REDIRECT_TARGET, CODE_REDIRECT_TARGET): - assert prices[slug] == backup[slug], slug - - -def test_every_retired_chat_slug_is_covered(cost_map: dict): - """The lists above must stay in step with what the registry marks retired.""" - marked = { - key - for key, entry in cost_map.items() - if isinstance(entry, dict) - and entry.get("litellm_provider") == "xai" - and "deprecation_date" in entry - and entry.get("mode") == "chat" - } - assert marked == {*REDIRECTED_SLUGS, *CODE_SLUGS} diff --git a/tests/test_litellm/proxy/spend_tracking/test_savings.py b/tests/test_litellm/proxy/spend_tracking/test_savings.py index e466edab131..408a394a105 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_savings.py +++ b/tests/test_litellm/proxy/spend_tracking/test_savings.py @@ -235,33 +235,6 @@ def test_negative_ttl_counts_do_not_become_cache_write_credits() -> None: assert results[0].prompt_caching < 0 -def test_unpublished_one_hour_price_uses_the_ordinary_write_price() -> None: - model: Final = "claude-4-opus-20250514" - pricing: Final = litellm.get_model_info(model=model, custom_llm_provider="anthropic") - assert pricing.get("cache_creation_input_token_cost_above_1hr") is None - assert pricing["cache_creation_input_token_cost"] > pricing["input_cost_per_token"] - results: Final = tuple( - compute_savings_spend( - model=model, - custom_llm_provider="anthropic", - compression_saved_tokens=0, - gateway_injected_cache=True, - usage_object={ - "prompt_tokens": 6000, - "completion_tokens": 100, - "prompt_tokens_details": { - "text_tokens": 1000, - "cache_creation_tokens": 5000, - "cache_creation_token_details": ttl, - }, - }, - ) - for ttl in (None, {"ephemeral_1h_input_tokens": 5000}) - ) - assert results[0] == results[1] - assert results[0].prompt_caching < 0 - - def test_prompt_caching_savings_nets_out_the_cache_write_premium(): """A cache-writing request is only credited the read discount minus the write premium.""" input_cost, cache_read_cost = _anthropic_costs("claude-sonnet-5") @@ -354,108 +327,6 @@ def test_openai_style_cache_write_tokens_are_netted_out(): ) -def test_model_without_a_cache_write_price_takes_no_premium(): - """An absent write price must mean zero premium, never a bonus. - - ``_get_cost_per_unit`` in the cost calculator defaults a missing price to 0.0. Were - that default copied here the premium would be ``0 - input_cost``, and a model with no - write pricing would report cache writes as free money. This is the common case: most - of the pricing map publishes a cache-read price and no cache-write price. - """ - model = "amazon.nova-2-lite-v1:0" - info = litellm.get_model_info(model=model) - input_cost = info["input_cost_per_token"] - cache_read_cost = info["cache_read_input_token_cost"] - assert info.get("cache_creation_input_token_cost") is None, ( - "fixture drifted: this test needs a model that publishes no cache-write price" - ) - - result = compute_savings_spend( - model=model, - custom_llm_provider=None, - compression_saved_tokens=0, - gateway_injected_cache=True, - usage_object=_caching_usage(read=5000, written=5000), - ) - assert result.prompt_caching == pytest.approx(5000 * (input_cost - cache_read_cost)) - assert result.prompt_caching > 0 - - -def test_zero_cache_write_price_is_read_as_unpublished(): - """A ``0.0`` write price means "no separate price", not "writes are free". - - ``deepseek-chat`` carries an explicit zero in the pricing map. Taken literally the - premium would be ``0 - input_cost``, paying out a saving of ``writes * input_cost`` - on traffic that cached nothing. No provider gives cache writes away, so a falsy - price falls open to the input cost like an absent one does. - """ - info = litellm.get_model_info(model="deepseek-chat", custom_llm_provider="deepseek") - assert info.get("cache_creation_input_token_cost") == 0.0, ( - "fixture drifted: this test exists because deepseek-chat publishes a literal 0.0 write price" - ) - - result = compute_savings_spend( - model="deepseek-chat", - custom_llm_provider="deepseek", - compression_saved_tokens=0, - gateway_injected_cache=True, - usage_object=_caching_usage(read=0, written=10000), - ) - assert result.prompt_caching == pytest.approx(0.0) - - -def test_zero_cache_read_price_stays_literal(): - """The read leg must NOT copy the write leg's falsy fall-open. - - The two zeros mean opposite things. A free cache *write* is unpublished pricing, so - it falls open to input. A free cache *read* is real and is the largest discount - available -- 15 models charge for input and serve reads for nothing. Falling that - open to the input cost would zero out their savings entirely. - """ - model = "gemini-robotics-er-1.5-preview" - info = litellm.get_model_info(model=model) - input_cost = info["input_cost_per_token"] - assert info.get("cache_read_input_token_cost") == 0.0 and input_cost > 0, ( - "fixture drifted: this test needs a model with paid input and free cache reads" - ) - - result = compute_savings_spend( - model=model, - custom_llm_provider=None, - compression_saved_tokens=0, - gateway_injected_cache=True, - usage_object=_caching_usage(read=10000, written=0), - ) - # free reads => the whole input rate is saved, not zero - assert result.prompt_caching == pytest.approx(10000 * input_cost) - - -def test_sub_input_cache_write_price_is_an_extra_saving(): - """A few models price writes below input; there the premium is a real credit. - - Clamping the premium at zero would silently undercount these, so the subtraction - stays signed. ``azure/eu/gpt-4o-2024-11-20`` ships a write price at ~0.5x input. - """ - model = "azure/eu/gpt-4o-2024-11-20" - info = litellm.get_model_info(model=model) - input_cost = info["input_cost_per_token"] - cheap_write = info["cache_creation_input_token_cost"] - assert 0 < cheap_write < input_cost, "fixture drifted: this test needs a model pricing cache writes below input" - # no published read price, so the read leg mirrors input and contributes nothing; - # the whole result is the negative premium, i.e. a credit. - assert info.get("cache_read_input_token_cost") is None - - result = compute_savings_spend( - model=model, - custom_llm_provider=None, - compression_saved_tokens=0, - gateway_injected_cache=True, - usage_object=_caching_usage(read=1000, written=4000), - ) - assert result.prompt_caching == pytest.approx(4000 * (input_cost - cheap_write)) - assert result.prompt_caching > 0 - - def test_negative_cache_write_count_clamps_to_zero(): """A malformed negative write count must not be read as a saving.""" input_cost, cache_read_cost = _anthropic_costs("claude-sonnet-5") @@ -728,21 +599,6 @@ def test_malformed_usage_object_does_not_fail_the_spend_write(): assert result.compression > 0 -def test_model_without_cache_read_pricing_yields_no_caching_savings(): - """A model with no discounted cache-read rate cannot have saved anything by - reading from cache, so the driver must report zero rather than the full input rate.""" - model = "azure/gpt-3.5-turbo" - assert litellm.get_model_info(model=model).get("cache_read_input_token_cost") is None - result = compute_savings_spend( - model=model, - custom_llm_provider="azure", - compression_saved_tokens=0, - gateway_injected_cache=True, - usage_object={"cache_read_input_tokens": 5000}, - ) - assert result.prompt_caching == 0.0 - - def test_the_same_deployment_spelled_two_ways_is_not_a_switch(): """The spend log records a normalized model name while the baseline arrives as the operator wrote it in config. Comparing the raw strings makes a request that never diff --git a/tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py b/tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py deleted file mode 100644 index 63d19e884fa..00000000000 --- a/tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py +++ /dev/null @@ -1,39 +0,0 @@ -import json -from pathlib import Path - -import pytest - -import litellm -from litellm import get_model_info - -AZURE_AI_GROK_4_3_MODEL = "azure_ai/grok-4.3" -AZURE_AI_GROK_4_3_SOURCE = "https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/introducing-grok-4-3-on-microsoft-foundry-latest-generation-agentic-capabilities/4517096" - - -def _load_model_cost(path: Path) -> dict: - with open(path) as f: - return json.load(f) - - -@pytest.fixture(autouse=True) -def reload_model_costs(): - original_model_cost = litellm.model_cost - json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" - litellm.model_cost = _load_model_cost(json_path) - get_model_info.cache_clear() - yield - litellm.model_cost = original_model_cost - get_model_info.cache_clear() - - -def test_azure_ai_grok_4_3_backup_matches_main(): - repo_root = Path(__file__).parents[2] - main_path = repo_root / "model_prices_and_context_window.json" - backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" - - main_cost = _load_model_cost(main_path) - backup_cost = _load_model_cost(backup_path) - - assert backup_cost.get(AZURE_AI_GROK_4_3_MODEL) == main_cost.get( - AZURE_AI_GROK_4_3_MODEL - ) diff --git a/tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py b/tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py deleted file mode 100644 index 29592ff69cd..00000000000 --- a/tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py +++ /dev/null @@ -1,50 +0,0 @@ -from pathlib import Path -from typing import Final - -import pytest -from pydantic import TypeAdapter - -from litellm import cost_per_token, get_model_info -from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider - -REPO_ROOT: Final = Path(__file__).parents[2] -MODEL: Final = "azure_ai/grok-4.6" -COST_MAP_ADAPTER: Final = TypeAdapter(dict[str, dict[str, object]]) - - -def _cost_map_entry(path: Path) -> dict[str, object]: - return COST_MAP_ADAPTER.validate_json(path.read_bytes())[MODEL] - - -@pytest.mark.usefixtures("local_model_cost_map") -def test_azure_ai_grok_4_6_is_priced_and_routed() -> None: - routed_model, provider, _, _ = get_llm_provider(model=MODEL) - assert (routed_model, provider) == ("grok-4.6", "azure_ai") - - info = get_model_info(model=routed_model, custom_llm_provider=provider) - assert info["litellm_provider"] == "azure_ai" - assert info["mode"] == "chat" - assert info["input_cost_per_token"] == 2e-06 - assert info["output_cost_per_token"] == 6e-06 - assert info["cache_read_input_token_cost"] == 5e-07 - assert info["max_input_tokens"] == 200000 - assert info["max_output_tokens"] == 128000 - assert info["max_tokens"] == 128000 - assert info["supports_function_calling"] is True - assert info["supports_prompt_caching"] is True - assert info["supports_reasoning"] is True - assert info["supports_response_schema"] is True - assert info["supports_tool_choice"] is True - assert info["supports_vision"] is True - assert info["supports_web_search"] is True - - prompt_cost, completion_cost = cost_per_token(model=MODEL, prompt_tokens=1_000_000, completion_tokens=1_000_000) - assert prompt_cost == pytest.approx(2.0) - assert completion_cost == pytest.approx(6.0) - - -def test_azure_ai_grok_4_6_entry_source_and_backup_match() -> None: - main_entry = _cost_map_entry(REPO_ROOT / "model_prices_and_context_window.json") - backup_entry = _cost_map_entry(REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json") - - assert backup_entry == main_entry diff --git a/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py b/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py deleted file mode 100644 index 8206172cdee..00000000000 --- a/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py +++ /dev/null @@ -1,93 +0,0 @@ -import json -from pathlib import Path - -import pytest - -import litellm -from litellm.types.utils import PromptTokensDetailsWrapper, Usage -from litellm.utils import supports_function_calling, supports_prompt_caching - -REPO_ROOT = Path(__file__).parents[2] -MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -MODEL = "baseten/zai-org/GLM-5.3" - -INPUT_COST = 1.4e-06 -CACHED_INPUT_COST = 1.4e-07 -OUTPUT_COST = 4.4e-06 - - -def _load(path): - with open(path) as f: - return json.load(f) - - -@pytest.fixture -def local_model_cost_map(monkeypatch): - """Force get_model_info to resolve against the in-repo cost map instead of the - remote one fetched at import time, which still carries the pre-merge registry.""" - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) - litellm.get_model_info.cache_clear() - yield - litellm.get_model_info.cache_clear() - - -def test_baseten_glm_5_3_capabilities_are_visible_to_callers(local_model_cost_map): - """The entry advertises prompt caching and tool calling, so the helpers every - caller checks before sending a request must say so too.""" - assert supports_prompt_caching(model=MODEL) is True - assert supports_function_calling(model=MODEL) is True - - info = litellm.get_model_info(model="zai-org/GLM-5.3", custom_llm_provider="baseten") - assert info["max_input_tokens"] == 1048576 - assert info["max_output_tokens"] == 262144 - - -def test_cached_prompt_tokens_bill_at_the_cached_rate(local_model_cost_map): - """A cache hit reports its reused tokens under prompt_tokens_details, and those - tokens cost a tenth of the input rate, not the full rate and not nothing.""" - usage = Usage( - prompt_tokens=21010, - completion_tokens=100, - total_tokens=21110, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=20992), - ) - - prompt_cost, completion_cost = litellm.cost_per_token( - model=MODEL, usage_object=usage, custom_llm_provider="baseten" - ) - - assert prompt_cost == pytest.approx(18 * INPUT_COST + 20992 * CACHED_INPUT_COST) - assert completion_cost == pytest.approx(100 * OUTPUT_COST) - - -def test_backup_matches_main(): - """Ensure the bundled (backup) cost map stays in sync with the canonical file. - - Both keys are asserted present first: comparing two ``.get`` results alone passes - just as happily when neither file has the entry at all, which is the exact state - this test exists to catch. - """ - main_cost = _load(MAIN_PATH) - backup_cost = _load(BACKUP_PATH) - - assert MODEL in main_cost, f"{MODEL} missing from model_prices_and_context_window.json" - assert MODEL in backup_cost, f"{MODEL} missing from model_prices_and_context_window_backup.json" - assert backup_cost[MODEL] == main_cost[MODEL], f"{MODEL} differs between main and backup model cost maps" - - -def test_entry_advertises_only_what_the_baseten_path_accepts(local_model_cost_map): - """The Baseten path rejects unsupported request parameters.""" - supported = litellm.get_supported_openai_params(model="zai-org/GLM-5.3", custom_llm_provider="baseten") - assert supported is not None - - with pytest.raises(litellm.UnsupportedParamsError): - litellm.utils.get_optional_params( - model="zai-org/GLM-5.3", - custom_llm_provider="baseten", - parallel_tool_calls=True, - reasoning_effort="high", - drop_params=False, - ) diff --git a/tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py b/tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py deleted file mode 100644 index 26eece614bf..00000000000 --- a/tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py +++ /dev/null @@ -1,85 +0,0 @@ -import json -from pathlib import Path - -import pytest - -import litellm -from litellm.constants import bedrock_embedding_models -from litellm.types.utils import PromptTokensDetailsWrapper, Usage - -REPO_ROOT = Path(__file__).parents[2] -MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -BASE_MODEL = "twelvelabs.marengo-embed-3-0-v1:0" -PROFILE_MODELS = ("us.twelvelabs.marengo-embed-3-0-v1:0", "eu.twelvelabs.marengo-embed-3-0-v1:0") -ALL_MODELS = (BASE_MODEL, *PROFILE_MODELS) -MARENGO_2_7_MODELS = ( - "twelvelabs.marengo-embed-2-7-v1:0", - "us.twelvelabs.marengo-embed-2-7-v1:0", - "eu.twelvelabs.marengo-embed-2-7-v1:0", -) -PER_REQUEST_MODELS = (*ALL_MODELS, *MARENGO_2_7_MODELS) - -TEXT_REQUEST_COST = 7e-05 -IMAGE_REQUEST_COST = 0.0001 -VIDEO_COST_PER_SECOND = 0.0007 -AUDIO_COST_PER_SECOND = 0.00014 - - -def _load(path): - with open(path) as f: - return json.load(f) - - -@pytest.mark.parametrize("model", ALL_MODELS) -def test_marengo_embed_3_is_visible_to_callers(model, local_model_cost_map): - info = litellm.get_model_info(model=model, custom_llm_provider="bedrock") - assert info["mode"] == "embedding" - assert info["output_vector_size"] == 512 - assert info["max_input_tokens"] == 500 - - -@pytest.mark.parametrize("model", PER_REQUEST_MODELS) -@pytest.mark.parametrize( - "details,expected_cost", - [ - (PromptTokensDetailsWrapper(query_count=1), TEXT_REQUEST_COST), - (PromptTokensDetailsWrapper(image_count=1), IMAGE_REQUEST_COST), - (PromptTokensDetailsWrapper(query_count=1, image_count=1), TEXT_REQUEST_COST + IMAGE_REQUEST_COST), - (PromptTokensDetailsWrapper(query_count=1, image_count=2), TEXT_REQUEST_COST + 2 * IMAGE_REQUEST_COST), - (PromptTokensDetailsWrapper(video_length_seconds=10), 10 * VIDEO_COST_PER_SECOND), - (PromptTokensDetailsWrapper(audio_length_seconds=10), 10 * AUDIO_COST_PER_SECOND), - ], -) -def test_marengo_requests_are_billed_per_request(model, details, expected_cost, local_model_cost_map): - usage = Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0, prompt_tokens_details=details) - prompt_cost, completion_cost = litellm.cost_per_token( - model=model, usage_object=usage, custom_llm_provider="bedrock" - ) - assert prompt_cost == pytest.approx(expected_cost) - assert completion_cost == 0.0 - - -@pytest.mark.parametrize("model", PER_REQUEST_MODELS) -def test_marengo_token_counts_bill_nothing(model, local_model_cost_map): - usage = Usage(prompt_tokens=128, completion_tokens=0, total_tokens=128) - prompt_cost, completion_cost = litellm.cost_per_token( - model=model, usage_object=usage, custom_llm_provider="bedrock" - ) - assert prompt_cost == 0.0 - assert completion_cost == 0.0 - - -def test_marengo_embed_3_is_a_known_bedrock_embedding_model(): - assert BASE_MODEL in bedrock_embedding_models - - -@pytest.mark.parametrize("model", PER_REQUEST_MODELS) -def test_backup_matches_main(model): - main_cost = _load(MAIN_PATH) - backup_cost = _load(BACKUP_PATH) - - assert model in main_cost, f"{model} missing from model_prices_and_context_window.json" - assert model in backup_cost, f"{model} missing from model_prices_and_context_window_backup.json" - assert backup_cost[model] == main_cost[model], f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_bedrock_usgov_pricing.py b/tests/test_litellm/test_bedrock_usgov_pricing.py index a3a7fc4ed7a..b83176b6460 100644 --- a/tests/test_litellm/test_bedrock_usgov_pricing.py +++ b/tests/test_litellm/test_bedrock_usgov_pricing.py @@ -31,18 +31,6 @@ def model_data(): return json.load(f) -def test_usgov_east_haiku_profile_mirrors_in_region_row(model_data): - """us-gov-east-1 serves claude-3-haiku through the us-gov. inference profile - only, so the profile row must bill exactly like the in-region gov row. - """ - profile = model_data["us-gov.anthropic.claude-3-haiku-20240307-v1:0"] - in_region = model_data["bedrock/us-gov-east-1/anthropic.claude-3-haiku-20240307-v1:0"] - assert profile["litellm_provider"] == "bedrock_converse" - assert {k: v for k, v in profile.items() if k != "litellm_provider"} == { - k: v for k, v in in_region.items() if k != "litellm_provider" - } - - GOV_ROW_SOURCES = { "us-gov.anthropic.claude-fable-5-1": "anthropic.claude-fable-5-1", "bedrock/us-gov-west-1/anthropic.claude-fable-5-1": "anthropic.claude-fable-5-1", diff --git a/tests/test_litellm/test_claude_fable_5_config.py b/tests/test_litellm/test_claude_fable_5_config.py index 0473161faac..25327eb9430 100644 --- a/tests/test_litellm/test_claude_fable_5_config.py +++ b/tests/test_litellm/test_claude_fable_5_config.py @@ -12,10 +12,7 @@ shape, which Fable 5 rejects with a 400. import json import os -import pytest - from litellm.constants import BEDROCK_CONVERSE_MODELS -from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap REPO_ROOT = os.path.join(os.path.dirname(__file__), "../..") @@ -26,99 +23,10 @@ def _load_root_cost_map() -> dict: return json.load(f) -def test_fable_5_geo_multiplier_without_fast_mode(): - """First-party ``inference_geo='us'`` carries the 1.1x premium, but unlike - the Opus line there is no fast-mode variant for Fable 5; a ``fast`` key - here would silently misprice ``speed='fast'`` requests.""" - model_data = _load_root_cost_map() - entry = model_data["claude-fable-5"]["provider_specific_entry"] - assert entry == {"us": 1.1} - - -def test_fable_5_present_in_bundled_backup(): - """The bundled backup is the runtime fallback (and what tests load with - ``LITELLM_LOCAL_MODEL_COST_MAP=True``) — it must carry the same entries as - the root cost map, otherwise the model resolves on one path but not the - other.""" - backup = GetModelCostMap.load_local_model_cost_map() - root = _load_root_cost_map() - for model_name in ( - "claude-fable-5", - "anthropic.claude-fable-5", - "global.anthropic.claude-fable-5", - "us.anthropic.claude-fable-5", - "eu.anthropic.claude-fable-5", - "vertex_ai/claude-fable-5", - "vertex_ai/claude-fable-5@default", - "azure_ai/claude-fable-5", - ): - assert model_name in backup, f"Missing from backup cost map: {model_name}" - assert backup[model_name] == root[model_name], model_name - - def test_fable_5_registered_for_bedrock_converse(): assert "anthropic.claude-fable-5" in BEDROCK_CONVERSE_MODELS -@pytest.mark.parametrize( - "cost_map", - [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], - ids=["root", "bundled_backup"], -) -def test_fable_5_all_variants_carry_adaptive_thinking_flag(cost_map): - """Every Fable 5 entry must advertise ``supports_adaptive_thinking``. - - Adaptive-thinking detection is cost-map driven, so a single variant missing - the flag silently sends the legacy ``thinking.type='enabled'`` shape and the - provider 400s (issue #29188 for the Opus 4.8 equivalent). Fable 5 is even - stricter than Opus 4.8: an explicit ``thinking.type='disabled'`` also 400s, - so adaptive is the only valid thinking shape LiteLLM can emit for it.""" - variants = [k for k in cost_map if "claude-fable-5" in k] - assert variants, "no claude-fable-5 entries found in cost map" - missing = [ - k for k in variants if cost_map[k].get("supports_adaptive_thinking") is not True - ] - assert not missing, f"missing supports_adaptive_thinking: {missing}" - - -@pytest.mark.parametrize( - "cost_map", - [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], - ids=["root", "bundled_backup"], -) -def test_fable_5_all_variants_carry_thinking_always_on_flag(cost_map): - """Every Fable 5 entry must advertise ``thinking_always_on``. - - The flag drives the Anthropic transformations to omit an explicit - ``thinking.type='disabled'``, which Fable 5 rejects with a 400; a variant - missing the flag forwards the param verbatim and the provider 400s.""" - variants = [k for k in cost_map if "claude-fable-5" in k] - assert variants, "no claude-fable-5 entries found in cost map" - missing = [k for k in variants if cost_map[k].get("thinking_always_on") is not True] - assert not missing, f"missing thinking_always_on: {missing}" - - -@pytest.mark.parametrize( - "model", - [ - "claude-fable-5", - "anthropic/claude-fable-5", - "anthropic.claude-fable-5", - "bedrock/us.anthropic.claude-fable-5", - "bedrock/invoke/eu.anthropic.claude-fable-5", - "bedrock/global.anthropic.claude-fable-5", - "vertex_ai/claude-fable-5", - "azure_ai/claude-fable-5", - ], -) -def test_adaptive_thinking_detected_for_fable_5(local_model_cost_map, model): - """Provider-routed ids must resolve to a flagged entry so ``reasoning_effort`` - maps to ``thinking.type='adaptive'`` + ``output_config.effort``.""" - from litellm.llms.anthropic.common_utils import AnthropicModelInfo - - assert AnthropicModelInfo._is_adaptive_thinking_model(model, "anthropic") is True - - FABLE_5_1_VARIANTS = ( "claude-fable-5-1", "anthropic.claude-fable-5-1", @@ -131,73 +39,5 @@ FABLE_5_1_VARIANTS = ( ) -@pytest.mark.parametrize( - "cost_map", - [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], - ids=["root", "bundled_backup"], -) -def test_fable_5_1_cache_reads_cost_a_quarter_of_fable_5(cost_map): - """Fable 5.1 prices cache hits at 0.025x base input instead of the usual - 0.1x, so copying Fable 5's cache-read price overcharges every cache hit 4x.""" - for model_name in FABLE_5_1_VARIANTS: - info = cost_map[model_name] - geo_premium = model_name.startswith(("us.", "eu.")) - expected = 2.75e-07 if geo_premium else 2.5e-07 - assert info["cache_read_input_token_cost"] == expected, model_name - assert info["cache_read_input_token_cost"] == pytest.approx( - info["input_cost_per_token"] * 0.025 - ), model_name - - -def test_fable_5_1_present_in_bundled_backup(): - backup = GetModelCostMap.load_local_model_cost_map() - root = _load_root_cost_map() - for model_name in FABLE_5_1_VARIANTS: - assert model_name in backup, f"Missing from backup cost map: {model_name}" - assert backup[model_name] == root[model_name], model_name - - def test_fable_5_1_registered_for_bedrock_converse(): assert "anthropic.claude-fable-5-1" in BEDROCK_CONVERSE_MODELS - - -@pytest.mark.parametrize( - "model", - [ - "claude-fable-5-1", - "anthropic/claude-fable-5-1", - "anthropic.claude-fable-5-1", - "bedrock/us.anthropic.claude-fable-5-1", - "bedrock/invoke/eu.anthropic.claude-fable-5-1", - "bedrock/global.anthropic.claude-fable-5-1", - "vertex_ai/claude-fable-5-1", - "azure_ai/claude-fable-5-1", - ], -) -def test_adaptive_thinking_detected_for_fable_5_1(local_model_cost_map, model): - from litellm.llms.anthropic.common_utils import AnthropicModelInfo - - assert AnthropicModelInfo._is_adaptive_thinking_model(model, "anthropic") is True - - -@pytest.mark.parametrize( - "cost_map", - [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], - ids=["root", "bundled_backup"], -) -def test_sampling_params_flag_on_all_models_that_removed_them(cost_map): - """Fable 5 and Opus 4.7/4.8 reject ``top_p``/``top_k``/``temperature != 1``; - the drop/raise gating is cost-map driven, so every variant must carry an - explicit ``supports_sampling_params: false``. The perplexity route is - exempt: it is OpenAI-compatible and maps sampling params upstream.""" - variants = [ - k - for k in cost_map - if any(v in k for v in ("claude-fable-5", "claude-opus-4-7", "claude-opus-4-8")) - and not k.startswith("perplexity/") - ] - assert variants, "no matching entries found in cost map" - missing = [ - k for k in variants if cost_map[k].get("supports_sampling_params") is not False - ] - assert not missing, f"missing supports_sampling_params=false: {missing}" diff --git a/tests/test_litellm/test_claude_haiku_4_5_config.py b/tests/test_litellm/test_claude_haiku_4_5_config.py deleted file mode 100644 index 9172b6479a5..00000000000 --- a/tests/test_litellm/test_claude_haiku_4_5_config.py +++ /dev/null @@ -1,48 +0,0 @@ -""" -Test Claude Haiku 4.5 model configurations for Bedrock -https://github.com/BerriAI/litellm/issues/15818 -""" - -import json -import os - - -def test_bedrock_haiku_4_5_matches_sonnet_capabilities(): - """ - Test that Haiku 4.5 has same capabilities as Sonnet 4.5 - (including computer_use, vision, tools, etc.) - """ - # Load model configuration - json_path = os.path.join( - os.path.dirname(__file__), "../../model_prices_and_context_window.json" - ) - with open(json_path) as f: - model_data = json.load(f) - - haiku_model = "us.anthropic.claude-haiku-4-5-20251001-v1:0" - sonnet_model = "us.anthropic.claude-sonnet-4-5-20250929-v1:0" - - haiku_info = model_data[haiku_model] - sonnet_info = model_data[sonnet_model] - - # Both should use bedrock_converse - assert haiku_info["litellm_provider"] == "bedrock_converse" - assert sonnet_info["litellm_provider"] == "bedrock_converse" - - # Shared capabilities that should match - shared_capabilities = [ - "supports_vision", - "supports_computer_use", - "supports_function_calling", - "supports_tool_choice", - "supports_prompt_caching", - "supports_response_schema", - "supports_pdf_input", - "supports_assistant_prefill", - "supports_reasoning", - ] - - for capability in shared_capabilities: - assert haiku_info.get(capability) == sonnet_info.get( - capability - ), f"Capability {capability} mismatch: Haiku={haiku_info.get(capability)}, Sonnet={sonnet_info.get(capability)}" diff --git a/tests/test_litellm/test_claude_opus_5_config.py b/tests/test_litellm/test_claude_opus_5_config.py index 7a57937305b..5f3e23fc18a 100644 --- a/tests/test_litellm/test_claude_opus_5_config.py +++ b/tests/test_litellm/test_claude_opus_5_config.py @@ -18,7 +18,6 @@ import os import pytest from litellm.constants import BEDROCK_CONVERSE_MODELS -from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap REPO_ROOT = os.path.join(os.path.dirname(__file__), "../..") @@ -62,33 +61,5 @@ def test_opus_5_bedrock_rejects_strict_tools(model_name, local_model_cost_map): assert bedrock_converse_supports_strict_tools(model_name) is False -def test_opus_5_present_in_bundled_backup(): - """The bundled backup is the runtime fallback (and what tests load with - ``LITELLM_LOCAL_MODEL_COST_MAP=True``); it must carry the same entries as the - root cost map, otherwise the model resolves on one path but not the other.""" - backup = GetModelCostMap.load_local_model_cost_map() - for model_name in ALL_OPUS_5_VARIANTS: - assert model_name in backup, f"Missing from backup cost map: {model_name}" - - def test_opus_5_registered_for_bedrock_converse(): assert "anthropic.claude-opus-5" in BEDROCK_CONVERSE_MODELS - - -@pytest.mark.parametrize( - "cost_map", - [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], - ids=["root", "bundled_backup"], -) -def test_opus_5_all_variants_carry_adaptive_thinking_flag(cost_map): - """Every Opus 5 entry must advertise ``supports_adaptive_thinking``. - - Adaptive-thinking detection is cost-map driven, so a single variant missing - the flag silently sends the legacy ``thinking.type='enabled'`` shape, which - Opus 5 rejects with a 400.""" - variants = [k for k in cost_map if "claude-opus-5" in k] - assert variants, "no claude-opus-5 entries found in cost map" - missing = [ - k for k in variants if cost_map[k].get("supports_adaptive_thinking") is not True - ] - assert not missing, f"missing supports_adaptive_thinking: {missing}" diff --git a/tests/test_litellm/test_claude_sonnet_5_config.py b/tests/test_litellm/test_claude_sonnet_5_config.py index 8c6d2cd1851..18273f7494a 100644 --- a/tests/test_litellm/test_claude_sonnet_5_config.py +++ b/tests/test_litellm/test_claude_sonnet_5_config.py @@ -13,10 +13,7 @@ populate ``litellm.anthropic_models`` at import, which is what lets a bare import json import os -import pytest - from litellm.constants import BEDROCK_CONVERSE_MODELS -from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap REPO_ROOT = os.path.join(os.path.dirname(__file__), "../..") @@ -40,31 +37,5 @@ def _load_root_cost_map() -> dict: return json.load(f) -def test_sonnet_5_present_in_bundled_backup(): - """The bundled backup is the runtime fallback (and what tests load with - ``LITELLM_LOCAL_MODEL_COST_MAP=True``); it must carry the same entries as the - root cost map, otherwise the model resolves on one path but not the other.""" - backup = GetModelCostMap.load_local_model_cost_map() - for model_name in ALL_SONNET_5_VARIANTS: - assert model_name in backup, f"Missing from backup cost map: {model_name}" - - def test_sonnet_5_registered_for_bedrock_converse(): assert "anthropic.claude-sonnet-5" in BEDROCK_CONVERSE_MODELS - - -@pytest.mark.parametrize( - "cost_map", - [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], - ids=["root", "bundled_backup"], -) -def test_sonnet_5_all_variants_carry_adaptive_thinking_flag(cost_map): - """Every Sonnet 5 entry must advertise ``supports_adaptive_thinking``. - - Adaptive-thinking detection is cost-map driven, so a single variant missing - the flag silently sends the legacy ``thinking.type='enabled'`` shape and the - provider 400s. This guards against a future variant being added without it.""" - variants = [k for k in cost_map if "claude-sonnet-5" in k] - assert variants, "no claude-sonnet-5 entries found in cost map" - missing = [k for k in variants if cost_map[k].get("supports_adaptive_thinking") is not True] - assert not missing, f"missing supports_adaptive_thinking: {missing}" diff --git a/tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py b/tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py deleted file mode 100644 index 4e770be7c3e..00000000000 --- a/tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -Regression tests for the Cloudflare Workers AI text-generation catalog in the -model-cost map. - -The Cloudflare list was badly stale (only 4 ancient entries). These tests pin -the newly added current Workers AI models (sourced from Cloudflare's live -``/ai/models/search?task=Text Generation`` catalog) and guard against the root -``model_prices_and_context_window.json`` and the bundled -``litellm/model_prices_and_context_window_backup.json`` drifting out of sync for -the ``cloudflare/`` namespace. -""" - -import json -import os - -import pytest - -import litellm - -ROOT_MAP = os.path.join( - os.path.dirname(os.path.dirname(litellm.__file__)), - "model_prices_and_context_window.json", -) -BACKUP_MAP = os.path.join( - os.path.dirname(litellm.__file__), - "model_prices_and_context_window_backup.json", -) - - -def _load(path: str) -> dict: - with open(path, encoding="utf-8") as f: - return json.load(f) - - -def _cloudflare_keys(data: dict) -> set: - return {k for k in data if k.startswith("cloudflare/")} - - -def test_root_and_backup_have_identical_cloudflare_keys(): - if not os.path.exists(ROOT_MAP): - pytest.skip("root cost map only ships in source checkouts") - assert _cloudflare_keys(_load(ROOT_MAP)) == _cloudflare_keys(_load(BACKUP_MAP)) - - -def test_root_and_backup_cloudflare_entries_are_byte_for_byte_equal(): - if not os.path.exists(ROOT_MAP): - pytest.skip("root cost map only ships in source checkouts") - root = {k: v for k, v in _load(ROOT_MAP).items() if k.startswith("cloudflare/")} - backup = {k: v for k, v in _load(BACKUP_MAP).items() if k.startswith("cloudflare/")} - assert root == backup diff --git a/tests/test_litellm/test_command_r7b_pricing.py b/tests/test_litellm/test_command_r7b_pricing.py deleted file mode 100644 index dc7b5a45ca2..00000000000 --- a/tests/test_litellm/test_command_r7b_pricing.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -Regression test: ``command-r7b-12-2024`` had its input/output per-token -costs transposed in the model-cost maps (input=1.5e-07 / output=3.75e-08), -even though Cohere publishes $0.0375/1M input and $0.15/1M output, i.e. -output is ~4x input like every other ``command-r`` entry. - -These tests pin the corrected values in both the primary price map and the -``litellm/`` backup, and verify ``get_model_info`` surfaces them, so the -swap cannot silently regress. -""" - -import json -import os - - -import litellm - -MODEL = "command-r7b-12-2024" -EXPECTED_INPUT_COST = 3.75e-08 -EXPECTED_OUTPUT_COST = 1.5e-07 - - -def _load_json(path: str) -> dict: - with open(path, encoding="utf-8") as f: - return json.load(f) - - -def _backup_path() -> str: - return os.path.join( - os.path.dirname(litellm.__file__), - "model_prices_and_context_window_backup.json", - ) - - -def _main_path() -> str: - # This test lives at ``tests/test_litellm/``; the primary price map sits at - # the repo root, two directories up. Resolve it relative to this file so the - # test works regardless of where ``litellm`` itself is installed (e.g. a pip - # install into site-packages). - return os.path.join( - os.path.dirname(__file__), - "..", - "..", - "model_prices_and_context_window.json", - ) - - -class TestCommandR7bPricingData: - """The JSON price maps must carry Cohere's published costs, with output - more expensive than input.""" - - -class TestCommandR7bPricingModelInfo: - """``get_model_info`` must report the corrected, un-swapped costs.""" - - def test_get_model_info_costs(self): - # Patch litellm.model_cost with the local backup so the test is not - # dependent on the remote fetch hitting a not-yet-merged main branch. - original = litellm.model_cost - try: - litellm.model_cost = _load_json(_backup_path()) - info = litellm.get_model_info(MODEL) - assert info["input_cost_per_token"] == EXPECTED_INPUT_COST - assert info["output_cost_per_token"] == EXPECTED_OUTPUT_COST - assert info["output_cost_per_token"] > info["input_cost_per_token"] - finally: - litellm.model_cost = original diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py index cbbd5aa6eb6..7fedb43ab6e 100644 --- a/tests/test_litellm/test_cost_calculator.py +++ b/tests/test_litellm/test_cost_calculator.py @@ -1,8 +1,6 @@ - from typing import Final import pytest - from pydantic import BaseModel import litellm @@ -18,9 +16,7 @@ from litellm.litellm_core_utils.litellm_logging import Logging from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo from litellm.types.llms.base import CachedTokensDetails from litellm.types.llms.openai import OpenAIRealtimeStreamList -from litellm.types.rerank import RerankResponse from litellm.types.utils import ( - CacheCreationTokenDetails, ModelInfo, ModelResponse, PromptTokensDetailsWrapper, @@ -53,26 +49,6 @@ def test_cost_per_token_duplicate_openai_prefix_matches_model_cost(monkeypatch): assert prompt_usd + completion_usd > 0 -def test_cost_per_token_tiered_only_model_bills_at_tier_rate(monkeypatch): - """ - Regression: models that publish only tiered_pricing (no top-level per-token rates), - e.g. volcengine doubao-seed-2.0, must reach the generic tiered path instead of - recording zero spend. - """ - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) - - prompt_usd, completion_usd = cost_per_token( - model="volcengine/doubao-seed-2-0-pro-260215", - prompt_tokens=40000, - completion_tokens=500, - custom_llm_provider="volcengine", - ) - - assert prompt_usd == pytest.approx(40000 * 7e-07) - assert completion_usd == pytest.approx(500 * 3.5e-06) - - def test_cost_per_token_non_string_model_does_not_hang(): """ The provider-prefix dedup loop must not spin forever when `model` is a @@ -129,27 +105,9 @@ def test_completion_cost_uses_response_model_for_dynamic_routing(_local_model_co assert cost > 0, "Cost should be calculated using response model" -def test_jina_rerank_bills_total_tokens_at_input_rate_only(_local_model_cost_map): - response: Final = RerankResponse( - id="rerank-1", - results=[{"index": 0, "relevance_score": 0.9}], - meta={"billed_units": {"total_tokens": 1000}}, - ) - - cost: Final = completion_cost( - completion_response=response, - model="jina_ai/jina-reranker-v2-base-multilingual", - call_type="rerank", - ) - - assert cost == pytest.approx(1000 * 5e-08) - - def test_cost_calculator_with_response_cost_in_additional_headers(): class MockResponse(BaseModel): - _hidden_params = { - "additional_headers": {"llm_provider-x-litellm-response-cost": 1000} - } + _hidden_params = {"additional_headers": {"llm_provider-x-litellm-response-cost": 1000}} result = response_cost_calculator( response_object=MockResponse(), @@ -164,147 +122,6 @@ def test_cost_calculator_with_response_cost_in_additional_headers(): assert result == 1000 -@pytest.mark.parametrize( - ("model", "expected_cost"), - [ - ("vertex_ai/lyria-002", 0.06), - ("vertex_ai/lyria-3-clip-preview", 0.04), - ("vertex_ai/lyria-3-pro-preview", 0.08), - ], -) -@pytest.mark.parametrize("runtime_state", ("complete", "missing", "routing_only", "custom_zero", "custom_price")) -@pytest.mark.parametrize("call_type", ("speech", "aspeech")) -def test_vertex_lyria_speech_cost( - model: str, - expected_cost: float, - _local_model_cost_map: None, - monkeypatch: pytest.MonkeyPatch, - runtime_state: str, - call_type: str, -) -> None: - model_info: Final = litellm.model_cost[model] - if runtime_state == "missing": - monkeypatch.delitem(litellm.model_cost, model) - elif runtime_state == "routing_only": - monkeypatch.setitem( - litellm.model_cost, - model, - {key: value for key, value in model_info.items() if key != "output_cost_per_image"}, - ) - elif runtime_state in ("custom_zero", "custom_price"): - multiplier: Final = 0 if runtime_state == "custom_zero" else 2 - monkeypatch.setitem( - litellm.model_cost, - model, - {**model_info, "output_cost_per_image": model_info["output_cost_per_image"] * multiplier}, - ) - - cost: Final = completion_cost( - model=model, - prompt="A bright synth track", - call_type=call_type, - ) - - expected: Final = 0 if runtime_state == "custom_zero" else expected_cost * (2 if runtime_state == "custom_price" else 1) - assert cost == pytest.approx(expected) - - -def test_baseten_model_api_pricing_entries(_local_model_cost_map): - - expected_pricing = { - "baseten/nvidia/Nemotron-120B-A12B": (3e-07, 7.5e-07), - "baseten/MiniMaxAI/MiniMax-M2.5": (3e-07, 1.2e-06), - "baseten/zai-org/GLM-5": (9.5e-07, 3.15e-06), - "baseten/zai-org/GLM-4.7": (6e-07, 2.2e-06), - "baseten/zai-org/GLM-4.6": (6e-07, 2.2e-06), - "baseten/moonshotai/Kimi-K2.5": (6e-07, 3e-06), - "baseten/moonshotai/Kimi-K2-Thinking": (6e-07, 2.5e-06), - "baseten/moonshotai/Kimi-K2-Instruct-0905": (6e-07, 2.5e-06), - "baseten/openai/gpt-oss-120b": (1e-07, 5e-07), - "baseten/deepseek-ai/DeepSeek-V3.1": (5e-07, 1.5e-06), - "baseten/deepseek-ai/DeepSeek-V3-0324": (7.7e-07, 7.7e-07), - } - - for model_name, (input_cost, output_cost) in expected_pricing.items(): - model_info = litellm.model_cost.get(model_name) - assert model_info is not None, f"Missing model pricing entry: {model_name}" - assert model_info["litellm_provider"] == "baseten" - assert model_info["input_cost_per_token"] == input_cost - assert model_info["output_cost_per_token"] == output_cost - - -def test_wandb_model_api_pricing_entries(_local_model_cost_map): - - expected_pricing = { - "wandb/moonshotai/Kimi-K2.5": (6e-07, 3e-06), - "wandb/MiniMaxAI/MiniMax-M2.5": (3e-07, 1.2e-06), - "wandb/Qwen/Qwen3-235B-A22B-Instruct-2507": (1e-07, 1e-07), - "wandb/Qwen/Qwen3-235B-A22B-Thinking-2507": (1e-07, 1e-07), - "wandb/deepseek-ai/DeepSeek-R1-0528": (1.35e-06, 5.4e-06), - "wandb/deepseek-ai/DeepSeek-V3-0324": (1.14e-06, 2.75e-06), - "wandb/meta-llama/Llama-4-Scout-17B-16E-Instruct": (1.7e-07, 6.6e-07), - } - - for model_name, (input_cost, output_cost) in expected_pricing.items(): - model_info = litellm.model_cost.get(model_name) - assert model_info is not None, f"Missing model pricing entry: {model_name}" - assert model_info["litellm_provider"] == "wandb" - assert model_info["input_cost_per_token"] == input_cost - assert model_info["output_cost_per_token"] == output_cost - - -def test_openrouter_qwen36_plus_model_info(_local_model_cost_map): - - model_info = litellm.model_cost.get("openrouter/qwen/qwen3.6-plus") - - assert model_info is not None - assert model_info["litellm_provider"] == "openrouter" - assert model_info["mode"] == "chat" - assert model_info["max_input_tokens"] == 1000000 - assert model_info["max_output_tokens"] == 65536 - assert model_info["input_cost_per_token"] == 3.25e-07 - assert model_info["output_cost_per_token"] == 1.95e-06 - assert model_info["supports_function_calling"] is True - assert model_info["supports_tool_choice"] is True - assert model_info["supports_reasoning"] is True - assert model_info["supports_vision"] is True - - -@pytest.mark.parametrize( - "model", - [ - "github_copilot/mai-code-1-flash", - "github_copilot/mai-code-1-flash-internal", - ], -) -def test_github_copilot_mai_code_1_flash_pricing(_local_model_cost_map, model): - - model_info = litellm.model_cost.get(model) - - assert model_info is not None, f"Missing model pricing entry: {model}" - assert model_info["litellm_provider"] == "github_copilot" - assert model_info["mode"] == "chat" - assert model_info["input_cost_per_token"] == 7.5e-07 - assert model_info["cache_read_input_token_cost"] == 7.5e-08 - assert model_info["output_cost_per_token"] == 4.5e-06 - assert model_info["supported_endpoints"] == ["/v1/chat/completions"] - - prompt_usd, completion_usd = cost_per_token( - model=model, - prompt_tokens=1000, - completion_tokens=500, - custom_llm_provider="github_copilot", - usage_object=Usage( - prompt_tokens=1000, - completion_tokens=500, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=200), - ), - ) - - assert prompt_usd == pytest.approx((800 * 7.5e-07) + (200 * 7.5e-08)) - assert completion_usd == pytest.approx(500 * 4.5e-06) - - def test_cost_calculator_with_usage(_local_model_cost_map, monkeypatch): usage = Usage( @@ -332,13 +149,12 @@ def test_cost_calculator_with_usage(_local_model_cost_map, monkeypatch): # Step 1: Test a model where input_cost_per_image_token is not set. # In this case the calculation should use input_cost_per_token as fallback. - assert ( - model_info.get("input_cost_per_image_token") is None - ), "Test case expects that input_cost_per_image_token is not set" + assert model_info.get("input_cost_per_image_token") is None, ( + "Test case expects that input_cost_per_image_token is not set" + ) expected_cost = ( - usage.prompt_tokens_details.audio_tokens - * model_info["input_cost_per_audio_token"] + usage.prompt_tokens_details.audio_tokens * model_info["input_cost_per_audio_token"] + usage.prompt_tokens_details.text_tokens * model_info["input_cost_per_token"] + usage.prompt_tokens_details.image_tokens * model_info["input_cost_per_token"] + usage.completion_tokens * model_info["output_cost_per_token"] @@ -373,12 +189,9 @@ def test_cost_calculator_with_usage(_local_model_cost_map, monkeypatch): ) expected_cost = ( - usage.prompt_tokens_details.audio_tokens - * temp_model_info_object["input_cost_per_audio_token"] - + usage.prompt_tokens_details.text_tokens - * temp_model_info_object["input_cost_per_token"] - + usage.prompt_tokens_details.image_tokens - * temp_model_info_object["input_cost_per_image_token"] + usage.prompt_tokens_details.audio_tokens * temp_model_info_object["input_cost_per_audio_token"] + + usage.prompt_tokens_details.text_tokens * temp_model_info_object["input_cost_per_token"] + + usage.prompt_tokens_details.image_tokens * temp_model_info_object["input_cost_per_image_token"] + usage.completion_tokens * temp_model_info_object["output_cost_per_token"] ) @@ -388,14 +201,11 @@ def test_cost_calculator_with_usage(_local_model_cost_map, monkeypatch): def test_transcription_cost_uses_token_pricing(_local_model_cost_map): from litellm import completion_cost - usage = Usage( prompt_tokens=14, completion_tokens=45, total_tokens=59, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=0, audio_tokens=14 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=0, audio_tokens=14), ) response = TranscriptionResponse(text="demo text") response.usage = usage @@ -439,7 +249,6 @@ def test_transcription_token_pricing_is_provider_aware(_local_model_cost_map): def test_transcription_cost_falls_back_to_duration(_local_model_cost_map): from litellm import completion_cost - response = TranscriptionResponse(text="demo text") response.duration = 10.0 @@ -460,7 +269,6 @@ def test_vertex_chirp_3_transcription_cost_from_duration(_local_model_cost_map): every transcription priced to $0.00 instead of using input_cost_per_second.""" from litellm import completion_cost - response = TranscriptionResponse(text="demo text") response.duration = 18.0 @@ -484,9 +292,7 @@ def test_handle_realtime_stream_cost_calculation(): {"type": "session.created", "session": {"model": "gpt-3.5-turbo"}}, { "type": "response.done", - "response": { - "usage": {"input_tokens": 100, "output_tokens": 50, "total_tokens": 150} - }, + "response": {"usage": {"input_tokens": 100, "output_tokens": 50, "total_tokens": 150}}, }, { "type": "response.done", @@ -517,9 +323,7 @@ def test_handle_realtime_stream_cost_calculation(): expected_cost = (300 * 0.0015 / 1000) + ( # input tokens (100 + 200) 150 * 0.002 / 1000 ) # output tokens (50 + 100) - assert ( - abs(cost - expected_cost) <= 0.00075 - ) # Allow small floating point differences + assert abs(cost - expected_cost) <= 0.00075 # Allow small floating point differences # Test with different model name in session results[0]["session"]["model"] = "gpt-4" @@ -599,14 +403,7 @@ def test_handle_realtime_stream_cost_calculation_stores_cost_breakdown(): assert logging_obj.cost_breakdown is not None assert logging_obj.cost_breakdown["input_cost"] > 0 assert logging_obj.cost_breakdown["output_cost"] > 0 - assert ( - abs( - logging_obj.cost_breakdown["input_cost"] - + logging_obj.cost_breakdown["output_cost"] - - total_cost - ) - < 1e-9 - ) + assert abs(logging_obj.cost_breakdown["input_cost"] + logging_obj.cost_breakdown["output_cost"] - total_cost) < 1e-9 assert abs(logging_obj.cost_breakdown["total_cost"] - total_cost) < 1e-9 @@ -680,9 +477,7 @@ def test_realtime_logging_object_allows_null_transcript_in_conversation_item_add }, ] - usage = RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results( - results=results - ) + usage = RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results(results=results) logging_result = RealtimeAPITokenUsageProcessor.create_logging_realtime_object( usage=usage, results=results, @@ -732,9 +527,7 @@ def test_realtime_logging_object_does_not_validate_unknown_event_types(): }, ] - usage = RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results( - results=results - ) + usage = RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results(results=results) # On unfixed code this raises pydantic ValidationError instead of returning. logging_result = RealtimeAPITokenUsageProcessor.create_logging_realtime_object( usage=usage, @@ -746,8 +539,7 @@ def test_realtime_logging_object_does_not_validate_unknown_event_types(): unknown_types = { r["type"] for r in logging_result.results - if r["type"] - in ("rate_limits.updated", "response.function_call_arguments.delta") + if r["type"] in ("rate_limits.updated", "response.function_call_arguments.delta") } assert unknown_types == { "rate_limits.updated", @@ -780,9 +572,7 @@ def test_realtime_transcription_duration_cost(monkeypatch): "type": "session.created", "session": { "type": "transcription", - "audio": { - "input": {"transcription": {"model": "gpt-realtime-whisper"}} - }, + "audio": {"input": {"transcription": {"model": "gpt-realtime-whisper"}}}, }, }, { @@ -797,9 +587,7 @@ def test_realtime_transcription_duration_cost(monkeypatch): }, ] - combined = RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results( - results=results - ) + combined = RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results(results=results) logging_obj = Logging( model="gpt-realtime-whisper", messages=[], @@ -892,9 +680,7 @@ def test_realtime_transcription_token_billed_fallback(monkeypatch): # gpt-4o-transcribe: input_cost_per_audio_token = 2.5e-06, input_cost_per_token = 2.5e-06, # output_cost_per_token = 1e-05 - model_info = litellm.get_model_info( - model="gpt-4o-transcribe", custom_llm_provider="openai" - ) + model_info = litellm.get_model_info(model="gpt-4o-transcribe", custom_llm_provider="openai") usage = { "type": "tokens", "input_tokens": 40, @@ -975,10 +761,7 @@ def test_get_transcription_model_falls_back_to_session_model(monkeypatch): mock_response=True, ) - assert ( - result._hidden_params["response_cost"] - > result_2._hidden_params["response_cost"] - ) + assert result._hidden_params["response_cost"] > result_2._hidden_params["response_cost"] model_info = router.get_deployment_model_info( model_id="my-unique-model-id", model_name="anthropic/claude-sonnet-4-5-20250929" @@ -1141,9 +924,7 @@ def test_tiered_pricing_only_deployment_selects_router_model_id(): assert entry.get("input_cost_per_token") is None assert entry.get("tiered_pricing") is not None # The stripped shared alias must not carry tiered pricing. - assert ( - litellm.model_cost["dashscope/qwen-tier-only-test"].get("tiered_pricing") is None - ) + assert litellm.model_cost["dashscope/qwen-tier-only-test"].get("tiered_pricing") is None selected = _select_model_name_for_cost_calc( model="dashscope/qwen-tier-only-test", @@ -1223,9 +1004,7 @@ def test_azure_realtime_cost_calculator(_local_model_cost_map): combined_usage_object=Usage( prompt_tokens=100, completion_tokens=100, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=10, audio_tokens=90 - ), + prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=10, audio_tokens=90), ), custom_llm_provider="azure", litellm_model_name="my-custom-azure-deployment", @@ -1244,7 +1023,6 @@ def test_azure_audio_output_cost_calculation(_local_model_cost_map): """ from litellm.types.utils import Choices, CompletionTokensDetailsWrapper, Message - # Scenario from issue #19764: # Input: 17 text tokens, 0 audio tokens # Output: 110 text tokens, 482 audio tokens @@ -1300,14 +1078,10 @@ def test_azure_audio_output_cost_calculation(_local_model_cost_map): wrong_total_cost = expected_input_cost + wrong_output_cost # Verify audio tokens are NOT charged at text rate (the bug) - assert ( - abs(cost - wrong_total_cost) > 0.001 - ), "Bug: Audio tokens are being charged at text token rate" + assert abs(cost - wrong_total_cost) > 0.001, "Bug: Audio tokens are being charged at text token rate" # Verify cost matches - assert ( - abs(cost - expected_total_cost) < 0.0000001 - ), f"Expected cost {expected_total_cost}, got {cost}" + assert abs(cost - expected_total_cost) < 0.0000001, f"Expected cost {expected_total_cost}, got {cost}" def test_default_image_cost_calculator(monkeypatch): @@ -1321,9 +1095,7 @@ def test_default_image_cost_calculator(monkeypatch): monkeypatch.setattr( litellm, "model_cost", - { - "azure/bf9001cd7209f5734ecb4ab937a5a0e2ba5f119708bd68f184db362930f9dc7b": temp_object - }, + {"azure/bf9001cd7209f5734ecb4ab937a5a0e2ba5f119708bd68f184db362930f9dc7b": temp_object}, ) args = { @@ -1539,9 +1311,7 @@ def test_gemini_25_implicit_caching_cost(): expected_cost = 0.00068708 # Allow for small floating point differences - assert ( - abs(result - expected_cost) < 1e-8 - ), f"Expected cost {expected_cost}, but got {result}" + assert abs(result - expected_cost) < 1e-8, f"Expected cost {expected_cost}, but got {result}" print(f"✓ Gemini 2.5 implicit caching cost calculation is correct: ${result:.8f}") @@ -1612,9 +1382,7 @@ def test_log_context_cost_calculation(): # Get model info to understand the pricing from litellm import get_model_info - model_info = get_model_info( - model="claude-4-sonnet-20250514", custom_llm_provider="anthropic" - ) + model_info = get_model_info(model="claude-4-sonnet-20250514", custom_llm_provider="anthropic") # Calculate expected cost based on actual model pricing input_cost_per_token = model_info.get("input_cost_per_token", 0) @@ -1622,12 +1390,8 @@ def test_log_context_cost_calculation(): cache_creation_cost_per_token = model_info.get("cache_creation_input_token_cost", 0) # Check if tiered pricing is applied - input_cost_above_200k = model_info.get( - "input_cost_per_token_above_200k_tokens", input_cost_per_token - ) - output_cost_above_200k = model_info.get( - "output_cost_per_token_above_200k_tokens", output_cost_per_token - ) + input_cost_above_200k = model_info.get("input_cost_per_token_above_200k_tokens", input_cost_per_token) + output_cost_above_200k = model_info.get("output_cost_per_token_above_200k_tokens", output_cost_per_token) cache_creation_above_200k = model_info.get( "cache_creation_input_token_cost_above_200k_tokens", cache_creation_cost_per_token, @@ -1635,31 +1399,23 @@ def test_log_context_cost_calculation(): print(f"DEBUG: Base input cost per token: ${input_cost_per_token:.2e}") print(f"DEBUG: Base output cost per token: ${output_cost_per_token:.2e}") - print( - f"DEBUG: Base cache creation cost per token: ${cache_creation_cost_per_token:.2e}" - ) + print(f"DEBUG: Base cache creation cost per token: ${cache_creation_cost_per_token:.2e}") # Handle tiered pricing - if not available, use base pricing if input_cost_above_200k is not None: - print( - f"DEBUG: Tiered input cost per token (>200k): ${input_cost_above_200k:.2e}" - ) + print(f"DEBUG: Tiered input cost per token (>200k): ${input_cost_above_200k:.2e}") else: print("DEBUG: No tiered input pricing available, using base pricing") input_cost_above_200k = input_cost_per_token if output_cost_above_200k is not None: - print( - f"DEBUG: Tiered output cost per token (>200k): ${output_cost_above_200k:.2e}" - ) + print(f"DEBUG: Tiered output cost per token (>200k): ${output_cost_above_200k:.2e}") else: print("DEBUG: No tiered output pricing available, using base pricing") output_cost_above_200k = output_cost_per_token if cache_creation_above_200k is not None: - print( - f"DEBUG: Tiered cache creation cost per token (>200k): ${cache_creation_above_200k:.2e}" - ) + print(f"DEBUG: Tiered cache creation cost per token (>200k): ${cache_creation_above_200k:.2e}") else: print("DEBUG: No tiered cache creation pricing available, using base pricing") cache_creation_above_200k = cache_creation_cost_per_token @@ -1673,13 +1429,9 @@ def test_log_context_cost_calculation(): print(f"DEBUG: Expected total: ${expected_total:.6f}") # Allow for small floating point differences - assert ( - abs(result - expected_total) < 1e-6 - ), f"Expected cost ${expected_total:.6f}, but got ${result:.6f}" + assert abs(result - expected_total) < 1e-6, f"Expected cost ${expected_total:.6f}, but got ${result:.6f}" - print( - f"✓ Log context cost calculation with tiered pricing is correct: ${result:.6f}" - ) + print(f"✓ Log context cost calculation with tiered pricing is correct: ${result:.6f}") print(f" - Input tokens (300k): ${expected_input_cost:.6f}") print(f" - Output tokens (50k): ${expected_output_cost:.6f}") print(f" - Cache creation (1k): ${expected_cache_cost:.6f}") @@ -1738,8 +1490,7 @@ def test_gemini_25_explicit_caching_cost_direct_usage(): expected_actual_cost = ( model_info["input_cost_per_token"] * usage.prompt_tokens_details.text_tokens - + model_info["cache_read_input_token_cost"] - * usage.prompt_tokens_details.cached_tokens + + model_info["cache_read_input_token_cost"] * usage.prompt_tokens_details.cached_tokens + model_info["output_cost_per_token"] * usage.completion_tokens ) @@ -1763,7 +1514,6 @@ def test_azure_ai_cache_cost_calculation(_local_model_cost_map): from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token from litellm.types.utils import PromptTokensDetailsWrapper, Usage - # Register a custom azure_ai model with cache pricing test_model_id = "test-azure-ai-claude-model" litellm.register_model( @@ -1812,12 +1562,12 @@ def test_azure_ai_cache_cost_calculation(_local_model_cost_map): print(f"Output cost: {output_cost}, Expected: {expected_output_cost}") print(f"Total cost: {total_cost}") - assert ( - abs(input_cost - expected_input_cost) < 1e-10 - ), f"Input cost mismatch: got {input_cost}, expected {expected_input_cost}" - assert ( - abs(output_cost - expected_output_cost) < 1e-10 - ), f"Output cost mismatch: got {output_cost}, expected {expected_output_cost}" + assert abs(input_cost - expected_input_cost) < 1e-10, ( + f"Input cost mismatch: got {input_cost}, expected {expected_input_cost}" + ) + assert abs(output_cost - expected_output_cost) < 1e-10, ( + f"Output cost mismatch: got {output_cost}, expected {expected_output_cost}" + ) AZURE_GPT_5_6_MAP_KEYS = ( @@ -1886,6 +1636,7 @@ def test_azure_gpt_5_6_rates_match_azure_price_page(_local_model_cost_map, model for key in token_cost_keys: assert entry[key] == pytest.approx(global_entry[key] * 1.1), key + def test_vertex_regional_deployment_costs_uplift_over_global(monkeypatch): """ Regression for https://github.com/BerriAI/litellm/issues/34393: two Vertex @@ -1968,7 +1719,6 @@ def test_cost_discount_vertex_ai(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response (use a model that exists in model_prices_and_context_window.json) response = ModelResponse( id="test-id", @@ -1997,7 +1747,6 @@ def test_cost_discount_vertex_ai(monkeypatch): custom_llm_provider="vertex_ai", ) - # Verify discount is applied (5% off means 95% of original cost) expected_cost = cost_without_discount * 0.95 assert cost_with_discount == pytest.approx(expected_cost, rel=1e-9) @@ -2015,7 +1764,6 @@ def test_cost_discount_not_applied_to_other_providers(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response for OpenAI response = ModelResponse( id="test-id", @@ -2044,7 +1792,6 @@ def test_cost_discount_not_applied_to_other_providers(monkeypatch): custom_llm_provider="openai", ) - # Costs should be the same (no discount applied to OpenAI) assert cost_with_selective_discount == cost_without_discount @@ -2060,7 +1807,6 @@ def test_cost_margin_percentage(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response response = ModelResponse( id="test-id", @@ -2089,7 +1835,6 @@ def test_cost_margin_percentage(monkeypatch): custom_llm_provider="openai", ) - # Verify margin is applied (10% margin means 110% of original cost) expected_cost = cost_without_margin * 1.10 assert cost_with_margin == pytest.approx(expected_cost, rel=1e-9) @@ -2107,7 +1852,6 @@ def test_cost_margin_fixed_amount(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response response = ModelResponse( id="test-id", @@ -2136,7 +1880,6 @@ def test_cost_margin_fixed_amount(monkeypatch): custom_llm_provider="openai", ) - # Verify fixed margin is applied expected_cost = cost_without_margin + 0.001 assert cost_with_margin == pytest.approx(expected_cost, rel=1e-9) @@ -2154,7 +1897,6 @@ def test_cost_margin_combined(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response response = ModelResponse( id="test-id", @@ -2174,9 +1916,7 @@ def test_cost_margin_combined(monkeypatch): ) # Set 8% margin + $0.0005 fixed for openai - monkeypatch.setattr(litellm, "cost_margin_config", { - "openai": {"percentage": 0.08, "fixed_amount": 0.0005} - }) + monkeypatch.setattr(litellm, "cost_margin_config", {"openai": {"percentage": 0.08, "fixed_amount": 0.0005}}) # Calculate cost with margin cost_with_margin = completion_cost( @@ -2185,7 +1925,6 @@ def test_cost_margin_combined(monkeypatch): custom_llm_provider="openai", ) - # Verify combined margin is applied expected_cost = cost_without_margin * 1.08 + 0.0005 assert cost_with_margin == pytest.approx(expected_cost, rel=1e-9) @@ -2203,7 +1942,6 @@ def test_cost_margin_global(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response response = ModelResponse( id="test-id", @@ -2232,7 +1970,6 @@ def test_cost_margin_global(monkeypatch): custom_llm_provider="openai", ) - # Verify global margin is applied expected_cost = cost_without_margin * 1.05 assert cost_with_global_margin == pytest.approx(expected_cost, rel=1e-9) @@ -2250,7 +1987,6 @@ def test_cost_margin_provider_overrides_global(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response response = ModelResponse( id="test-id", @@ -2279,16 +2015,13 @@ def test_cost_margin_provider_overrides_global(monkeypatch): custom_llm_provider="openai", ) - # Verify provider-specific margin is used (not global) expected_cost = cost_without_margin * 1.10 # 10% from provider, not 5% from global assert cost_with_provider_margin == pytest.approx(expected_cost, rel=1e-9) print("✓ Cost margin provider override test passed:") print(f" - Original cost: ${cost_without_margin:.6f}") - print( - f" - Cost with provider margin (10%, overrides 5% global): ${cost_with_provider_margin:.6f}" - ) + print(f" - Cost with provider margin (10%, overrides 5% global): ${cost_with_provider_margin:.6f}") print(f" - Margin added: ${cost_with_provider_margin - cost_without_margin:.6f}") @@ -2299,7 +2032,6 @@ def test_cost_margin_with_discount(monkeypatch): from litellm import completion_cost from litellm.types.utils import Usage - # Create mock response response = ModelResponse( id="test-id", @@ -2330,7 +2062,6 @@ def test_cost_margin_with_discount(monkeypatch): custom_llm_provider="openai", ) - # Verify: discount applied first, then margin # Base cost -> discount: base * 0.95 -> margin: (base * 0.95) * 1.10 expected_cost = base_cost * 0.95 * 1.10 @@ -2368,9 +2099,7 @@ def test_azure_image_generation_cost_calculator(): size=None, usage=ImageUsage( input_tokens=0, - input_tokens_details=ImageUsageInputTokensDetails( - image_tokens=0, text_tokens=0 - ), + input_tokens_details=ImageUsageInputTokensDetails(image_tokens=0, text_tokens=0), output_tokens=0, total_tokens=0, ), @@ -2400,7 +2129,6 @@ def test_completion_cost_extracts_service_tier_from_response(_local_model_cost_m """Test that completion_cost extracts service_tier from completion_response object.""" from litellm import completion_cost - # Test with gpt-5-nano which has flex pricing model = "gpt-5-nano" @@ -2441,23 +2169,18 @@ def test_completion_cost_extracts_service_tier_from_response(_local_model_cost_m assert flex_cost < standard_cost, "Flex cost should be less than standard cost" flex_ratio = flex_cost / standard_cost - assert ( - 0.45 <= flex_ratio <= 0.55 - ), f"Flex pricing should be ~50% of standard, got {flex_ratio:.2f}" + assert 0.45 <= flex_ratio <= 0.55, f"Flex pricing should be ~50% of standard, got {flex_ratio:.2f}" def test_completion_cost_extracts_service_tier_from_usage(_local_model_cost_map): """Test that completion_cost extracts service_tier from usage object.""" from litellm import completion_cost - # Test with gpt-5-nano which has flex pricing model = "gpt-5-nano" # Create usage object with service_tier - usage_with_service_tier = Usage( - prompt_tokens=1000, completion_tokens=500, total_tokens=1500 - ) + usage_with_service_tier = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) # Set service_tier as an attribute on the usage object setattr(usage_with_service_tier, "service_tier", "flex") @@ -2475,9 +2198,7 @@ def test_completion_cost_extracts_service_tier_from_usage(_local_model_cost_map) ) # Create usage object without service_tier - usage_without_service_tier = Usage( - prompt_tokens=1000, completion_tokens=500, total_tokens=1500 - ) + usage_without_service_tier = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) # Create ModelResponse with usage without service_tier response_standard = ModelResponse( @@ -2498,16 +2219,13 @@ def test_completion_cost_extracts_service_tier_from_usage(_local_model_cost_map) assert flex_cost < standard_cost, "Flex cost should be less than standard cost" flex_ratio = flex_cost / standard_cost - assert ( - 0.45 <= flex_ratio <= 0.55 - ), f"Flex pricing should be ~50% of standard, got {flex_ratio:.2f}" + assert 0.45 <= flex_ratio <= 0.55, f"Flex pricing should be ~50% of standard, got {flex_ratio:.2f}" def test_completion_cost_service_tier_priority(_local_model_cost_map): """Test that service_tier extraction follows priority: optional_params > completion_response > usage.""" from litellm import completion_cost - # Test with gpt-5-nano which has flex pricing model = "gpt-5-nano" @@ -2556,16 +2274,13 @@ def test_completion_cost_service_tier_priority(_local_model_cost_map): assert cost_from_usage > 0, "Cost from usage should be greater than 0" # Costs should be similar (all using flex) - assert ( - abs(cost_from_params - cost_from_usage) < 1e-6 - ), "Costs from params and usage should be similar (both flex)" + assert abs(cost_from_params - cost_from_usage) < 1e-6, "Costs from params and usage should be similar (both flex)" def test_completion_cost_service_tier_for_bedrock(_local_model_cost_map): """Test that Bedrock cost calculation applies service_tier-specific pricing.""" from litellm import completion_cost - model = "bedrock/us-east-1/test-bedrock-service-tier-cost-model" litellm.register_model( model_cost={ @@ -2621,7 +2336,6 @@ def test_completion_cost_service_tier_for_anthropic(_local_model_cost_map): from litellm import completion_cost from litellm.llms.anthropic.chat.transformation import AnthropicConfig - model = "claude-test-service-tier-cost-model" litellm.register_model( model_cost={ @@ -2674,7 +2388,6 @@ def test_completion_cost_anthropic_auto_tier_uses_served_priority_rate(_local_mo from litellm import completion_cost from litellm.llms.anthropic.chat.transformation import AnthropicConfig - model = "claude-test-auto-tier-cost-model" litellm.register_model( model_cost={ @@ -2768,7 +2481,6 @@ def test_completion_cost_non_string_service_tier_defers_to_served_tier(_local_mo from litellm import completion_cost from litellm.llms.anthropic.chat.transformation import AnthropicConfig - model = "claude-test-non-string-tier-cost-model" litellm.register_model( model_cost={ @@ -2818,7 +2530,6 @@ def test_completion_cost_non_string_response_service_tier_defers_to_served_tier( from litellm import completion_cost from litellm.llms.anthropic.chat.transformation import AnthropicConfig - model = "claude-test-response-non-string-tier-cost-model" litellm.register_model( model_cost={ @@ -2841,9 +2552,7 @@ def test_completion_cost_non_string_response_service_tier_defers_to_served_tier( }, reasoning_content=None, ) - response = ModelResponse( - usage=usage, model=model, service_tier={"name": "priority"} - ) + response = ModelResponse(usage=usage, model=model, service_tier={"name": "priority"}) cost = completion_cost( completion_response=response, @@ -2866,7 +2575,6 @@ def test_completion_cost_non_string_usage_service_tier_prices_standard(_local_mo """ from litellm import completion_cost - model = "claude-test-usage-non-string-tier-cost-model" litellm.register_model( model_cost={ @@ -2913,7 +2621,6 @@ def test_anthropic_cost_per_token_prices_cache_at_served_tier_with_multiplier(_l ) from litellm.types.utils import PromptTokensDetailsWrapper, Usage - model = "claude-test-priority-cache-fast-model" litellm.register_model( model_cost={ @@ -2939,9 +2646,7 @@ def test_anthropic_cost_per_token_prices_cache_at_served_tier_with_multiplier(_l ) usage.speed = "fast" - prompt_cost, completion_cost = anthropic_cost_per_token( - model=model, usage=usage, service_tier="priority" - ) + prompt_cost, completion_cost = anthropic_cost_per_token(model=model, usage=usage, service_tier="priority") expected_prompt = ((1000 - 200) * 6e-6 + 200 * 0.6e-6) * 2 expected_completion = 500 * 30e-6 * 2 @@ -3071,9 +2776,7 @@ def test_anthropic_fast_multiplier_only_on_models_with_fast_mode(_local_model_co "model", ["claude-sonnet-4-6", "claude-mythos-5", "claude-mythos-preview"], ) -def test_anthropic_us_data_residency_uplift_on_claude_4_6_and_later_models( - _local_model_cost_map, monkeypatch, model -): +def test_anthropic_us_data_residency_uplift_on_claude_4_6_and_later_models(_local_model_cost_map, monkeypatch, model): """ Anthropic bills every Claude 4.6+ model served with ``inference_geo="us"`` at 1.1x, and echoes that geo back in the response usage, so each of these real @@ -3138,29 +2841,27 @@ def test_gemini_cache_tokens_details_no_negative_values(): usage = VertexGeminiConfig._calculate_usage(completion_response) # Text tokens should be non-cached text only: 9402 - 9393 = 9 - assert ( - usage.prompt_tokens_details.text_tokens == 9 - ), f"Expected text_tokens=9, got {usage.prompt_tokens_details.text_tokens}" + assert usage.prompt_tokens_details.text_tokens == 9, ( + f"Expected text_tokens=9, got {usage.prompt_tokens_details.text_tokens}" + ) # Image tokens should be non-cached image only: 258 - 258 = 0 - assert ( - usage.prompt_tokens_details.image_tokens == 0 - ), f"Expected image_tokens=0, got {usage.prompt_tokens_details.image_tokens}" + assert usage.prompt_tokens_details.image_tokens == 0, ( + f"Expected image_tokens=0, got {usage.prompt_tokens_details.image_tokens}" + ) # Total cached should match - assert ( - usage.prompt_tokens_details.cached_tokens == 9651 - ), f"Expected cached_tokens=9651, got {usage.prompt_tokens_details.cached_tokens}" + assert usage.prompt_tokens_details.cached_tokens == 9651, ( + f"Expected cached_tokens=9651, got {usage.prompt_tokens_details.cached_tokens}" + ) # MOST IMPORTANT: text_tokens should NEVER be negative - assert ( - usage.prompt_tokens_details.text_tokens >= 0 - ), f"BUG: text_tokens is negative ({usage.prompt_tokens_details.text_tokens})! This was the issue in #18750" - - print( - "✅ Issue #18750 fix verified: text_tokens is correctly calculated and non-negative" + assert usage.prompt_tokens_details.text_tokens >= 0, ( + f"BUG: text_tokens is negative ({usage.prompt_tokens_details.text_tokens})! This was the issue in #18750" ) + print("✅ Issue #18750 fix verified: text_tokens is correctly calculated and non-negative") + def test_gemini_without_cache_tokens_details(): """ @@ -3227,18 +2928,18 @@ def test_gemini_implicit_caching_cost_calculation(): usage = VertexGeminiConfig._calculate_usage(completion_response) # Verify parsing - assert ( - usage.cache_read_input_tokens == 8000 - ), f"cache_read_input_tokens should be 8000, got {usage.cache_read_input_tokens}" - assert ( - usage.prompt_tokens_details.cached_tokens == 8000 - ), f"cached_tokens should be 8000, got {usage.prompt_tokens_details.cached_tokens}" + assert usage.cache_read_input_tokens == 8000, ( + f"cache_read_input_tokens should be 8000, got {usage.cache_read_input_tokens}" + ) + assert usage.prompt_tokens_details.cached_tokens == 8000, ( + f"cached_tokens should be 8000, got {usage.prompt_tokens_details.cached_tokens}" + ) # CRITICAL: text_tokens should be (10000 - 8000) = 2000, NOT 10000 # This is the fix for issue #16341 - assert ( - usage.prompt_tokens_details.text_tokens == 2000 - ), f"text_tokens should be 2000 (10000 - 8000), got {usage.prompt_tokens_details.text_tokens}" + assert usage.prompt_tokens_details.text_tokens == 2000, ( + f"text_tokens should be 2000 (10000 - 8000), got {usage.prompt_tokens_details.text_tokens}" + ) # Verify cost calculation uses cached token pricing response = ModelResponse( @@ -3276,9 +2977,7 @@ def test_gemini_implicit_caching_cost_calculation(): f"Cached tokens may not be using reduced pricing." ) - print( - "✅ Issue #16341 fix verified: Gemini implicit caching cost calculated correctly" - ) + print("✅ Issue #16341 fix verified: Gemini implicit caching cost calculated correctly") def test_additional_costs_only_for_azure_ai(_local_model_cost_map): @@ -3292,7 +2991,6 @@ def test_additional_costs_only_for_azure_ai(_local_model_cost_map): """ from litellm.cost_calculator import _get_additional_costs - # Non-azure_ai providers should return None result = _get_additional_costs( model="gpt-4o", @@ -3319,45 +3017,6 @@ def test_additional_costs_only_for_azure_ai(_local_model_cost_map): assert result is None, "Vertex AI should have no additional costs" -def test_openrouter_gemini_3_1_flash_lite_preview_pricing(_local_model_cost_map): - """ - Test that openrouter/google/gemini-3.1-flash-lite-preview has a pricing entry. - - Regression test for https://github.com/BerriAI/litellm/issues/25604 - - The model exists and is callable via OpenRouter, but was missing from - model_prices_and_context_window.json when other Gemini 3.x variants were present. - This caused ValueError: This model isn't mapped yet during router pre-call checks. - """ - - model_name = "openrouter/google/gemini-3.1-flash-lite-preview" - model_info = litellm.model_cost.get(model_name) - - assert model_info is not None, f"Missing model pricing entry: {model_name}" - assert model_info["litellm_provider"] == "openrouter" - assert model_info["input_cost_per_token"] == 2.5e-07 - assert model_info["output_cost_per_token"] == 1.5e-06 - assert model_info["max_input_tokens"] == 1048576 - assert model_info["max_output_tokens"] == 65536 - - -def test_gemini_3_1_flash_lite_pricing(_local_model_cost_map): - - for model_name in ( - "gemini-3.1-flash-lite", - "gemini/gemini-3.1-flash-lite", - "vertex_ai/gemini-3.1-flash-lite", - ): - model_info = litellm.model_cost.get(model_name) - assert model_info is not None, f"Missing model pricing entry: {model_name}" - assert model_info["input_cost_per_token"] == 2.5e-07 - assert model_info["input_cost_per_audio_token"] == 5e-07 - assert model_info["output_cost_per_token"] == 1.5e-06 - assert model_info["output_cost_per_reasoning_token"] == 1.5e-06 - assert model_info["cache_read_input_token_cost"] == 2.5e-08 - assert model_info["max_input_tokens"] == 1048576 - - def test_custom_pricing_applies_cache_read_input_cost(): """ Bug 1 reproduction: custom_cost_per_token with cache_read_input_token_cost @@ -3435,12 +3094,7 @@ def test_custom_pricing_applies_cache_creation_input_cost_via_prompt_details(): }, ) - expected = ( - (4000 - 1000 - 500) * 0.0000025 - + 1000 * 0.00000025 - + 500 * 0.000003125 - + 100 * 0.000015 - ) + expected = (4000 - 1000 - 500) * 0.0000025 + 1000 * 0.00000025 + 500 * 0.000003125 + 100 * 0.000015 assert cost == pytest.approx(expected) @@ -3485,9 +3139,7 @@ def test_custom_pricing_applies_cache_creation_input_cost_via_cache_write_tokens }, ) - expected_prompt = ( - (4000 - 1000 - 500) * 0.0000025 + 1000 * 0.00000025 + 500 * 0.000003125 - ) + expected_prompt = (4000 - 1000 - 500) * 0.0000025 + 1000 * 0.00000025 + 500 * 0.000003125 expected_completion = 100 * 0.000015 assert prompt_cost == pytest.approx(expected_prompt) @@ -3527,10 +3179,7 @@ def test_extract_cache_read_tokens_zero_when_missing(): assert _extract_cache_read_tokens({}) == 0 assert _extract_cache_read_tokens({"cache_read_input_tokens": None}) == 0 - assert ( - _extract_cache_read_tokens({"prompt_tokens_details": {"cached_tokens": None}}) - == 0 - ) + assert _extract_cache_read_tokens({"prompt_tokens_details": {"cached_tokens": None}}) == 0 def test_extract_cache_creation_tokens_anthropic_top_level(): @@ -3572,12 +3221,7 @@ def test_extract_cache_creation_tokens_zero_when_missing(): assert _extract_cache_creation_tokens({}) == 0 assert _extract_cache_creation_tokens({"cache_creation_input_tokens": None}) == 0 - assert ( - _extract_cache_creation_tokens( - {"prompt_tokens_details": {"cache_write_tokens": None}} - ) - == 0 - ) + assert _extract_cache_creation_tokens({"prompt_tokens_details": {"cache_write_tokens": None}}) == 0 def test_custom_pricing_anthropic_style_cache_tokens_not_double_counted(): @@ -3664,94 +3308,6 @@ def test_custom_pricing_without_cache_keys_preserves_legacy_behavior(): assert cost == pytest.approx(expected) -def test_openrouter_gemini_3_1_flash_lite_stable_pricing(_local_model_cost_map): - """ - Test that openrouter/google/gemini-3.1-flash-lite (stable, no -preview suffix) - has a pricing entry. - - Google promoted gemini-3.1-flash-lite to GA on 2026-05-07. PR #27933 added the - stable pricing for the bare, gemini/, and vertex_ai/ prefixes but missed the - openrouter/google/ variant — every other Gemini family in the file has an - openrouter/google/ sibling (2.0-flash-001, 2.5-flash, 2.5-pro, 3-flash-preview, - 3-pro-preview, 3.1-flash-lite-preview, 3.1-pro-preview), so the gap is a - consistency issue, not a design choice. Same shape as the preview-variant gap - fixed in PR #25610. - - Pricing matches the existing -preview entry one-for-one (input $0.25/M, output - $1.50/M, cache-read $0.025/M) — Google did not change costs at the GA cutover. - """ - - model_name = "openrouter/google/gemini-3.1-flash-lite" - model_info = litellm.model_cost.get(model_name) - - assert model_info is not None, f"Missing model pricing entry: {model_name}" - assert model_info["litellm_provider"] == "openrouter" - assert model_info["input_cost_per_token"] == 2.5e-07 - assert model_info["output_cost_per_token"] == 1.5e-06 - assert model_info["cache_read_input_token_cost"] == 2.5e-08 - assert model_info["max_input_tokens"] == 1048576 - assert model_info["max_output_tokens"] == 65536 - - -def test_completion_cost_logs_reasoning_and_cache_breakdown(_local_model_cost_map): - """ - completion_cost must surface explicit reasoning and cache-read costs into the - cost_breakdown stored on the logging object, so they end up in the spend logs - rather than being silently folded into the output/input totals. - """ - from datetime import datetime - - from litellm.litellm_core_utils.litellm_logging import Logging - from litellm.types.utils import Choices, CompletionTokensDetailsWrapper, Message - - - logging_obj = Logging( - model="gemini-2.5-flash", - messages=[{"role": "user", "content": "Hello"}], - stream=False, - call_type="completion", - start_time=datetime.now(), - litellm_call_id="reasoning-cache-breakdown", - function_id="f", - ) - - response = ModelResponse( - id="x", - created=1, - model="gemini-2.5-flash", - object="chat.completion", - choices=[ - Choices( - index=0, - message=Message(role="assistant", content="hi"), - finish_reason="length", - ) - ], - usage=Usage( - prompt_tokens=209, - completion_tokens=3996, - total_tokens=4205, - completion_tokens_details=CompletionTokensDetailsWrapper( - reasoning_tokens=3114, text_tokens=882 - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=100, text_tokens=109 - ), - ), - ) - - litellm.completion_cost( - completion_response=response, - model="gemini-2.5-flash", - custom_llm_provider="vertex_ai", - litellm_logging_obj=logging_obj, - ) - - assert logging_obj.cost_breakdown is not None - assert logging_obj.cost_breakdown["reasoning_cost"] == pytest.approx(3114 * 2.5e-06) - assert logging_obj.cost_breakdown["cache_read_cost"] == pytest.approx(100 * 3e-08) - - def test_completion_cost_logs_the_rates_it_billed_at(monkeypatch): """A caller reporting the cost lines beside their per-token rates reads both off this one call. completion_cost infers the provider, and xai's inclusive tier thresholds put a request sitting @@ -3802,9 +3358,7 @@ def test_completion_cost_logs_the_rates_it_billed_at(monkeypatch): assert rates is not None assert rates.input_cost_per_token == pytest.approx(6e-6) assert rates.cache_read_input_token_cost == pytest.approx(6e-7) - assert logging_obj.cost_breakdown["cache_read_cost"] == pytest.approx( - 100_000 * rates.cache_read_input_token_cost - ) + assert logging_obj.cost_breakdown["cache_read_cost"] == pytest.approx(100_000 * rates.cache_read_input_token_cost) assert logging_obj.cost_breakdown["output_cost"] == pytest.approx(1_000 * rates.output_cost_per_token) @@ -4026,11 +3580,7 @@ def test_completion_cost_bills_interactions_api_response(): cost = completion_cost(completion_response=response, custom_llm_provider="gemini") reasoning_rate = model_info.get("output_cost_per_reasoning_token") or model_info["output_cost_per_token"] - expected = ( - 100 * model_info["input_cost_per_token"] - + 50 * model_info["output_cost_per_token"] - + 25 * reasoning_rate - ) + expected = 100 * model_info["input_cost_per_token"] + 50 * model_info["output_cost_per_token"] + 25 * reasoning_rate assert cost == pytest.approx(expected) assert cost > 0 @@ -4201,7 +3751,9 @@ def test_completion_cost_prices_anthropic_shaped_cache_read_tokens(_local_model_ 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: +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"}}], @@ -4269,6 +3821,8 @@ def test_completion_cost_together_metadata_only_model_still_uses_size_bucket(_lo ) 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. @@ -4553,60 +4107,6 @@ def test_completion_cost_keeps_custom_priced_slash_router_id(_local_model_cost_m 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_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", [ @@ -4755,32 +4255,6 @@ def test_explicit_pricing_precedes_private_provider_response_model( assert selected == expected -def test_cost_per_token_mistral_voxtral_tts_bills_per_input_character(_local_model_cost_map): - prompt_usd, completion_usd = cost_per_token( - model="voxtral-mini-tts-2603", - custom_llm_provider="mistral", - call_type="speech", - prompt_characters=1000, - ) - - assert prompt_usd == pytest.approx(1000 * 1.6e-05) - assert completion_usd == 0.0 - - -def test_batch_cost_calculator_gpt_6_astra_bills_half_the_standard_rate(_local_model_cost_map): - """gpt-6-astra batch pricing is 50% off the standard $10 input and $50 output rates per 1M tokens.""" - from litellm.cost_calculator import batch_cost_calculator - - usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - - prompt_cost, completion_cost = batch_cost_calculator( - usage=usage, model="gpt-6-astra", custom_llm_provider="openai" - ) - - assert prompt_cost == pytest.approx(1000 * 5e-6) - assert completion_cost == pytest.approx(500 * 2.5e-5) - - def test_handle_realtime_stream_cost_calculation_bills_nested_reasoning_tokens_once( _local_model_cost_map: None, ) -> None: diff --git a/tests/test_litellm/test_daybreak_model_metadata.py b/tests/test_litellm/test_daybreak_model_metadata.py index 79149b84f0b..58f9ff4e7c8 100644 --- a/tests/test_litellm/test_daybreak_model_metadata.py +++ b/tests/test_litellm/test_daybreak_model_metadata.py @@ -32,13 +32,6 @@ def _load(path): return json.load(f) -def test_blue_alias_matches_its_snapshot_computer_use(): - cost_map = _load(MAIN_PATH) - - assert cost_map[BLUE_ALIAS]["supports_computer_use"] is True - assert cost_map[BLUE_SNAPSHOT]["supports_computer_use"] is True - - @pytest.mark.parametrize(("alias", "snapshot"), OFFICIAL_ALIAS_SNAPSHOTS) def test_official_alias_tracks_snapshot(alias, snapshot): cost_map = _load(MAIN_PATH) @@ -51,11 +44,3 @@ def test_official_alias_tracks_snapshot(alias, snapshot): field: snapshot_info.get(field) for field in PRICE_FIELDS } assert alias_info["max_output_tokens"] == snapshot_info["max_output_tokens"] - - -@pytest.mark.parametrize("model", (*DAYBREAK_MODELS, BLUE_SNAPSHOT, *(alias for alias, _ in OFFICIAL_ALIAS_SNAPSHOTS))) -def test_backup_matches_main(model): - main_cost = _load(MAIN_PATH) - backup_cost = _load(BACKUP_PATH) - - assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_deepseek_model_metadata.py b/tests/test_litellm/test_deepseek_model_metadata.py index 9cbd14ebd1e..e8a98094c4e 100644 --- a/tests/test_litellm/test_deepseek_model_metadata.py +++ b/tests/test_litellm/test_deepseek_model_metadata.py @@ -12,14 +12,11 @@ field set to ``True``. import json import os - import litellm from litellm.utils import ( _supports_factory, - supports_response_schema, ) - # --------------------------------------------------------------------------- # Data-level tests – verify the JSON files are in sync # --------------------------------------------------------------------------- @@ -39,18 +36,6 @@ class TestDeepSeekModelCostEntries: """Verify that provider-prefixed DeepSeek entries contain the same capability flags as their bare-name counterparts in the JSON files.""" - def test_deepseek_chat_max_input_tokens_matches_bare_in_backup(self): - data = _load_backup_json() - bare = data.get("deepseek-chat", {}) - prefixed = data.get("deepseek/deepseek-chat", {}) - assert prefixed.get("max_input_tokens") == bare.get("max_input_tokens") - - def test_deepseek_reasoner_max_output_tokens_matches_bare_in_backup(self): - data = _load_backup_json() - bare = data.get("deepseek-reasoner", {}) - prefixed = data.get("deepseek/deepseek-reasoner", {}) - assert prefixed.get("max_output_tokens") == bare.get("max_output_tokens") - # --------------------------------------------------------------------------- # API-level tests – verify supports_response_schema returns True @@ -61,28 +46,6 @@ class TestSupportsResponseSchemaDeepSeek: """All calling conventions for DeepSeek should return True for ``supports_response_schema``.""" - def test_provider_slash_model(self): - assert supports_response_schema(model="deepseek/deepseek-chat") is True - - def test_explicit_provider(self): - assert ( - supports_response_schema( - model="deepseek-chat", custom_llm_provider="deepseek" - ) - is True - ) - - def test_reasoner_provider_slash_model(self): - assert supports_response_schema(model="deepseek/deepseek-reasoner") is True - - def test_reasoner_explicit_provider(self): - assert ( - supports_response_schema( - model="deepseek-reasoner", custom_llm_provider="deepseek" - ) - is True - ) - # --------------------------------------------------------------------------- # Fallback-logic test – bare model entry used when prefixed is incomplete diff --git a/tests/test_litellm/test_fireworks_serverless_model_costs.py b/tests/test_litellm/test_fireworks_serverless_model_costs.py index 5b7561f6a2c..0b55b0ff1e4 100644 --- a/tests/test_litellm/test_fireworks_serverless_model_costs.py +++ b/tests/test_litellm/test_fireworks_serverless_model_costs.py @@ -14,11 +14,6 @@ import os import pytest -from litellm import completion_cost -from litellm.types.utils import Choices, Message, ModelResponse, Usage -from litellm.utils import get_model_info - - NEW_ENTRIES = { "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813": { "input_cost_per_token": 1.32e-06, @@ -32,46 +27,11 @@ NEW_ENTRIES = { @pytest.fixture(scope="module") def model_data(): - json_path = os.path.join( - os.path.dirname(__file__), "../../model_prices_and_context_window.json" - ) + json_path = os.path.join(os.path.dirname(__file__), "../../model_prices_and_context_window.json") with open(json_path) as f: return json.load(f) -def test_bare_fireworks_ids_resolve_through_prefixed_entries(): - """Bare IDs from #37274 resolve via the provider-prefix lookup path.""" - for bare_id, prefixed_key in [ - ( - "accounts/fireworks/models/deepseek-v4-pro-0813", - "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813", - ), - ]: - info = get_model_info(model=bare_id, custom_llm_provider="fireworks_ai") - expected = NEW_ENTRIES[prefixed_key] - assert info.get("key") == prefixed_key - assert info["litellm_provider"] == "fireworks_ai" - assert info["input_cost_per_token"] == pytest.approx(expected["input_cost_per_token"]) - assert info["cache_read_input_token_cost"] == pytest.approx(expected["cache_read_input_token_cost"]) - assert info["output_cost_per_token"] == pytest.approx(expected["output_cost_per_token"]) - assert info["max_input_tokens"] == expected["max_input_tokens"] - assert info["max_output_tokens"] == expected["max_output_tokens"] - - -def test_deepseek_v4p1_flash_twin_costs(local_model_cost_map): - for model in ( - "fireworks_ai/deepseek-v4p1-flash", - "fireworks_ai/accounts/fireworks/models/deepseek-v4p1-flash", - ): - response = ModelResponse( - model=model, - choices=[Choices(index=0, message=Message(role="assistant", content="ok"))], - usage=Usage(prompt_tokens=1000, completion_tokens=1000, total_tokens=2000), - ) - cost = completion_cost(completion_response=response, model=model) - assert cost == pytest.approx(8.8e-04) - - TWIN_PINNED_PRICES = { "deepseek-v4-flash-0731": { "input_cost_per_token": 2.2e-07, @@ -95,7 +55,7 @@ def test_fireworks_account_prefixed_twins_agree_on_price(model_data): for key, entry in model_data.items(): if not key.startswith(prefix): continue - bare_key = f"fireworks_ai/{key[len(prefix):]}" + bare_key = f"fireworks_ai/{key[len(prefix) :]}" bare_entry = model_data.get(bare_key) if bare_entry is None: continue diff --git a/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py b/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py index 9c3ed8b0f35..fd5dcc88e9f 100644 --- a/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py +++ b/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py @@ -4,25 +4,12 @@ from pathlib import Path import pytest import litellm -from litellm import completion_cost -from litellm.cost_calculator import cost_per_token from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider -from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token -from litellm.llms.gemini.image_generation.cost_calculator import ( - cost_calculator as gemini_image_generation_cost_calculator, -) -from litellm.llms.vertex_ai.image_generation.cost_calculator import ( - cost_calculator as vertex_image_generation_cost_calculator, -) from litellm.types.utils import ( - CompletionTokensDetailsWrapper, ImageObject, ImageResponse, ImageUsage, ImageUsageInputTokensDetails, - ModelResponse, - PromptTokensDetailsWrapper, - Usage, ) REPO_ROOT = Path(__file__).parents[2] @@ -122,16 +109,6 @@ def test_per_route_capabilities_match_model_cards(model: str, path: Path): assert info[field] == value, f"{model} {field} in {path.name}: {info.get(field)} != {value}" -@pytest.mark.parametrize("model", ALL_KEYS) -def test_backup_matches_main(model: str): - assert _load(BACKUP_PATH).get(model) == _load(MAIN_PATH).get(model) - - -def test_one_k_image_price_matches_official_token_math(): - assert TOKENS_PER_1K_IMAGE * OUTPUT_IMAGE_TOKEN_COST == pytest.approx(OUTPUT_COST_PER_1K_IMAGE) - assert TOKENS_PER_1K_IMAGE * INPUT_COST == pytest.approx(INPUT_COST_PER_IMAGE) - - def test_gemini_prefix_routes_to_gemini(): routed_model, provider, _, _ = get_llm_provider(model=GEMINI) assert routed_model == UNPREFIXED @@ -144,78 +121,6 @@ def test_vertex_prefix_routes_to_vertex(): assert provider == "vertex_ai" -def test_get_model_info_reports_published_costs(local_model_cost_map): - info = litellm.get_model_info(UNPREFIXED) - assert info["input_cost_per_token"] == INPUT_COST - assert info["output_cost_per_token"] == OUTPUT_TEXT_COST - assert info["cache_read_input_token_cost"] == CACHE_READ_COST - - -@pytest.mark.parametrize("model", ALL_KEYS) -def test_reasoning_params_are_not_offered_on_an_image_endpoint(model: str, local_model_cost_map): - assert litellm.supports_reasoning(model) is False - - -def test_text_token_cost(local_model_cost_map): - prompt_cost, text_completion_cost = cost_per_token( - model=GEMINI, prompt_tokens=1000, completion_tokens=500 - ) - assert prompt_cost == pytest.approx(1000 * INPUT_COST) - assert text_completion_cost == pytest.approx(500 * OUTPUT_TEXT_COST) - - -def test_completion_cost_bills_one_k_image(local_model_cost_map): - response = ModelResponse() - response.model = UNPREFIXED - response.usage = Usage( - prompt_tokens=7, - completion_tokens=TOKENS_PER_1K_IMAGE, - total_tokens=7 + TOKENS_PER_1K_IMAGE, - completion_tokens_details=CompletionTokensDetailsWrapper( - image_tokens=TOKENS_PER_1K_IMAGE, text_tokens=0 - ), - ) - billed = completion_cost( - completion_response=response, - model=UNPREFIXED, - custom_llm_provider="vertex_ai", - ) - expected = TOKENS_PER_1K_IMAGE * OUTPUT_IMAGE_TOKEN_COST + 7 * INPUT_COST - assert billed == pytest.approx(expected) - - -def test_image_tokens_are_not_billed_as_text(local_model_cost_map): - usage = Usage( - completion_tokens=1345, - prompt_tokens=10, - total_tokens=1355, - completion_tokens_details=CompletionTokensDetailsWrapper( - accepted_prediction_tokens=None, - audio_tokens=None, - reasoning_tokens=225, - rejected_prediction_tokens=None, - text_tokens=0, - image_tokens=TOKENS_PER_1K_IMAGE, - ), - prompt_tokens_details=PromptTokensDetailsWrapper( - audio_tokens=None, cached_tokens=None, text_tokens=10, image_tokens=None - ), - ) - - _, image_completion_cost = generic_cost_per_token( - model=UNPREFIXED, - usage=usage, - custom_llm_provider="vertex_ai", - ) - - expected_completion_cost = ( - TOKENS_PER_1K_IMAGE * OUTPUT_IMAGE_TOKEN_COST + 225 * OUTPUT_TEXT_COST - ) - bugged_text_only_cost = 1345 * OUTPUT_TEXT_COST - assert image_completion_cost > bugged_text_only_cost * 2 - assert image_completion_cost == pytest.approx(expected_completion_cost) - - def _one_k_image_response() -> ImageResponse: return ImageResponse( data=[ImageObject(b64_json="img1")], @@ -229,34 +134,3 @@ def _one_k_image_response() -> ImageResponse: total_tokens=50 + TOKENS_PER_1K_IMAGE + TOKENS_PER_1K_IMAGE, ), ) - - -def test_gemini_image_generation_uses_token_pricing(local_model_cost_map): - cost = gemini_image_generation_cost_calculator( - model=GEMINI, image_response=_one_k_image_response() - ) - expected = ( - 50 + TOKENS_PER_1K_IMAGE - ) * INPUT_COST + TOKENS_PER_1K_IMAGE * OUTPUT_IMAGE_TOKEN_COST - assert cost == pytest.approx(expected) - assert cost != OUTPUT_COST_PER_1K_IMAGE - - -def test_vertex_image_generation_uses_token_pricing(local_model_cost_map): - cost = vertex_image_generation_cost_calculator( - model=UNPREFIXED, image_response=_one_k_image_response() - ) - expected = ( - 50 + TOKENS_PER_1K_IMAGE - ) * INPUT_COST + TOKENS_PER_1K_IMAGE * OUTPUT_IMAGE_TOKEN_COST - assert cost == pytest.approx(expected) - - -def test_vertex_image_generation_falls_back_to_flat_image_price(local_model_cost_map): - image_response = ImageResponse( - data=[ImageObject(b64_json="img1"), ImageObject(b64_json="img2")] - ) - cost = vertex_image_generation_cost_calculator( - model=UNPREFIXED, image_response=image_response - ) - assert cost == pytest.approx(2 * OUTPUT_COST_PER_1K_IMAGE) diff --git a/tests/test_litellm/test_gemini_tts_native_audio_pricing.py b/tests/test_litellm/test_gemini_tts_native_audio_pricing.py deleted file mode 100644 index 5578ed0cd3e..00000000000 --- a/tests/test_litellm/test_gemini_tts_native_audio_pricing.py +++ /dev/null @@ -1,135 +0,0 @@ -import json -from collections.abc import Iterator -from pathlib import Path -from typing import Final - -import pytest - -import litellm -from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token -from litellm.types.utils import CompletionTokensDetailsWrapper, PromptTokensDetailsWrapper, Usage - -REPO_ROOT: Final = Path(__file__).parents[2] -MAIN_PATH: Final = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PATH: Final = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -FLASH_TTS_KEYS: Final = ("gemini-2.5-flash-preview-tts", "gemini/gemini-2.5-flash-preview-tts") -PRO_TTS_KEYS: Final = ("gemini-2.5-pro-preview-tts", "gemini/gemini-2.5-pro-preview-tts") -NATIVE_AUDIO_KEYS: Final = tuple( - f"{prefix}gemini-2.5-flash-native-audio-{suffix}" - for prefix in ("", "gemini/") - for suffix in ("latest", "preview-09-2025", "preview-12-2025") -) - -LIVE_NATIVE_AUDIO_KEYS: Final = ( - "gemini-live-2.5-flash-preview-native-audio-09-2025", - "gemini/gemini-live-2.5-flash-preview-native-audio-09-2025", -) - -FLASH_TTS_INPUT: Final = 5e-07 -FLASH_TTS_AUDIO_OUTPUT: Final = 1e-05 -PRO_TTS_INPUT: Final = 1e-06 -PRO_TTS_AUDIO_OUTPUT: Final = 2e-05 -NATIVE_AUDIO_TEXT_INPUT: Final = 5e-07 -NATIVE_AUDIO_AUDIO_INPUT: Final = 3e-06 -NATIVE_AUDIO_TEXT_OUTPUT: Final = 2e-06 -NATIVE_AUDIO_AUDIO_OUTPUT: Final = 1.2e-05 - -PUBLISHED_RATES: Final = { - **{ - key: {"input_cost_per_token": FLASH_TTS_INPUT, "output_cost_per_token": FLASH_TTS_AUDIO_OUTPUT} - for key in FLASH_TTS_KEYS - }, - **{ - key: {"input_cost_per_token": PRO_TTS_INPUT, "output_cost_per_token": PRO_TTS_AUDIO_OUTPUT} - for key in PRO_TTS_KEYS - }, - **{ - key: { - "input_cost_per_token": NATIVE_AUDIO_TEXT_INPUT, - "input_cost_per_audio_token": NATIVE_AUDIO_AUDIO_INPUT, - "output_cost_per_token": NATIVE_AUDIO_TEXT_OUTPUT, - "output_cost_per_audio_token": NATIVE_AUDIO_AUDIO_OUTPUT, - } - for key in (*NATIVE_AUDIO_KEYS, *LIVE_NATIVE_AUDIO_KEYS) - }, -} -ALL_KEYS: Final = tuple(PUBLISHED_RATES) -NATIVE_AUDIO_BILLING_CASES: Final = ( - *((key, "gemini") for key in NATIVE_AUDIO_KEYS), - ("gemini-live-2.5-flash-preview-native-audio-09-2025", "vertex_ai"), - ("gemini/gemini-live-2.5-flash-preview-native-audio-09-2025", "gemini"), -) -LONG_CONTEXT_TIER_FIELDS: Final = ( - "input_cost_per_token_above_200k_tokens", - "output_cost_per_token_above_200k_tokens", - "cache_read_input_token_cost_above_200k_tokens", -) - - -def _load(path: Path) -> dict[str, dict[str, object]]: - with open(path, encoding="utf-8") as f: - return json.load(f) - - -@pytest.fixture -def local_model_cost_map(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) - litellm.get_model_info.cache_clear() - yield - litellm.get_model_info.cache_clear() - - -@pytest.mark.parametrize("model", ALL_KEYS) -def test_backup_matches_main(model: str): - assert _load(BACKUP_PATH)[model] == _load(MAIN_PATH)[model] - - -@pytest.mark.parametrize( - ("model", "provider", "input_rate", "audio_output_rate"), - ( - ("gemini-2.5-flash-preview-tts", "gemini", FLASH_TTS_INPUT, FLASH_TTS_AUDIO_OUTPUT), - ("gemini-2.5-pro-preview-tts", "gemini", PRO_TTS_INPUT, PRO_TTS_AUDIO_OUTPUT), - ("gemini-2.5-pro-preview-tts", "vertex_ai", PRO_TTS_INPUT, PRO_TTS_AUDIO_OUTPUT), - ), -) -def test_tts_audio_output_is_billed_at_the_audio_rate( - model: str, provider: str, input_rate: float, audio_output_rate: float, local_model_cost_map -): - usage: Final = Usage( - prompt_tokens=9, - completion_tokens=49, - total_tokens=58, - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=9), - completion_tokens_details=CompletionTokensDetailsWrapper(audio_tokens=49, text_tokens=0), - ) - prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider=provider) - assert prompt_cost == pytest.approx(9 * input_rate) - assert completion_cost == pytest.approx(49 * audio_output_rate) - - -@pytest.mark.parametrize("model, provider", NATIVE_AUDIO_BILLING_CASES) -def test_native_audio_output_is_billed_at_the_audio_rate(model: str, provider: str, local_model_cost_map): - usage: Final = Usage( - prompt_tokens=377, - completion_tokens=84, - total_tokens=461, - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=377), - completion_tokens_details=CompletionTokensDetailsWrapper(audio_tokens=48, reasoning_tokens=36, text_tokens=0), - ) - prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider=provider) - assert prompt_cost == pytest.approx(377 * NATIVE_AUDIO_TEXT_INPUT) - assert completion_cost == pytest.approx(48 * NATIVE_AUDIO_AUDIO_OUTPUT + 36 * NATIVE_AUDIO_TEXT_OUTPUT) - - -@pytest.mark.parametrize("model, provider", NATIVE_AUDIO_BILLING_CASES) -def test_native_audio_input_is_billed_at_the_audio_rate(model: str, provider: str, local_model_cost_map): - usage: Final = Usage( - prompt_tokens=1000, - completion_tokens=0, - total_tokens=1000, - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=100, audio_tokens=900), - ) - prompt_cost, _ = generic_cost_per_token(model=model, usage=usage, custom_llm_provider=provider) - assert prompt_cost == pytest.approx(100 * NATIVE_AUDIO_TEXT_INPUT + 900 * NATIVE_AUDIO_AUDIO_INPUT) diff --git a/tests/test_litellm/test_gpt_5_4_model_metadata.py b/tests/test_litellm/test_gpt_5_4_model_metadata.py deleted file mode 100644 index 294d0757069..00000000000 --- a/tests/test_litellm/test_gpt_5_4_model_metadata.py +++ /dev/null @@ -1,44 +0,0 @@ -import json -from functools import lru_cache -from pathlib import Path - -import pytest - -REPO_ROOT = Path(__file__).parents[2] -MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -DOCUMENTED_MAX_INPUT_TOKENS = 272000 -DOCUMENTED_MAX_OUTPUT_TOKENS = 128000 - -SMALL_MODEL_NAMES = ( - "gpt-5.4-mini", - "gpt-5.4-mini-2026-03-17", - "gpt-5.4-nano", - "gpt-5.4-nano-2026-03-17", -) -SMALL_MODELS = tuple(f"{prefix}{name}" for prefix in ("", "azure/", "azure_ai/") for name in SMALL_MODEL_NAMES) - -STANDARD_PRICING = { - "gpt-5.4-mini": (7.5e-07, 4.5e-06, 7.5e-08), - "gpt-5.4-nano": (2e-07, 1.25e-06, 2e-08), -} - -LONG_CONTEXT_MODELS = ("gpt-5.4", "gpt-5.4-pro") - - -@lru_cache(maxsize=2) -def _load(path: Path) -> dict[str, dict[str, object]]: - with open(path) as f: - return json.load(f) - - -def _pricing_key(model: str) -> str: - return "gpt-5.4-nano" if "nano" in model else "gpt-5.4-mini" - - -@pytest.mark.parametrize("model", SMALL_MODELS) -def test_gpt_5_4_small_models_backup_matches_main(model: str) -> None: - assert _load(BACKUP_PATH).get(model) == _load(MAIN_PATH).get(model), ( - f"{model} differs between main and backup model cost maps" - ) diff --git a/tests/test_litellm/test_gpt_5_5_model_metadata.py b/tests/test_litellm/test_gpt_5_5_model_metadata.py deleted file mode 100644 index e07efbcc913..00000000000 --- a/tests/test_litellm/test_gpt_5_5_model_metadata.py +++ /dev/null @@ -1,19 +0,0 @@ -import json -from pathlib import Path - - -def test_azure_ai_gpt_5_5_backup_matches_main(): - """Ensure the bundled model cost map stays in sync with the canonical file.""" - repo_root = Path(__file__).parents[2] - main_path = repo_root / "model_prices_and_context_window.json" - backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" - - with open(main_path) as f: - main_cost = json.load(f) - with open(backup_path) as f: - backup_cost = json.load(f) - - for model in ("azure_ai/gpt-5.5", "azure_ai/gpt-5.5-2026-04-23"): - assert backup_cost.get(model) == main_cost.get( - model - ), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_gpt_image_cost_calculator.py b/tests/test_litellm/test_gpt_image_cost_calculator.py index 86a721f8743..42d4c699200 100644 --- a/tests/test_litellm/test_gpt_image_cost_calculator.py +++ b/tests/test_litellm/test_gpt_image_cost_calculator.py @@ -10,19 +10,12 @@ gpt-image-1 uses token-based pricing: - Image Output: $40.00/1M tokens """ - - import pytest import litellm from litellm.types.utils import ( - CompletionTokensDetailsWrapper, - ImageResponse, ImageObject, - ImageUsage, - ImageUsageInputTokensDetails, - PromptTokensDetailsWrapper, - Usage, + ImageResponse, ) @@ -42,106 +35,6 @@ def _use_local_model_cost_map(monkeypatch): class TestGPTImageCostCalculator: """Test the OpenAI gpt-image cost calculator""" - def test_gpt_image_1_cost_with_text_only(self): - """Test cost calculation with only text input tokens""" - from litellm.llms.openai.image_generation.cost_calculator import cost_calculator - - usage = ImageUsage( - input_tokens=100, - output_tokens=5000, - total_tokens=5100, - input_tokens_details=ImageUsageInputTokensDetails( - text_tokens=100, - image_tokens=0, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(url="http://example.com/image.jpg")], - ) - image_response.usage = usage - - cost = cost_calculator( - model="gpt-image-1", - image_response=image_response, - custom_llm_provider="openai", - ) - - # Expected cost: - # Text input: 100 * $5/1M = 0.0005 - # Image output: 5000 * $40/1M = 0.2 - # Total: 0.2005 - expected_cost = 0.0005 + 0.2 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - - def test_gpt_image_1_cost_with_image_input(self): - """Test cost calculation with both text and image input tokens (for edits)""" - from litellm.llms.openai.image_generation.cost_calculator import cost_calculator - - usage = ImageUsage( - input_tokens=600, - output_tokens=5000, - total_tokens=5600, - input_tokens_details=ImageUsageInputTokensDetails( - text_tokens=100, - image_tokens=500, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(url="http://example.com/image.jpg")], - ) - image_response.usage = usage - - cost = cost_calculator( - model="gpt-image-1", - image_response=image_response, - custom_llm_provider="openai", - ) - - # Expected cost: - # Text input: 100 * $5/1M = 0.0005 - # Image input: 500 * $10/1M = 0.005 - # Image output: 5000 * $40/1M = 0.2 - # Total: 0.2055 - expected_cost = 0.0005 + 0.005 + 0.2 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - - def test_gpt_image_1_mini_cost(self): - """Test cost calculation for gpt-image-1-mini model""" - from litellm.llms.openai.image_generation.cost_calculator import cost_calculator - - usage = ImageUsage( - input_tokens=100, - output_tokens=5000, - total_tokens=5100, - input_tokens_details=ImageUsageInputTokensDetails( - text_tokens=100, - image_tokens=0, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(url="http://example.com/image.jpg")], - ) - image_response.usage = usage - - cost = cost_calculator( - model="gpt-image-1-mini", - image_response=image_response, - custom_llm_provider="openai", - ) - - # Expected cost for gpt-image-1-mini: - # Text input: 100 * $2/1M = 0.0002 - # Image output: 5000 * $8/1M = 0.04 - # Total: 0.0402 - expected_cost = 0.0002 + 0.04 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - def test_gpt_image_1_cost_no_usage(self): """Test that cost returns 0 when no usage data is available""" from litellm.llms.openai.image_generation.cost_calculator import cost_calculator @@ -159,98 +52,10 @@ class TestGPTImageCostCalculator: assert cost == 0.0 - def test_gpt_image_2_cost_with_text_and_image_tokens(self): - """Test cost calculation for gpt-image-2 token pricing""" - from litellm.llms.openai.image_generation.cost_calculator import cost_calculator - - usage = Usage( - prompt_tokens=600, - completion_tokens=5000, - total_tokens=5600, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=100, - image_tokens=500, - ), - completion_tokens_details=CompletionTokensDetailsWrapper( - image_tokens=5000, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(url="http://example.com/image.jpg")], - ) - image_response.usage = usage - - cost = cost_calculator( - model="gpt-image-2", - image_response=image_response, - custom_llm_provider="openai", - ) - - expected_cost = 100 * 5e-6 + 500 * 8e-6 + 5000 * 3e-5 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - class TestGPTImageCostRouting: """Test that gpt-image models are properly routed to the token-based calculator""" - def test_openai_gpt_image_routes_to_token_calculator(self): - """Test that OpenAI gpt-image-1 routes to token-based calculator""" - from litellm.litellm_core_utils.llm_cost_calc.utils import CostCalculatorUtils - - usage = ImageUsage( - input_tokens=100, - output_tokens=5000, - total_tokens=5100, - input_tokens_details=ImageUsageInputTokensDetails( - text_tokens=100, - image_tokens=0, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(url="http://example.com/image.jpg")], - ) - image_response.usage = usage - - cost = CostCalculatorUtils.route_image_generation_cost_calculator( - model="gpt-image-1", - completion_response=image_response, - custom_llm_provider="openai", - ) - - expected_cost = 0.0005 + 0.2 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - - def test_openai_gpt_image_2_routes_to_token_calculator(self): - """Test that OpenAI gpt-image-2 routes to token-based calculator""" - from litellm.litellm_core_utils.llm_cost_calc.utils import CostCalculatorUtils - - usage = Usage( - prompt_tokens=100, - completion_tokens=5000, - total_tokens=5100, - prompt_tokens_details=PromptTokensDetailsWrapper(text_tokens=100), - completion_tokens_details=CompletionTokensDetailsWrapper(image_tokens=5000), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(url="http://example.com/image.jpg")], - ) - image_response.usage = usage - - cost = CostCalculatorUtils.route_image_generation_cost_calculator( - model="gpt-image-2", - completion_response=image_response, - custom_llm_provider="openai", - ) - - expected_cost = 0.0005 + 0.15 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - def test_openai_dalle_routes_to_pixel_calculator(self): """Test that OpenAI DALL-E still routes to pixel-based calculator""" from litellm.litellm_core_utils.llm_cost_calc.utils import CostCalculatorUtils @@ -283,94 +88,10 @@ class TestGPTImage15OutputImageTokens: and these must be correctly included in cost calculation. """ - def test_gpt_image_15_output_image_tokens_cost(self): - """ - Test that output image tokens are correctly included in cost calculation. - - This tests the fix for issue #19508 where output_tokens_details.image_tokens - were not being included in the cost calculation, causing costs to be - underreported (e.g., $0.046 instead of $0.14). - """ - # Simulate gpt-image-1.5 response with output_tokens_details - # This is what the API returns and what convert_to_image_response transforms - usage = Usage( - prompt_tokens=169, - completion_tokens=4599, - total_tokens=4768, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=169, - image_tokens=0, - ), - completion_tokens_details=CompletionTokensDetailsWrapper( - text_tokens=439, - image_tokens=4160, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(b64_json="test")], - ) - image_response.usage = usage - image_response._hidden_params = {"custom_llm_provider": "openai"} - - cost = litellm.completion_cost( - completion_response=image_response, - model="gpt-image-1.5", - call_type="image_generation", - custom_llm_provider="openai", - ) - - # gpt-image-1.5 pricing: - # - input_cost_per_token: 5e-06 ($5/1M for text input) - # - output_cost_per_token: 1e-05 ($10/1M for text output) - # - output_cost_per_image_token: 3.2e-05 ($32/1M for image output) - # - # Expected cost: - # Input text: 169 * $5/1M = $0.000845 - # Output text: 439 * $10/1M = $0.00439 - # Output image: 4160 * $32/1M = $0.13312 - # Total: $0.138355 - expected_cost = 169 * 5e-06 + 439 * 1e-05 + 4160 * 3.2e-05 - - assert abs(cost - expected_cost) < 1e-6, ( - f"Expected {expected_cost}, got {cost}. " - f"Image tokens may not be included in cost calculation." - ) - class TestCompletionCostIntegration: """Test the full completion_cost integration for gpt-image-1""" - def test_completion_cost_gpt_image_1(self): - """Test completion_cost correctly calculates gpt-image-1 costs""" - usage = ImageUsage( - input_tokens=100, - output_tokens=5000, - total_tokens=5100, - input_tokens_details=ImageUsageInputTokensDetails( - text_tokens=100, - image_tokens=0, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(url="http://example.com/image.jpg")], - ) - image_response.usage = usage - image_response._hidden_params = {"custom_llm_provider": "openai"} - - cost = litellm.completion_cost( - completion_response=image_response, - model="gpt-image-1", - call_type="image_generation", - custom_llm_provider="openai", - ) - - expected_cost = 0.0005 + 0.2 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - class TestGPTImage2OutputImageTokensNoBreakdown: """ @@ -383,77 +104,6 @@ class TestGPTImage2OutputImageTokensNoBreakdown: cost component. """ - def test_gpt_image_2_output_priced_as_image_when_no_breakdown(self): - from litellm.llms.openai.image_generation.cost_calculator import ( - cost_calculator, - ) - - # Mirrors a real gpt-image-2 /v1/images/edits response: input breakdown is - # present, but there is no usable output token breakdown. - usage = ImageUsage( - input_tokens=3987, - output_tokens=5488, - total_tokens=9475, - input_tokens_details=ImageUsageInputTokensDetails( - text_tokens=943, - image_tokens=3044, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(b64_json="test")], - ) - image_response.usage = usage - image_response._hidden_params = {"custom_llm_provider": "openai"} - - cost = cost_calculator( - model="gpt-image-2", - image_response=image_response, - custom_llm_provider="openai", - ) - - # gpt-image-2 pricing: - # text input: 943 * $5/1M = 0.004715 - # image input: 3044 * $8/1M = 0.024352 - # image output: 5488 * $30/1M = 0.164640 (NOT text output $10/1M = 0.054880) - expected_cost = 943 * 5e-6 + 3044 * 8e-6 + 5488 * 3e-5 - assert abs(cost - expected_cost) < 1e-6, ( - f"Expected {expected_cost}, got {cost}. Generated image output tokens " - f"are likely being priced at the text output_cost_per_token rate." - ) - - def test_gpt_image_2_chat_usage_without_breakdown_uses_image_rate(self): - from litellm.llms.openai.image_generation.cost_calculator import ( - cost_calculator, - ) - - usage = Usage( - prompt_tokens=600, - completion_tokens=5000, - total_tokens=5600, - prompt_tokens_details=PromptTokensDetailsWrapper( - text_tokens=100, - image_tokens=500, - ), - ) - - image_response = ImageResponse( - created=1234567890, - data=[ImageObject(b64_json="test")], - ) - image_response.usage = usage - image_response._hidden_params = {"custom_llm_provider": "openai"} - - cost = cost_calculator( - model="gpt-image-2", - image_response=image_response, - custom_llm_provider="openai", - ) - - expected_cost = 100 * 5e-6 + 500 * 8e-6 + 5000 * 3e-5 - assert abs(cost - expected_cost) < 1e-6, f"Expected {expected_cost}, got {cost}" - if __name__ == "__main__": pytest.main([__file__, "-v"]) diff --git a/tests/test_litellm/test_gpt_realtime_mode.py b/tests/test_litellm/test_gpt_realtime_mode.py index 8c41e474486..778f620d72e 100644 --- a/tests/test_litellm/test_gpt_realtime_mode.py +++ b/tests/test_litellm/test_gpt_realtime_mode.py @@ -1,6 +1,3 @@ -import json -from pathlib import Path - from typing_extensions import get_args, get_type_hints from litellm.types.utils import ModelInfoBase @@ -44,13 +41,3 @@ ALL_REALTIME_ONLY_GPT_MODELS = REALTIME_ONLY_GPT_MODELS + REALTIME_ONLY_GPT_MODE def test_realtime_is_a_valid_mode_literal(): hints = get_type_hints(ModelInfoBase, include_extras=False) assert "realtime" in get_args(hints["mode"]) - - -def test_backup_matches_main_for_realtime_models(): - repo_root = Path(__file__).parents[2] - with open(repo_root / "model_prices_and_context_window.json") as f: - main_cost = json.load(f) - with open(repo_root / "litellm" / "model_prices_and_context_window_backup.json") as f: - backup_cost = json.load(f) - for model in ALL_REALTIME_ONLY_GPT_MODELS: - assert backup_cost.get(model) == main_cost.get(model) diff --git a/tests/test_litellm/test_mistral_medium_3_5_model_metadata.py b/tests/test_litellm/test_mistral_medium_3_5_model_metadata.py deleted file mode 100644 index d73311baae9..00000000000 --- a/tests/test_litellm/test_mistral_medium_3_5_model_metadata.py +++ /dev/null @@ -1,34 +0,0 @@ -import json -from pathlib import Path - -import pytest - - -REPO_ROOT = Path(__file__).parents[2] -MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -MEDIUM_3_5_MODELS = ( - "mistral/mistral-medium-3-5", - "mistral/mistral-medium-2604", - "mistral/mistral-medium-latest", -) - -SYNCED_MODELS = MEDIUM_3_5_MODELS + ( - "mistral/mistral-medium-2508", - "mistral/mistral-medium-3-1-2508", -) - - -def _load(path): - with open(path) as f: - return json.load(f) - - -@pytest.mark.parametrize("model", SYNCED_MODELS) -def test_backup_matches_main(model): - """Ensure the bundled (backup) cost map stays in sync with the canonical file.""" - main_cost = _load(MAIN_PATH) - backup_cost = _load(BACKUP_PATH) - - assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_mistral_small_4_0_model_metadata.py b/tests/test_litellm/test_mistral_small_4_0_model_metadata.py deleted file mode 100644 index 182c444bac9..00000000000 --- a/tests/test_litellm/test_mistral_small_4_0_model_metadata.py +++ /dev/null @@ -1,26 +0,0 @@ -import json -from pathlib import Path - -import pytest - -REPO_ROOT = Path(__file__).parents[2] -MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -SMALL_4_0_MODELS = ( - "mistral/mistral-small-latest", - "mistral/mistral-small-2603", -) - - -def _load(path): - with open(path) as f: - return json.load(f) - - -@pytest.mark.parametrize("model", SMALL_4_0_MODELS) -def test_backup_matches_main(model): - main_cost = _load(MAIN_PATH) - backup_cost = _load(BACKUP_PATH) - - assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py b/tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py deleted file mode 100644 index 29576eb0119..00000000000 --- a/tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py +++ /dev/null @@ -1,74 +0,0 @@ -import json -from pathlib import Path - -import pytest - -import litellm -from litellm.types.utils import PromptTokensDetailsWrapper, Usage -from litellm.utils import supports_prompt_caching, supports_reasoning - -REPO_ROOT = Path(__file__).parents[2] -MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -GLM_5_2_MODELS = ("mistral/zai-glm-5-2", "mistral/glm-5-2") - -INPUT_COST = 1.4e-06 -CACHED_INPUT_COST = 1.4e-07 -OUTPUT_COST = 4.4e-06 - - -def _load(path): - with open(path) as f: - return json.load(f) - - -@pytest.fixture -def local_model_cost_map(monkeypatch): - """Force get_model_info to resolve against the in-repo cost map instead of the - remote one fetched at import time, which still carries the pre-merge pricing.""" - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) - litellm.get_model_info.cache_clear() - yield - litellm.get_model_info.cache_clear() - - -@pytest.mark.parametrize("model", GLM_5_2_MODELS) -def test_zai_glm_5_2_capabilities_are_visible_to_callers(local_model_cost_map, model): - """Mistral advertises reasoning and prompt caching on this model, so the helpers - every caller checks before sending a request must say so too.""" - assert supports_reasoning(model=model) is True - assert supports_prompt_caching(model=model) is True - - info = litellm.get_model_info(model=model) - assert info["max_input_tokens"] == 1048576 - assert info["max_output_tokens"] == 131072 - - -@pytest.mark.parametrize("model", GLM_5_2_MODELS) -def test_cached_prompt_tokens_bill_at_the_cached_rate(local_model_cost_map, model): - """A cache hit reports its reused tokens under prompt_tokens_details, and those - tokens cost a tenth of the input rate, not the full rate and not nothing.""" - usage = Usage( - prompt_tokens=21010, - completion_tokens=100, - total_tokens=21110, - prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=20992), - ) - - prompt_cost, completion_cost = litellm.cost_per_token( - model=model, usage_object=usage, custom_llm_provider="mistral" - ) - - assert prompt_cost == pytest.approx(18 * INPUT_COST + 20992 * CACHED_INPUT_COST) - assert completion_cost == pytest.approx(100 * OUTPUT_COST) - - -@pytest.mark.parametrize("model", GLM_5_2_MODELS) -def test_backup_matches_main(model): - """Ensure the bundled (backup) cost map stays in sync with the canonical file.""" - main_cost = _load(MAIN_PATH) - backup_cost = _load(BACKUP_PATH) - - assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_muse_spark_1_1_model_metadata.py b/tests/test_litellm/test_muse_spark_1_1_model_metadata.py deleted file mode 100644 index f55266a78d7..00000000000 --- a/tests/test_litellm/test_muse_spark_1_1_model_metadata.py +++ /dev/null @@ -1,29 +0,0 @@ -import json -from pathlib import Path - -from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider - -MUSE_SPARK_MODEL = "meta/muse-spark-1.1" - - -def test_muse_spark_1_1_model_info(): - routed_model, provider, _, api_base = get_llm_provider(model=MUSE_SPARK_MODEL, api_key="sk-test") - assert routed_model == "muse-spark-1.1" - assert provider == "meta" - assert api_base == "https://api.meta.ai/v1" - - -def test_muse_spark_1_1_backup_matches_main(): - """Ensure the bundled model cost map stays in sync with the canonical file.""" - repo_root = Path(__file__).parents[2] - main_path = repo_root / "model_prices_and_context_window.json" - backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" - - with open(main_path) as f: - main_cost = json.load(f) - with open(backup_path) as f: - backup_cost = json.load(f) - - assert backup_cost.get(MUSE_SPARK_MODEL) == main_cost.get(MUSE_SPARK_MODEL), ( - f"{MUSE_SPARK_MODEL} differs between main and backup model cost maps" - ) diff --git a/tests/test_litellm/test_muse_spark_1_2_model_metadata.py b/tests/test_litellm/test_muse_spark_1_2_model_metadata.py index 02527a98711..4cc69d9f66d 100644 --- a/tests/test_litellm/test_muse_spark_1_2_model_metadata.py +++ b/tests/test_litellm/test_muse_spark_1_2_model_metadata.py @@ -3,10 +3,7 @@ from pathlib import Path import pytest -import litellm -from litellm.cost_calculator import cost_per_token from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider -from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import StandardBuiltInToolCostTracking MUSE_SPARK_STANDARD = "meta/muse-spark-1.2" MUSE_SPARK_CONTRIBUTOR = "meta/muse-spark-1.2-contributor" @@ -23,16 +20,6 @@ def _load_cost_map(filename: str = "model_prices_and_context_window.json") -> di return json.load(f) -@pytest.mark.parametrize("model, input_cost, cached_cost, output_cost", PRICING) -def test_muse_spark_1_2_cost_per_token( - local_model_cost_map, model: str, input_cost: float, cached_cost: float, output_cost: float -): - prompt_cost, completion_cost = cost_per_token(model=model, prompt_tokens=1000, completion_tokens=500) - - assert prompt_cost == pytest.approx(1000 * input_cost) - assert completion_cost == pytest.approx(500 * output_cost) - - @pytest.mark.parametrize("model", (MUSE_SPARK_STANDARD, MUSE_SPARK_CONTRIBUTOR)) def test_muse_spark_1_2_routes_to_meta_model_api(model: str): routed_model, provider, _, api_base = get_llm_provider(model=model, api_key="sk-test") @@ -42,22 +29,6 @@ def test_muse_spark_1_2_routes_to_meta_model_api(model: str): assert api_base == "https://api.meta.ai/v1" -@pytest.mark.parametrize("model", (MUSE_SPARK_STANDARD, MUSE_SPARK_CONTRIBUTOR)) -def test_muse_spark_1_2_web_search_cost_per_query(local_model_cost_map, model: str): - info = litellm.get_model_info(model=model) - - assert StandardBuiltInToolCostTracking.get_cost_for_web_search(model_info=info) == WEB_SEARCH_COST_PER_QUERY - - -@pytest.mark.parametrize("model", (MUSE_SPARK_STANDARD, MUSE_SPARK_CONTRIBUTOR)) -def test_muse_spark_1_2_backup_matches_main(model: str): - """Ensure the bundled model cost map stays in sync with the canonical file.""" - main_cost = _load_cost_map() - backup_cost = _load_cost_map("litellm/model_prices_and_context_window_backup.json") - - assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" - - def test_muse_spark_contributor_tier_is_cheaper_than_standard(): cost_map = _load_cost_map() standard = cost_map[MUSE_SPARK_STANDARD] diff --git a/tests/test_litellm/test_muse_spark_1_3_model_metadata.py b/tests/test_litellm/test_muse_spark_1_3_model_metadata.py index 92b099fc780..097dbc2923d 100644 --- a/tests/test_litellm/test_muse_spark_1_3_model_metadata.py +++ b/tests/test_litellm/test_muse_spark_1_3_model_metadata.py @@ -4,7 +4,6 @@ from pathlib import Path import pytest import litellm -from litellm.cost_calculator import cost_per_token from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import StandardBuiltInToolCostTracking @@ -23,16 +22,6 @@ def _load_cost_map(filename: str = "model_prices_and_context_window.json") -> di return json.load(f) -@pytest.mark.parametrize("model, input_cost, cached_cost, output_cost", PRICING) -def test_muse_spark_1_3_cost_per_token( - local_model_cost_map, model: str, input_cost: float, cached_cost: float, output_cost: float -): - prompt_cost, completion_cost = cost_per_token(model=model, prompt_tokens=1000, completion_tokens=500) - - assert prompt_cost == pytest.approx(1000 * input_cost) - assert completion_cost == pytest.approx(500 * output_cost) - - @pytest.mark.parametrize("model", (MUSE_SPARK_STANDARD, MUSE_SPARK_CONTRIBUTOR)) def test_muse_spark_1_3_routes_to_meta_model_api(model: str): routed_model, provider, _, api_base = get_llm_provider(model=model, api_key="sk-test") @@ -49,15 +38,6 @@ def test_muse_spark_1_3_web_search_cost_per_query(local_model_cost_map, model: s assert StandardBuiltInToolCostTracking.get_cost_for_web_search(model_info=info) == WEB_SEARCH_COST_PER_QUERY -@pytest.mark.parametrize("model", (MUSE_SPARK_STANDARD, MUSE_SPARK_CONTRIBUTOR)) -def test_muse_spark_1_3_backup_matches_main(model: str): - """Ensure the bundled model cost map stays in sync with the canonical file.""" - main_cost = _load_cost_map() - backup_cost = _load_cost_map("litellm/model_prices_and_context_window_backup.json") - - assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" - - def test_muse_spark_contributor_tier_is_cheaper_than_standard(): cost_map = _load_cost_map() standard = cost_map[MUSE_SPARK_STANDARD] diff --git a/tests/test_litellm/test_openai_service_tier_long_context_pricing.py b/tests/test_litellm/test_openai_service_tier_long_context_pricing.py index 8027d64d1ed..0cc564535ba 100644 --- a/tests/test_litellm/test_openai_service_tier_long_context_pricing.py +++ b/tests/test_litellm/test_openai_service_tier_long_context_pricing.py @@ -106,27 +106,3 @@ def test_cost_per_token_bills_long_context_at_the_tier_rate( ) assert input_cost == pytest.approx(LONG_CONTEXT_PROMPT_TOKENS * input_rate) assert output_cost == pytest.approx(COMPLETION_TOKENS * output_rate) - - -@pytest.mark.parametrize("model,tier,input_rate,output_rate", TIERED_COST_CASES) -def test_cost_per_token_tier_differs_from_the_standard_long_context_cost( - model: str, tier: str, input_rate: float, output_rate: float -) -> None: - """Flex halves the standard long-context bill and priority doubles it.""" - ratio = 0.5 if tier == "flex" else 2.0 - standard = sum( - litellm.cost_per_token( - model=model, - prompt_tokens=LONG_CONTEXT_PROMPT_TOKENS, - completion_tokens=COMPLETION_TOKENS, - ) - ) - tiered = sum( - litellm.cost_per_token( - model=model, - prompt_tokens=LONG_CONTEXT_PROMPT_TOKENS, - completion_tokens=COMPLETION_TOKENS, - service_tier=tier, - ) - ) - assert tiered == pytest.approx(standard * ratio) diff --git a/tests/test_litellm/test_replicate_model_key_format.py b/tests/test_litellm/test_replicate_model_key_format.py index 77ae5e1b069..39e9fa01d73 100644 --- a/tests/test_litellm/test_replicate_model_key_format.py +++ b/tests/test_litellm/test_replicate_model_key_format.py @@ -18,18 +18,3 @@ def test_replicate_models_have_valid_key_prefix(model_cost: dict[str, Any]) -> N assert not malformed, ( f"Replicate models must use 'replicate/owner/model' key format, found malformed keys: {malformed}" ) - - -def test_replicate_backup_matches_main() -> None: - repo_root = Path(__file__).parents[2] - main_path = repo_root / "model_prices_and_context_window.json" - backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" - - with open(main_path, encoding="utf-8") as f: - main_cost: dict[str, Any] = json.load(f) - with open(backup_path, encoding="utf-8") as f: - backup_cost: dict[str, Any] = json.load(f) - - for key in main_cost: - if main_cost[key].get("litellm_provider") == "replicate": - assert backup_cost.get(key) == main_cost.get(key), f"{key} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_sambanova_model_metadata.py b/tests/test_litellm/test_sambanova_model_metadata.py deleted file mode 100644 index 20f34f9f3cc..00000000000 --- a/tests/test_litellm/test_sambanova_model_metadata.py +++ /dev/null @@ -1,25 +0,0 @@ -import json -from pathlib import Path - -from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider - - -def test_sambanova_minimax_m27_model_info(): - model = "sambanova/MiniMax-M2.7" - json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" - with open(json_path) as f: - model_cost = json.load(f) - - info = model_cost.get(model) - assert info is not None, f"{model} not found in model_prices_and_context_window.json" - assert info["litellm_provider"] == "sambanova" - assert info["mode"] == "chat" - assert info["input_cost_per_token"] > 0 - assert info["output_cost_per_token"] > 0 - assert info["supports_function_calling"] is True - assert info["supports_reasoning"] is True - assert info["supports_tool_choice"] is True - - routed_model, provider, _, _ = get_llm_provider(model=model) - assert routed_model == "MiniMax-M2.7" - assert provider == "sambanova" diff --git a/tests/test_litellm/test_together_ai_model_metadata.py b/tests/test_litellm/test_together_ai_model_metadata.py index 99e93ae2865..851d0f0c9d8 100644 --- a/tests/test_litellm/test_together_ai_model_metadata.py +++ b/tests/test_litellm/test_together_ai_model_metadata.py @@ -5,7 +5,6 @@ from typing import Final import pytest from pydantic import TypeAdapter - REPO_ROOT: Final = Path(__file__).parents[2] CostMap = dict[str, dict[str, object]] @@ -109,14 +108,6 @@ def test_together_successor_metadata_points_at_live_models(cost_map: CostMap): assert "deprecation_date" not in target, f"{model} names deprecated successor {successor}" -def test_together_backup_cost_map_in_sync(cost_map: CostMap): - with open(REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json") as f: - backup = COST_MAP_ADAPTER.validate_python(json.load(f)) - together_main = {k: v for k, v in cost_map.items() if k.startswith("together_ai/")} - together_backup = {k: v for k, v in backup.items() if k.startswith("together_ai/")} - assert together_backup == together_main - - CACHED_INPUT_MODELS: Final = ( "together_ai/moonshotai/Kimi-K3", "together_ai/zai-org/GLM-5.2", diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index 02196a9cd26..bad531fdd51 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -6,9 +6,9 @@ import logging import os import queue import threading -from datetime import datetime, timedelta, timezone from collections.abc import Callable, Iterator from concurrent.futures import Future, ThreadPoolExecutor +from datetime import datetime, timedelta, timezone from typing import Final from unittest.mock import AsyncMock, MagicMock, patch @@ -17,10 +17,8 @@ import pytest import respx from jsonschema import validate - import litellm from litellm._internal_context import is_internal_call -from litellm.constants import DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT from litellm._logging import ( CorrelationContextFilter, JsonFormatter, @@ -28,10 +26,12 @@ from litellm._logging import ( trace_id_var, verbose_logger, ) +from litellm.constants import DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT from litellm.integrations.custom_logger import CustomLogger from litellm.litellm_core_utils.get_litellm_params import get_litellm_params from litellm.litellm_core_utils.thread_pool_executor import executor as logging_executor from litellm.proxy.utils import is_valid_api_key +from litellm.types.router import CredentialLiteLLMParams, GenericLiteLLMParams from litellm.types.utils import ( CallTypes, Delta, @@ -40,9 +40,9 @@ from litellm.types.utils import ( PromptTokensDetailsWrapper, StreamingChoices, Usage, + all_litellm_params, + bedrock_batch_litellm_params, ) -from litellm.types.utils import all_litellm_params, bedrock_batch_litellm_params -from litellm.types.router import CredentialLiteLLMParams, GenericLiteLLMParams from litellm.utils import ( ProviderConfigManager, TextCompletionStreamWrapper, @@ -53,7 +53,6 @@ from litellm.utils import ( async_post_call_failure_deployment_hook, async_post_call_success_deployment_hook, client, - get_llm_provider, get_non_default_completion_params, get_optional_params_image_gen, get_prompt_cache_min_tokens, @@ -154,36 +153,6 @@ def test_prompt_tokens_details_cache_write_creation_stay_in_sync_on_assignment() assert details.cache_write_tokens == details.cache_creation_tokens == 375 -def test_get_model_info_surfaces_supports_adaptive_thinking(local_model_cost_map): - """supports_adaptive_thinking must flow through get_model_info like every other - capability flag: both from an explicit cost-map entry and from a - fallback-generalization rule for an unmapped model. Regression: the field shipped - in the JSON but was never declared on ModelInfo nor copied during construction, so - get_model_info (and _supports_factory) silently dropped it for any provider-prefixed - or unmapped name.""" - explicit = litellm.get_model_info(model="claude-opus-4-8") - assert explicit["supports_adaptive_thinking"] is True - - generalized = litellm.get_model_info( - model="claude-opus-4-9", custom_llm_provider="anthropic" - ) - assert generalized["supports_adaptive_thinking"] is True - - -def test_get_model_info_surfaces_supports_parallel_function_calling(local_model_cost_map): - """A registry entry's supports_parallel_function_calling must read back through get_model_info - and litellm.supports_parallel_function_calling. Regression: the key was never copied into - ModelInfo, so provider-prefixed entries read None / False even when the map said True, and an - explicit False was indistinguishable from unset.""" - declared_true = litellm.get_model_info(model="together_ai/zai-org/GLM-5.3-Flash") - assert declared_true["supports_parallel_function_calling"] is True - assert litellm.supports_parallel_function_calling(model="together_ai/zai-org/GLM-5.3-Flash") is True - - declared_false = litellm.get_model_info(model="o3-mini") - assert declared_false["supports_parallel_function_calling"] is False - assert litellm.supports_parallel_function_calling(model="o3-mini") is False - - def test_get_model_info_surfaces_supported_endpoints(local_model_cost_map): """supported_endpoints ships in the cost map and is declared on ModelInfoBase, but the constructor never copied it, so get_model_info always returned None. @@ -198,9 +167,7 @@ def test_potential_model_names_keeps_provider_prefixed_candidate(): Agent API serves `perplexity/glm-5.2`, mapped as `perplexity/perplexity/glm-5.2`) needs the un-stripped `/` candidate. Every other candidate reads the leading `perplexity/` as the litellm prefix and strips it away.""" - already_prefixed = _get_potential_model_names( - model="perplexity/glm-5.2", custom_llm_provider="perplexity" - ) + already_prefixed = _get_potential_model_names(model="perplexity/glm-5.2", custom_llm_provider="perplexity") assert already_prefixed["provider_prefixed_model_name"] == "perplexity/perplexity/glm-5.2" assert already_prefixed["split_model"] == "glm-5.2" assert already_prefixed["combined_model_name"] == "perplexity/glm-5.2" @@ -210,104 +177,24 @@ def test_potential_model_names_keeps_provider_prefixed_candidate(): assert bare["provider_prefixed_model_name"] == bare["combined_model_name"] == "perplexity/glm-5.2" -def test_get_model_info_resolves_provider_prefixed_model_ids(local_model_cost_map): - """Perplexity's Agent API third-party models are keyed `perplexity/perplexity/` - because Perplexity's own id already starts with `perplexity/`. Callers run - `get_llm_provider` first, which hands `_get_potential_model_names` model - `perplexity/glm-5.2` with provider `perplexity`, and every candidate but the - provider-prefixed one strips that second `perplexity/` off. Regression: the - entries were unreachable from `supports_reasoning` and from the cost calculator's - per-token fallback, so a mapped model reported no reasoning support and raised - "This model isn't mapped yet" on the only path where its rates are ever used.""" - for model, reasoning in ( - ("perplexity/perplexity/glm-5.2", True), - ("perplexity/perplexity/kimi-k3", True), - ("perplexity/perplexity/deepseek-v4-flash-0731", True), - ("perplexity/perplexity/kimi-k2.7-code", False), - ("perplexity/perplexity/nemotron-3.5-lightning-30b-a3b", True), - ("perplexity/perplexity/nemotron-3-ultra-550b-a55b", True), - ): - assert litellm.supports_reasoning(model=model) is reasoning, model - - via_provider = litellm.get_model_info( - model="perplexity/glm-5.2", custom_llm_provider="perplexity" - ) - assert via_provider["key"] == "perplexity/perplexity/glm-5.2" - assert via_provider["input_cost_per_token"] == 1.4e-06 - assert via_provider["output_cost_per_token"] == 4.4e-06 - assert via_provider["mode"] == "responses" - - lightning = litellm.get_model_info( - model="perplexity/nemotron-3.5-lightning-30b-a3b", custom_llm_provider="perplexity" - ) - assert lightning["key"] == "perplexity/perplexity/nemotron-3.5-lightning-30b-a3b" - assert lightning["input_cost_per_token"] == 1.15e-08 - assert lightning["output_cost_per_token"] == 1.7e-07 - assert lightning["cache_read_input_token_cost"] == 1.15e-09 - assert lightning["mode"] == "responses" - - ultra = litellm.get_model_info(model="perplexity/perplexity/nemotron-3-ultra-550b-a55b") - assert ultra["key"] == "perplexity/perplexity/nemotron-3-ultra-550b-a55b" - - def test_get_model_info_strips_openai_finetune_ids_without_a_custom_suffix(local_model_cost_map): info = litellm.get_model_info(model="ft:gpt-4o-2024-08-06:my-org::abc123", custom_llm_provider="openai") assert info["key"] == "ft:gpt-4o-2024-08-06" -def test_provider_prefixed_lookup_never_outranks_an_existing_row(local_model_cost_map): - """The provider-prefixed candidate is tried last, after every candidate that - already existed, so no model that resolves today can change answer. `perplexity/sonar` - is the case that proves it: both `perplexity/sonar` and `perplexity/perplexity/sonar` - are cost-map keys, and the shorter one must keep winning.""" - sonar = litellm.get_model_info(model="sonar", custom_llm_provider="perplexity") - assert sonar["key"] == "perplexity/sonar" - assert sonar["mode"] == "chat" - assert sonar["input_cost_per_token"] == 1e-06 - - still_sonar = litellm.get_model_info( - model="perplexity/sonar", custom_llm_provider="perplexity" - ) - assert still_sonar["key"] == "perplexity/sonar" - assert still_sonar["mode"] == "chat" - - for model, provider, expected_key in ( - ("claude-sonnet-4-5", "anthropic", "claude-sonnet-4-5"), - ("anthropic/claude-sonnet-4-5", "anthropic", "claude-sonnet-4-5"), - ("gemini/gemini-2.0-flash", "gemini", "gemini/gemini-2.0-flash"), - ("openrouter/openai/gpt-4o", "openrouter", "openrouter/openai/gpt-4o"), - ): - assert litellm.get_model_info(model=model, custom_llm_provider=provider)["key"] == expected_key - - def test_check_provider_match_azure_ai_allows_openai_and_azure(): """ Test that azure_ai provider can match openai and azure models. This is needed for Azure Model Router which can route to OpenAI models. """ # azure_ai should match openai models - assert ( - _check_provider_match( - model_info={"litellm_provider": "openai"}, custom_llm_provider="azure_ai" - ) - is True - ) + assert _check_provider_match(model_info={"litellm_provider": "openai"}, custom_llm_provider="azure_ai") is True # azure_ai should match azure models - assert ( - _check_provider_match( - model_info={"litellm_provider": "azure"}, custom_llm_provider="azure_ai" - ) - is True - ) + assert _check_provider_match(model_info={"litellm_provider": "azure"}, custom_llm_provider="azure_ai") is True # azure_ai should NOT match other providers - assert ( - _check_provider_match( - model_info={"litellm_provider": "anthropic"}, custom_llm_provider="azure_ai" - ) - is False - ) + assert _check_provider_match(model_info={"litellm_provider": "anthropic"}, custom_llm_provider="azure_ai") is False def test_check_provider_match_github_allows_upstream_provider_metadata(): @@ -342,21 +229,11 @@ def test_check_provider_match_github_allows_upstream_provider_metadata(): def test_supports_function_calling_github_openai_alias(): assert litellm.utils.supports_function_calling(model="github/gpt-4o-mini") is True - assert ( - litellm.utils.supports_function_calling( - model="gpt-4o-mini", custom_llm_provider="github" - ) - is True - ) + assert litellm.utils.supports_function_calling(model="gpt-4o-mini", custom_llm_provider="github") is True def test_supports_function_calling_github_anthropic_alias(): - assert ( - litellm.utils.supports_function_calling( - model="github/claude-3-7-sonnet-20250219" - ) - is True - ) + assert litellm.utils.supports_function_calling(model="github/claude-3-7-sonnet-20250219") is True def test_supports_function_calling_deepinfra_llama(): @@ -364,21 +241,11 @@ def test_supports_function_calling_deepinfra_llama(): Regression test for https://github.com/BerriAI/litellm/issues/22619 """ - assert ( - litellm.utils.supports_function_calling( - model="deepinfra/meta-llama/Llama-3.3-70B-Instruct-Turbo" - ) - is True - ) + assert litellm.utils.supports_function_calling(model="deepinfra/meta-llama/Llama-3.3-70B-Instruct-Turbo") is True def test_supports_function_calling_unknown_github_alias_returns_false(): - assert ( - litellm.utils.supports_function_calling( - model="github/non-existent-model-for-capability-check" - ) - is False - ) + assert litellm.utils.supports_function_calling(model="github/non-existent-model-for-capability-check") is False def test_get_optional_params_image_gen(): @@ -462,9 +329,7 @@ def test_get_optional_params_image_gen_vertex_ai_size(): drop_params=True, ) assert optional_params is not None - assert ( - "aspectRatio" not in optional_params - ) # aspectRatio should not be set if size is not provided + assert "aspectRatio" not in optional_params # aspectRatio should not be set if size is not provided assert optional_params["sampleCount"] == 1 @@ -493,26 +358,19 @@ def test_all_model_configs(): VertexAILlama3Config, ) - assert ( - "max_completion_tokens" - in VertexAILlama3Config().get_supported_openai_params(model="llama3") - ) - assert VertexAILlama3Config().map_openai_params( - {"max_completion_tokens": 10}, {}, "llama3", drop_params=False - ) == {"max_tokens": 10} + assert "max_completion_tokens" in VertexAILlama3Config().get_supported_openai_params(model="llama3") + assert VertexAILlama3Config().map_openai_params({"max_completion_tokens": 10}, {}, "llama3", drop_params=False) == { + "max_tokens": 10 + } - assert "max_completion_tokens" in VertexAIAi21Config().get_supported_openai_params( - model="jamba-1.5-mini@001" - ) + assert "max_completion_tokens" in VertexAIAi21Config().get_supported_openai_params(model="jamba-1.5-mini@001") assert VertexAIAi21Config().map_openai_params( {"max_completion_tokens": 10}, {}, "jamba-1.5-mini@001", drop_params=False ) == {"max_tokens": 10} from litellm.llms.fireworks_ai.chat.transformation import FireworksAIConfig - assert "max_completion_tokens" in FireworksAIConfig().get_supported_openai_params( - model="llama3" - ) + assert "max_completion_tokens" in FireworksAIConfig().get_supported_openai_params(model="llama3") assert FireworksAIConfig().map_openai_params( model="llama3", non_default_params={"max_completion_tokens": 10}, @@ -522,9 +380,7 @@ def test_all_model_configs(): from litellm.llms.nvidia_nim.chat.transformation import NvidiaNimConfig - assert "max_completion_tokens" in NvidiaNimConfig().get_supported_openai_params( - model="llama3" - ) + assert "max_completion_tokens" in NvidiaNimConfig().get_supported_openai_params(model="llama3") assert NvidiaNimConfig().map_openai_params( model="llama3", non_default_params={"max_completion_tokens": 10}, @@ -534,9 +390,7 @@ def test_all_model_configs(): from litellm.llms.ollama.chat.transformation import OllamaChatConfig - assert "max_completion_tokens" in OllamaChatConfig().get_supported_openai_params( - model="llama3" - ) + assert "max_completion_tokens" in OllamaChatConfig().get_supported_openai_params(model="llama3") assert OllamaChatConfig().map_openai_params( model="llama3", non_default_params={"max_completion_tokens": 10}, @@ -546,9 +400,7 @@ def test_all_model_configs(): from litellm.llms.predibase.chat.transformation import PredibaseConfig - assert "max_completion_tokens" in PredibaseConfig().get_supported_openai_params( - model="llama3" - ) + assert "max_completion_tokens" in PredibaseConfig().get_supported_openai_params(model="llama3") assert PredibaseConfig().map_openai_params( model="llama3", non_default_params={"max_completion_tokens": 10}, @@ -560,10 +412,7 @@ def test_all_model_configs(): CodestralTextCompletionConfig, ) - assert ( - "max_completion_tokens" - in CodestralTextCompletionConfig().get_supported_openai_params(model="llama3") - ) + assert "max_completion_tokens" in CodestralTextCompletionConfig().get_supported_openai_params(model="llama3") assert CodestralTextCompletionConfig().map_openai_params( model="llama3", non_default_params={"max_completion_tokens": 10}, @@ -575,9 +424,7 @@ def test_all_model_configs(): VolcEngineChatConfig as VolcEngineConfig, ) - assert "max_completion_tokens" in VolcEngineConfig().get_supported_openai_params( - model="llama3" - ) + assert "max_completion_tokens" in VolcEngineConfig().get_supported_openai_params(model="llama3") assert VolcEngineConfig().map_openai_params( model="llama3", non_default_params={"max_completion_tokens": 10}, @@ -587,9 +434,7 @@ def test_all_model_configs(): from litellm.llms.ai21.chat.transformation import AI21ChatConfig - assert "max_completion_tokens" in AI21ChatConfig().get_supported_openai_params( - "jamba-1.5-mini@001" - ) + assert "max_completion_tokens" in AI21ChatConfig().get_supported_openai_params("jamba-1.5-mini@001") assert AI21ChatConfig().map_openai_params( model="jamba-1.5-mini@001", non_default_params={"max_completion_tokens": 10}, @@ -599,9 +444,7 @@ def test_all_model_configs(): from litellm.llms.azure.chat.gpt_transformation import AzureOpenAIConfig - assert "max_completion_tokens" in AzureOpenAIConfig().get_supported_openai_params( - model="gpt-3.5-turbo" - ) + assert "max_completion_tokens" in AzureOpenAIConfig().get_supported_openai_params(model="gpt-3.5-turbo") assert AzureOpenAIConfig().map_openai_params( model="gpt-3.5-turbo", non_default_params={"max_completion_tokens": 10}, @@ -612,11 +455,8 @@ def test_all_model_configs(): from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig - assert ( - "max_completion_tokens" - in AmazonConverseConfig().get_supported_openai_params( - model="anthropic.claude-3-sonnet-20240229-v1:0" - ) + assert "max_completion_tokens" in AmazonConverseConfig().get_supported_openai_params( + model="anthropic.claude-3-sonnet-20240229-v1:0" ) assert AmazonConverseConfig().map_openai_params( model="anthropic.claude-3-sonnet-20240229-v1:0", @@ -629,10 +469,7 @@ def test_all_model_configs(): CodestralTextCompletionConfig, ) - assert ( - "max_completion_tokens" - in CodestralTextCompletionConfig().get_supported_openai_params(model="llama3") - ) + assert "max_completion_tokens" in CodestralTextCompletionConfig().get_supported_openai_params(model="llama3") assert CodestralTextCompletionConfig().map_openai_params( model="llama3", non_default_params={"max_completion_tokens": 10}, @@ -642,11 +479,8 @@ def test_all_model_configs(): from litellm import AmazonAnthropicClaudeConfig, AmazonAnthropicConfig - assert ( - "max_completion_tokens" - in AmazonAnthropicClaudeConfig().get_supported_openai_params( - model="anthropic.claude-3-sonnet-20240229-v1:0" - ) + assert "max_completion_tokens" in AmazonAnthropicClaudeConfig().get_supported_openai_params( + model="anthropic.claude-3-sonnet-20240229-v1:0" ) assert AmazonAnthropicClaudeConfig().map_openai_params( @@ -656,10 +490,7 @@ def test_all_model_configs(): drop_params=False, ) == {"max_tokens": 10} - assert ( - "max_completion_tokens" - in AmazonAnthropicConfig().get_supported_openai_params(model="") - ) + assert "max_completion_tokens" in AmazonAnthropicConfig().get_supported_openai_params(model="") assert AmazonAnthropicConfig().map_openai_params( non_default_params={"max_completion_tokens": 10}, @@ -683,12 +514,7 @@ def test_all_model_configs(): VertexAIAnthropicConfig, ) - assert ( - "max_completion_tokens" - in VertexAIAnthropicConfig().get_supported_openai_params( - model="claude-sonnet-4-6" - ) - ) + assert "max_completion_tokens" in VertexAIAnthropicConfig().get_supported_openai_params(model="claude-sonnet-4-6") assert VertexAIAnthropicConfig().map_openai_params( non_default_params={"max_completion_tokens": 10}, @@ -702,9 +528,7 @@ def test_all_model_configs(): VertexGeminiConfig, ) - assert "max_completion_tokens" in VertexGeminiConfig().get_supported_openai_params( - model="gemini-1.0-pro" - ) + assert "max_completion_tokens" in VertexGeminiConfig().get_supported_openai_params(model="gemini-1.0-pro") assert VertexGeminiConfig().map_openai_params( model="gemini-1.0-pro", @@ -713,12 +537,7 @@ def test_all_model_configs(): drop_params=False, ) == {"max_output_tokens": 10} - assert ( - "max_completion_tokens" - in GoogleAIStudioGeminiConfig().get_supported_openai_params( - model="gemini-1.0-pro" - ) - ) + assert "max_completion_tokens" in GoogleAIStudioGeminiConfig().get_supported_openai_params(model="gemini-1.0-pro") assert GoogleAIStudioGeminiConfig().map_openai_params( model="gemini-1.0-pro", @@ -727,9 +546,7 @@ def test_all_model_configs(): drop_params=False, ) == {"max_output_tokens": 10} - assert "max_completion_tokens" in VertexGeminiConfig().get_supported_openai_params( - model="gemini-1.0-pro" - ) + assert "max_completion_tokens" in VertexGeminiConfig().get_supported_openai_params(model="gemini-1.0-pro") assert VertexGeminiConfig().map_openai_params( model="gemini-1.0-pro", @@ -752,12 +569,10 @@ def test_anthropic_web_search_in_model_info(monkeypatch): model_info = get_model_info(model) assert model_info is not None - assert ( - model_info["supports_web_search"] is True - ), f"Model {model} should support web search" - assert ( - model_info["search_context_cost_per_query"] is not None - ), f"Model {model} should have a search context cost per query" + assert model_info["supports_web_search"] is True, f"Model {model} should support web search" + assert model_info["search_context_cost_per_query"] is not None, ( + f"Model {model} should have a search context cost per query" + ) def test_cohere_embedding_optional_params(): @@ -867,9 +682,7 @@ def validate_model_cost_values(model_data, exceptions=None): continue if isinstance(cost_value, (int, float)) and cost_value > 1: - violations.append( - f"Model '{model_id}' has {field} = {cost_value} which exceeds 1" - ) + violations.append(f"Model '{model_id}' has {field} = {cost_value} which exceeds 1") # Check nested cost fields for field in nested_cost_fields: @@ -913,12 +726,8 @@ def test_aaamodel_prices_and_context_window_json_is_valid(): "cache_creation_input_token_cost_above_200k_tokens": {"type": "number"}, "cache_creation_input_token_cost_above_256k_tokens": {"type": "number"}, "cache_creation_input_token_cost_above_272k_tokens": {"type": "number"}, - "cache_creation_input_token_cost_above_272k_tokens_flex": { - "type": "number" - }, - "cache_creation_input_token_cost_above_272k_tokens_priority": { - "type": "number" - }, + "cache_creation_input_token_cost_above_272k_tokens_flex": {"type": "number"}, + "cache_creation_input_token_cost_above_272k_tokens_priority": {"type": "number"}, "cache_creation_input_token_cost_flex": {"type": "number"}, "cache_creation_input_token_cost_priority": {"type": "number"}, "cache_read_input_token_cost": {"type": "number"}, @@ -926,13 +735,9 @@ def test_aaamodel_prices_and_context_window_json_is_valid(): "cache_read_input_token_cost_above_200k_tokens": {"type": "number"}, "cache_read_input_token_cost_above_256k_tokens": {"type": "number"}, "cache_read_input_token_cost_above_272k_tokens": {"type": "number"}, - "cache_read_input_token_cost_above_272k_tokens_flex": { - "type": "number" - }, + "cache_read_input_token_cost_above_272k_tokens_flex": {"type": "number"}, "cache_read_input_token_cost_above_512k_tokens": {"type": "number"}, - "cache_creation_input_token_cost_above_1hr_above_200k_tokens": { - "type": "number" - }, + "cache_creation_input_token_cost_above_1hr_above_200k_tokens": {"type": "number"}, "cache_read_input_audio_token_cost": {"type": "number"}, "audio_transcription_config": {"type": "string"}, "deprecation_date": {"type": "string"}, @@ -952,12 +757,8 @@ def test_aaamodel_prices_and_context_window_json_is_valid(): "input_cost_per_token_above_512k_tokens": {"type": "number"}, "cache_read_input_token_cost_flex": {"type": "number"}, "cache_read_input_token_cost_priority": {"type": "number"}, - "cache_read_input_token_cost_above_200k_tokens_priority": { - "type": "number" - }, - "cache_read_input_token_cost_above_272k_tokens_priority": { - "type": "number" - }, + "cache_read_input_token_cost_above_200k_tokens_priority": {"type": "number"}, + "cache_read_input_token_cost_above_272k_tokens_priority": {"type": "number"}, "input_cost_per_token_flex": {"type": "number"}, "input_cost_per_token_priority": {"type": "number"}, "input_cost_per_token_above_200k_tokens_priority": {"type": "number"}, @@ -985,9 +786,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid(): "input_cost_per_token_cache_hit": {"type": "number"}, "input_cost_per_video_per_second": {"type": "number"}, "input_cost_per_video_per_second_above_8s_interval": {"type": "number"}, - "input_cost_per_video_per_second_above_15s_interval": { - "type": "number" - }, + "input_cost_per_video_per_second_above_15s_interval": {"type": "number"}, "input_cost_per_video_per_second_above_128k_tokens": {"type": "number"}, "input_dbu_cost_per_token": {"type": "number"}, "annotation_cost_per_page": {"type": "number"}, @@ -1215,18 +1014,12 @@ def test_aaamodel_prices_and_context_window_json_is_valid(): }, } - prod_json = os.path.join( - os.path.dirname(__file__), "..", "..", "model_prices_and_context_window.json" - ) + prod_json = os.path.join(os.path.dirname(__file__), "..", "..", "model_prices_and_context_window.json") with open(prod_json, "r") as model_prices_file: actual_json = json.load(model_prices_file) assert isinstance(actual_json, dict) - actual_json.pop( - "sample_spec", None - ) # remove the sample, whose schema is inconsistent with the real data - actual_json.pop( - "fallback_generalizations", None - ) # reserved meta key, not a model entry + actual_json.pop("sample_spec", None) # remove the sample, whose schema is inconsistent with the real data + actual_json.pop("fallback_generalizations", None) # reserved meta key, not a model entry # Validate schema validate(actual_json, INTENDED_SCHEMA) @@ -1262,9 +1055,7 @@ def test_max_tokens_consistency(): from pathlib import Path # Load the model configuration - config_path = ( - Path(__file__).parent.parent.parent / "model_prices_and_context_window.json" - ) + config_path = Path(__file__).parent.parent.parent / "model_prices_and_context_window.json" with open(config_path, "r") as f: models = json.load(f) @@ -1294,7 +1085,9 @@ def test_max_tokens_consistency(): if inconsistencies: error_msg = f"\n\n❌ Found {len(inconsistencies)} models with max_tokens != max_output_tokens:\n\n" for item in inconsistencies[:10]: # Show first 10 - error_msg += f" {item['model']}: max_tokens={item['max_tokens']}, max_output_tokens={item['max_output_tokens']}\n" + error_msg += ( + f" {item['model']}: max_tokens={item['max_tokens']}, max_output_tokens={item['max_output_tokens']}\n" + ) if len(inconsistencies) > 10: error_msg += f"\n ... and {len(inconsistencies) - 10} more\n" @@ -1303,28 +1096,6 @@ def test_max_tokens_consistency(): raise AssertionError(error_msg) -def test_get_model_info_gemini(monkeypatch): - """ - Tests if ALL gemini models have 'tpm' and 'rpm' in the model info - """ - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - litellm.model_cost = litellm.get_model_cost_map(url="") - - model_map = litellm.model_cost - for model, info in model_map.items(): - if ( - model.startswith("gemini/") - and not "gemma" in model - and not "learnlm" in model - and not "imagen" in model - and not "veo" in model - and not "lyria" in model - and not "robotics" in model - ): - assert info.get("tpm") is not None, f"{model} does not have tpm" - assert info.get("rpm") is not None, f"{model} does not have rpm" - - def test_get_model_info_bedrock_regional_inference_profile_pricing(local_model_cost_map): """Regression LIT-4056: with the bedrock/ routing prefix (plain, converse/, or invoke/), the exact regional cost-map entry must win over the region-stripped @@ -1347,14 +1118,6 @@ def test_get_model_info_bedrock_regional_inference_profile_pricing(local_model_c assert control["key"] == "au.anthropic.claude-opus-4-8" -def test_get_model_info_bedrock_regional_profile_without_entry_falls_back_to_base(local_model_cost_map): - """A regional profile with no dedicated cost-map entry must still resolve to its - region-stripped base entry.""" - assert "apac.anthropic.claude-opus-4-8" not in litellm.model_cost - info = litellm.get_model_info(model="bedrock/apac.anthropic.claude-opus-4-8") - assert info["key"] == "anthropic.claude-opus-4-8" - - def test_get_model_info_bedrock_double_provider_prefix_resolves(local_model_cost_map): """A doubled bedrock/ prefix routes at runtime via strip_bedrock_routing_prefix, so model info must resolve it to the same entry the request actually bills as.""" @@ -1369,15 +1132,10 @@ def test_openai_models_in_model_info(monkeypatch): model_map = litellm.model_cost violated_models = [] for model, info in model_map.items(): - if ( - info.get("litellm_provider") == "openai" - and info.get("supports_vision") is True - ): + if info.get("litellm_provider") == "openai" and info.get("supports_vision") is True: if info.get("supports_pdf_input") is not True: violated_models.append(model) - assert ( - len(violated_models) == 0 - ), f"The following models should support pdf input: {violated_models}" + assert len(violated_models) == 0, f"The following models should support pdf input: {violated_models}" def test_supports_tool_choice_simple_tests(): @@ -1385,18 +1143,8 @@ def test_supports_tool_choice_simple_tests(): simple sanity checks """ assert litellm.utils.supports_tool_choice(model="gpt-4o") == True - assert ( - litellm.utils.supports_tool_choice( - model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0" - ) - == True - ) - assert ( - litellm.utils.supports_tool_choice( - model="anthropic.claude-3-sonnet-20240229-v1:0" - ) - is True - ) + assert litellm.utils.supports_tool_choice(model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0") == True + assert litellm.utils.supports_tool_choice(model="anthropic.claude-3-sonnet-20240229-v1:0") is True assert ( litellm.utils.supports_tool_choice( @@ -1468,14 +1216,8 @@ def test_check_provider_match_none_value_matches_any_provider(): """ # Missing key already returned True; None must behave identically. assert litellm.utils._check_provider_match({}, "openai") is True - assert ( - litellm.utils._check_provider_match({"litellm_provider": None}, "openai") - is True - ) - assert ( - litellm.utils._check_provider_match({"litellm_provider": None}, "anthropic") - is True - ) + assert litellm.utils._check_provider_match({"litellm_provider": None}, "openai") is True + assert litellm.utils._check_provider_match({"litellm_provider": None}, "anthropic") is True # When custom_llm_provider is also None nothing constrains the match. assert litellm.utils._check_provider_match({"litellm_provider": None}, None) is True @@ -1567,9 +1309,7 @@ def test_supports_computer_use_utility(monkeypatch): try: # Test a model known to support computer_use from backup JSON - supports_cu_anthropic = supports_computer_use( - model="anthropic/claude-4-sonnet-20250514" - ) + supports_cu_anthropic = supports_computer_use(model="anthropic/claude-4-sonnet-20250514") assert supports_cu_anthropic is True # Test a model known not to have the flag or set to false (defaults to False via get_model_info) @@ -1588,35 +1328,6 @@ def test_supports_computer_use_utility(monkeypatch): delattr(litellm, "model_cost") -def test_get_model_info_shows_supports_computer_use(monkeypatch): - """ - Tests if 'supports_computer_use' is correctly retrieved by get_model_info. - We'll use 'claude-4-sonnet-20250514' as it's configured - in the backup JSON to have supports_computer_use: True. - """ - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - # Ensure litellm.model_cost is loaded, relying on the backup mechanism if primary fails - # as per previous debugging. - litellm.model_cost = litellm.get_model_cost_map(url="") - - # This model should have 'supports_computer_use': True in the backup JSON - model_known_to_support_computer_use = "claude-4-sonnet-20250514" - info = litellm.get_model_info(model_known_to_support_computer_use) - print(f"Info for {model_known_to_support_computer_use}: {info}") - - # After the fix in utils.py, this should now be present and True - assert info.get("supports_computer_use") is True - - # Optionally, test a model known NOT to support it, or where it's undefined (should default to False) - # For example, if "gpt-3.5-turbo" doesn't have it defined, it should be False. - model_known_not_to_support_computer_use = "gpt-3.5-turbo" - info_gpt = litellm.get_model_info(model_known_not_to_support_computer_use) - print(f"Info for {model_known_not_to_support_computer_use}: {info_gpt}") - assert ( - info_gpt.get("supports_computer_use") is None - ) # Expecting None due to the default in ModelInfoBase - - @pytest.mark.parametrize( "model, custom_llm_provider", [ @@ -1704,9 +1415,7 @@ def test_provider_supports_vertex_params(custom_llm_provider, expected): ("gpt-4o", "openai", False), ], ) -def test_vertex_params_not_stripped_for_vertex_family( - model, custom_llm_provider, should_keep -): +def test_vertex_params_not_stripped_for_vertex_family(model, custom_llm_provider, should_keep): optional_params = litellm.utils.get_optional_params( model=model, custom_llm_provider=custom_llm_provider, @@ -1772,25 +1481,19 @@ class TestProxyFunctionCalling: ("command-nightly", "litellm_proxy/command-nightly", False), ], ) - def test_proxy_function_calling_support_consistency( - self, direct_model, proxy_model, expected_result - ): + def test_proxy_function_calling_support_consistency(self, direct_model, proxy_model, expected_result): """Test that proxy models have the same function calling support as their direct counterparts.""" direct_result = supports_function_calling(direct_model) proxy_result = supports_function_calling(proxy_model) # Both should match the expected result - assert ( - direct_result == expected_result - ), f"Direct model {direct_model} should return {expected_result}" - assert ( - proxy_result == expected_result - ), f"Proxy model {proxy_model} should return {expected_result}" + assert direct_result == expected_result, f"Direct model {direct_model} should return {expected_result}" + assert proxy_result == expected_result, f"Proxy model {proxy_model} should return {expected_result}" # Direct and proxy should be consistent - assert ( - direct_result == proxy_result - ), f"Mismatch: {direct_model}={direct_result} vs {proxy_model}={proxy_result}" + assert direct_result == proxy_result, ( + f"Mismatch: {direct_model}={direct_result} vs {proxy_model}={proxy_result}" + ) @pytest.mark.parametrize( "proxy_model_name,underlying_model,expected_proxy_result", @@ -1857,9 +1560,7 @@ class TestProxyFunctionCalling: ("litellm_proxy/local-mistral", "ollama/mistral", False), ], ) - def test_proxy_custom_model_names_without_config( - self, proxy_model_name, underlying_model, expected_proxy_result - ): + def test_proxy_custom_model_names_without_config(self, proxy_model_name, underlying_model, expected_proxy_result): """ Test proxy models with custom model names that differ from underlying models. @@ -1870,17 +1571,15 @@ class TestProxyFunctionCalling: # Test the underlying model directly first to establish what it SHOULD return try: underlying_result = supports_function_calling(underlying_model) - print( - f"Underlying model {underlying_model} supports function calling: {underlying_result}" - ) + print(f"Underlying model {underlying_model} supports function calling: {underlying_result}") except Exception as e: print(f"Warning: Could not test underlying model {underlying_model}: {e}") # Test the proxy model - this will return False due to lack of configuration context proxy_result = supports_function_calling(proxy_model_name) - assert ( - proxy_result == expected_proxy_result - ), f"Proxy model {proxy_model_name} should return {expected_proxy_result} (without config context)" + assert proxy_result == expected_proxy_result, ( + f"Proxy model {proxy_model_name} should return {expected_proxy_result} (without config context)" + ) def test_proxy_model_resolution_with_custom_names_documentation(self): """ @@ -1894,9 +1593,7 @@ class TestProxyFunctionCalling: # Case 1: Custom model name that cannot be resolved custom_model = "litellm_proxy/my-custom-claude" result = supports_function_calling(custom_model) - assert ( - result is False - ), "Custom model names return False without proxy config context" + assert result is False, "Custom model names return False without proxy config context" # Case 2: Model name that can be resolved (matches pattern) resolvable_model = "litellm_proxy/claude-sonnet-4-5-20250929" @@ -1933,9 +1630,7 @@ class TestProxyFunctionCalling: ), # Hints at Bedrock Claude 3 Sonnet ], ) - def test_proxy_models_with_naming_hints( - self, proxy_model_with_hints, expected_result - ): + def test_proxy_models_with_naming_hints(self, proxy_model_with_hints, expected_result): """ Test proxy models with names that provide hints about the underlying model. @@ -1947,14 +1642,10 @@ class TestProxyFunctionCalling: # Currently these will return False, but we document the expected behavior # In the future, we could implement smarter model name inference - print( - f"Model {proxy_model_with_hints}: current={proxy_result}, desired={expected_result}" - ) + print(f"Model {proxy_model_with_hints}: current={proxy_result}, desired={expected_result}") # For now, we expect False (current behavior), but document the limitation - assert ( - proxy_result is False - ), f"Current limitation: {proxy_model_with_hints} returns False without inference" + assert proxy_result is False, f"Current limitation: {proxy_model_with_hints} returns False without inference" @pytest.mark.parametrize( "proxy_model,expected_result", @@ -1979,9 +1670,7 @@ class TestProxyFunctionCalling: """ try: result = supports_function_calling(model=proxy_model) - assert ( - result == expected_result - ), f"Proxy model {proxy_model} returned {result}, expected {expected_result}" + assert result == expected_result, f"Proxy model {proxy_model} returned {result}, expected {expected_result}" except Exception as e: pytest.fail(f"Error testing proxy model {proxy_model}: {e}") @@ -2021,17 +1710,11 @@ class TestProxyFunctionCalling: parameter explicitly set to None, which is a common usage pattern. """ try: - result = supports_function_calling( - model=model_name, custom_llm_provider=None - ) + result = supports_function_calling(model=model_name, custom_llm_provider=None) # All the models in this test should support function calling - assert ( - result is True - ), f"Model {model_name} should support function calling but returned {result}" + assert result is True, f"Model {model_name} should support function calling but returned {result}" except Exception as e: - pytest.fail( - f"Error testing {model_name} with custom_llm_provider=None: {e}" - ) + pytest.fail(f"Error testing {model_name} with custom_llm_provider=None: {e}") def test_edge_cases_and_malformed_proxy_models(self): """Test edge cases and malformed proxy model names.""" @@ -2046,9 +1729,9 @@ class TestProxyFunctionCalling: try: result = supports_function_calling(model=model_name) # For malformed models, we expect False or the function to handle gracefully - assert ( - result == expected_result - ), f"Edge case {model_name} returned {result}, expected {expected_result}" + assert result == expected_result, ( + f"Edge case {model_name} returned {result}, expected {expected_result}" + ) except Exception: # It's acceptable for malformed model names to raise exceptions # rather than returning False, as long as they're handled gracefully @@ -2068,9 +1751,7 @@ class TestProxyFunctionCalling: proxy_result = supports_function_calling(model=proxy_model) print(f"\nDemonstration of proxy model resolution:") - print( - f"Direct model '{direct_model}' supports function calling: {direct_result}" - ) + print(f"Direct model '{direct_model}' supports function calling: {direct_result}") print(f"Proxy model '{proxy_model}' supports function calling: {proxy_result}") # This assertion will currently fail due to the bug @@ -2083,11 +1764,9 @@ class TestProxyFunctionCalling: ) assert direct_result == proxy_result, ( - f"Proxy model resolution issue: {direct_model} -> {direct_result}, " - f"{proxy_model} -> {proxy_result}" + f"Proxy model resolution issue: {direct_model} -> {direct_result}, {proxy_model} -> {proxy_result}" ) - @pytest.mark.parametrize( "proxy_model_name,underlying_bedrock_model,expected_proxy_result,description", [ @@ -2258,13 +1937,11 @@ class TestProxyFunctionCalling: # Most Bedrock Converse API models with Anthropic Claude should support function calling if "anthropic.claude-3" in underlying_bedrock_model: - assert ( - underlying_result is True - ), f"Claude 3 models should support function calling: {underlying_bedrock_model}" + assert underlying_result is True, ( + f"Claude 3 models should support function calling: {underlying_bedrock_model}" + ) except Exception as e: - print( - f" Warning: Could not test underlying model {underlying_bedrock_model}: {e}" - ) + print(f" Warning: Could not test underlying model {underlying_bedrock_model}: {e}") # Test the proxy model - should return False due to lack of configuration context proxy_result = supports_function_calling(proxy_model_name) @@ -2349,9 +2026,7 @@ class TestProxyFunctionCalling: result = supports_function_calling(model) print(f"Direct test - {model}: {result}") # Claude 3 models should support function calling - assert ( - result is True - ), f"Claude 3 model should support function calling: {model}" + assert result is True, f"Claude 3 model should support function calling: {model}" except Exception as e: print(f"Could not test {model}: {e}") @@ -2403,9 +2078,7 @@ def test_register_model_url_fetch_uses_single_attempt(monkeypatch): monkeypatch.setattr(litellm, "model_cost", dict(litellm.model_cost)) before = dict(litellm.model_cost) threads_before = {thread.name for thread in threading.enumerate()} - route = respx.get("https://example.invalid/custom_pricing.json").mock( - return_value=httpx.Response(503) - ) + route = respx.get("https://example.invalid/custom_pricing.json").mock(return_value=httpx.Response(503)) litellm.register_model(model_cost="https://example.invalid/custom_pricing.json") @@ -2413,8 +2086,7 @@ def test_register_model_url_fetch_uses_single_attempt(monkeypatch): assert route.call_count == 1 assert not (threads_after - threads_before) & {"litellm-model-cost-map-retry"} assert not any( - thread.name == "litellm-model-cost-map-retry" and thread.is_alive() - for thread in threading.enumerate() + thread.name == "litellm-model-cost-map-retry" and thread.is_alive() for thread in threading.enumerate() ) assert litellm.model_cost.keys() >= before.keys() @@ -2528,9 +2200,7 @@ def test_anthropic_claude_4_invoke_chat_provider_config(): def test_bedrock_application_inference_profile(): model = "arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-5-haiku-20241022-v1:0" - from pydantic import BaseModel - from litellm import completion from litellm.utils import supports_tool_choice result = supports_tool_choice(model, custom_llm_provider="bedrock") @@ -2560,7 +2230,7 @@ def test_image_response_utils(): "object": "list", "hidden_params": {"additional_headers": {}}, } - image_response = ImageResponse(**result) + ImageResponse(**result) def test_is_valid_api_key(): @@ -2597,7 +2267,6 @@ def test_block_key_hashing_logic(): """ Test that block_key() function only hashes keys that start with "sk-" """ - import hashlib from litellm.proxy.utils import hash_token @@ -2623,17 +2292,13 @@ def test_block_key_hashing_logic(): # Additional verification: if it should be hashed, verify it's actually a hash if should_be_hashed: # SHA-256 hashes are 64 characters long and contain only hex digits - assert ( - len(hashed_token) == 64 - ), f"Hash length should be 64, got {len(hashed_token)} for {input_key}" - assert all( - c in "0123456789abcdef" for c in hashed_token - ), f"Hash should contain only hex digits for {input_key}" + assert len(hashed_token) == 64, f"Hash length should be 64, got {len(hashed_token)} for {input_key}" + assert all(c in "0123456789abcdef" for c in hashed_token), ( + f"Hash should contain only hex digits for {input_key}" + ) else: # If not hashed, it should be the original string - assert ( - hashed_token == input_key - ), f"Non-hashed key should remain unchanged: {input_key}" + assert hashed_token == input_key, f"Non-hashed key should remain unchanged: {input_key}" print("✅ All block_key hashing logic tests passed!") @@ -2660,9 +2325,7 @@ def test_generate_gcp_iam_access_token(): mock_iam_credentials_v1.GenerateAccessTokenRequest = Mock() # Test successful token generation by mocking sys.modules - with patch.dict( - "sys.modules", {"google.cloud.iam_credentials_v1": mock_iam_credentials_v1} - ): + with patch.dict("sys.modules", {"google.cloud.iam_credentials_v1": mock_iam_credentials_v1}): from litellm._redis import _generate_gcp_iam_access_token result = _generate_gcp_iam_access_token(service_account) @@ -2718,17 +2381,13 @@ def test_generate_azure_ad_redis_token(): mock_azure_identity.ClientSecretCredential = Mock() mock_azure_identity.ManagedIdentityCredential = Mock() - with patch.dict( - "sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()} - ): + with patch.dict("sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()}): from litellm._redis import _generate_azure_ad_redis_token result = _generate_azure_ad_redis_token() assert result == expected_token - mock_credential.get_token.assert_called_once_with( - "https://redis.azure.com/.default" - ) + mock_credential.get_token.assert_called_once_with("https://redis.azure.com/.default") def test_generate_azure_ad_redis_token_service_principal(): @@ -2750,9 +2409,7 @@ def test_generate_azure_ad_redis_token_service_principal(): mock_azure_identity.ClientSecretCredential = mock_client_secret_credential mock_azure_identity.ManagedIdentityCredential = Mock() - with patch.dict( - "sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()} - ): + with patch.dict("sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()}): from litellm._redis import _generate_azure_ad_redis_token result = _generate_azure_ad_redis_token( @@ -2772,6 +2429,7 @@ def test_generate_azure_ad_redis_token_service_principal(): def test_generate_azure_ad_redis_token_import_error(): """Test that _generate_azure_ad_redis_token raises ImportError when azure-identity is missing.""" from unittest.mock import patch + from litellm._redis import _generate_azure_ad_redis_token with patch.dict("sys.modules", {"azure.identity": None}): @@ -2795,9 +2453,7 @@ def test_redis_client_logic_azure_ad_auth(): mock_azure_identity.ClientSecretCredential = Mock(return_value=mock_credential) mock_azure_identity.ManagedIdentityCredential = Mock(return_value=mock_credential) - with patch.dict( - "sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()} - ): + with patch.dict("sys.modules", {"azure.identity": mock_azure_identity, "azure": Mock()}): from litellm._redis import _get_redis_client_logic redis_kwargs = _get_redis_client_logic( @@ -2828,78 +2484,6 @@ if __name__ == "__main__": pytest.main([__file__, "-v"]) -def test_model_info_for_vertex_ai_deepseek_model(): - model_info = litellm.get_model_info( - model="vertex_ai/deepseek-ai/deepseek-r1-0528-maas" - ) - assert model_info is not None - assert model_info["litellm_provider"] == "vertex_ai-deepseek_models" - assert model_info["mode"] == "chat" - - assert model_info["input_cost_per_token"] is not None - assert model_info["output_cost_per_token"] is not None - print("vertex deepseek model info", model_info) - - -def test_model_info_for_fireworks_short_form_models(): - """ - Test that fireworks_ai short-form model entries (fireworks_ai/) - are correctly configured in model_prices_and_context_window.json. - - These entries enable cost attribution for models called via short-form - names (e.g., fireworks_ai/glm-4p7 instead of - fireworks_ai/accounts/fireworks/models/glm-4p7). - """ - import json - from pathlib import Path - - json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" - with open(json_path) as f: - model_cost = json.load(f) - - # glm-4p7: short-form and long-form - for key in [ - "fireworks_ai/glm-4p7", - "fireworks_ai/accounts/fireworks/models/glm-4p7", - ]: - info = model_cost.get(key) - assert ( - info is not None - ), f"{key} not found in model_prices_and_context_window.json" - assert info["litellm_provider"] == "fireworks_ai" - assert info["mode"] == "chat" - assert info["input_cost_per_token"] == 6e-07 - assert info["output_cost_per_token"] == 2.2e-06 - assert info["max_input_tokens"] == 202800 - assert info["supports_reasoning"] is True - - # minimax-m2p1: short-form and long-form - for key in [ - "fireworks_ai/minimax-m2p1", - "fireworks_ai/accounts/fireworks/models/minimax-m2p1", - ]: - info = model_cost.get(key) - assert ( - info is not None - ), f"{key} not found in model_prices_and_context_window.json" - assert info["litellm_provider"] == "fireworks_ai" - assert info["mode"] == "chat" - assert info["input_cost_per_token"] == 3e-07 - assert info["output_cost_per_token"] == 1.2e-06 - assert info["max_input_tokens"] == 204800 - - # kimi-k2p5: short-form only (long-form already existed) - info = model_cost.get("fireworks_ai/kimi-k2p5") - assert ( - info is not None - ), "fireworks_ai/kimi-k2p5 not found in model_prices_and_context_window.json" - assert info["litellm_provider"] == "fireworks_ai" - assert info["mode"] == "chat" - assert info["input_cost_per_token"] == 6e-07 - assert info["output_cost_per_token"] == 3e-06 - assert info["max_input_tokens"] == 262144 - - class TestGetValidModelsWithCLI: """Test get_valid_models function as used in CLI token usage""" @@ -2918,9 +2502,7 @@ class TestGetValidModelsWithCLI: ] } - with patch.object( - litellm.module_level_client, "get", return_value=mock_response - ) as mock_get: + with patch.object(litellm.module_level_client, "get", return_value=mock_response) as mock_get: # Test the exact pattern used in cli_token_usage.py result = litellm.get_valid_models( check_provider_endpoint=True, @@ -3138,9 +2720,7 @@ class TestProxyLoggingBudgetAlerts: user_info = MagicMock() # Should not raise an error - await proxy_logging.budget_alerts( - type="organization_budget", user_info=user_info - ) + await proxy_logging.budget_alerts(type="organization_budget", user_info=user_info) async def test_budget_alerts_with_both_slack_and_email(self): """Test that budget_alerts calls both slack and email instances when both are in alerting.""" @@ -3192,9 +2772,7 @@ class TestProxyLoggingBudgetAlerts: proxy_logging.slack_alerting_instance.budget_alerts.assert_called_once_with( type=alert_type, user_info=user_info ) - proxy_logging.email_logging_instance.budget_alerts.assert_called_once_with( - type=alert_type, user_info=user_info - ) + proxy_logging.email_logging_instance.budget_alerts.assert_called_once_with(type=alert_type, user_info=user_info) async def test_budget_alerts_soft_budget_with_alert_emails_bypasses_alerting_none( self, @@ -3411,9 +2989,7 @@ def test_last_assistant_with_tool_calls_has_no_thinking_blocks_issue_18926(): {"role": "user", "content": "Build a feature"}, { "role": "assistant", - "thinking_blocks": [ - {"type": "thinking", "thinking": "Let me analyze the requirements..."} - ], + "thinking_blocks": [{"type": "thinking", "thinking": "Let me analyze the requirements..."}], "tool_calls": [ { "id": "toolu_1", @@ -3661,65 +3237,31 @@ class TestGetOptionalParamsDeepSeek: class TestIsStreamingRequest: def test_stream_true_in_kwargs(self): - assert ( - _is_streaming_request(kwargs={"stream": True}, call_type="acompletion") - is True - ) + assert _is_streaming_request(kwargs={"stream": True}, call_type="acompletion") is True def test_stream_false_in_kwargs(self): - assert ( - _is_streaming_request(kwargs={"stream": False}, call_type="acompletion") - is False - ) + assert _is_streaming_request(kwargs={"stream": False}, call_type="acompletion") is False def test_no_stream_in_kwargs(self): assert _is_streaming_request(kwargs={}, call_type="acompletion") is False def test_generate_content_stream_string(self): - assert ( - _is_streaming_request( - kwargs={}, call_type=CallTypes.generate_content_stream.value - ) - is True - ) + assert _is_streaming_request(kwargs={}, call_type=CallTypes.generate_content_stream.value) is True def test_agenerate_content_stream_string(self): - assert ( - _is_streaming_request( - kwargs={}, call_type=CallTypes.agenerate_content_stream.value - ) - is True - ) + assert _is_streaming_request(kwargs={}, call_type=CallTypes.agenerate_content_stream.value) is True def test_generate_content_stream_enum(self): - assert ( - _is_streaming_request( - kwargs={}, call_type=CallTypes.generate_content_stream - ) - is True - ) + assert _is_streaming_request(kwargs={}, call_type=CallTypes.generate_content_stream) is True def test_agenerate_content_stream_enum(self): - assert ( - _is_streaming_request( - kwargs={}, call_type=CallTypes.agenerate_content_stream - ) - is True - ) - + assert _is_streaming_request(kwargs={}, call_type=CallTypes.agenerate_content_stream) is True def test_non_streaming_call_type_enum(self): - assert ( - _is_streaming_request(kwargs={}, call_type=CallTypes.acompletion) is False - ) + assert _is_streaming_request(kwargs={}, call_type=CallTypes.acompletion) is False def test_stream_true_overrides_non_streaming_call_type(self): - assert ( - _is_streaming_request( - kwargs={"stream": True}, call_type=CallTypes.acompletion - ) - is True - ) + assert _is_streaming_request(kwargs={"stream": True}, call_type=CallTypes.acompletion) is True class TestCallbackAsyncSyncSeparation: @@ -3962,28 +3504,6 @@ class TestValidateAndFixThinkingParam: assert validate_and_fix_thinking_param(thinking=False) is None -@pytest.mark.usefixtures("local_model_cost_map") -def test_deepseek_flash_completion_cost(): - from litellm.types.utils import ModelResponse - - response = ModelResponse( - model="deepseek-flash", - usage=Usage( - prompt_tokens=1_000_000, - completion_tokens=1_000_000, - total_tokens=2_000_000, - ), - ) - - cost = litellm.completion_cost( - completion_response=response, - model="deepseek-flash", - custom_llm_provider="deepseek", - ) - - assert cost == pytest.approx(1.50, abs=1e-9) - - _FIREWORKS_MODELS = [ ( "accounts/fireworks/models/glm-5p2", @@ -4131,62 +3651,6 @@ def _assert_fireworks_entry( assert info["supports_vision"] is expected_vision -def test_fireworks_models_in_cost_map(): - import json - from pathlib import Path - - json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" - with open(json_path) as f: - model_cost = json.load(f) - - for entry in _FIREWORKS_MODELS: - _assert_fireworks_entry(model_cost, *entry) - - for short in _FIREWORKS_SHORT_FORMS: - long_key = f"fireworks_ai/accounts/fireworks/models/{short}" - short_key = f"fireworks_ai/{short}" - assert model_cost.get(short_key) == model_cost.get( - long_key - ), f"short-form {short_key} does not match long-form {long_key}" - - for short in _FIREWORKS_ROUTER_SHORT_FORMS: - long_key = f"fireworks_ai/accounts/fireworks/routers/{short}" - short_key = f"fireworks_ai/{short}" - assert model_cost.get(short_key) == model_cost.get( - long_key - ), f"short-form {short_key} does not match long-form {long_key}" - - -def test_fireworks_models_in_backup_cost_map(): - import json - from pathlib import Path - - json_path = ( - Path(__file__).parents[2] - / "litellm" - / "model_prices_and_context_window_backup.json" - ) - with open(json_path) as f: - model_cost = json.load(f) - - for entry in _FIREWORKS_MODELS: - _assert_fireworks_entry(model_cost, *entry) - - for short in _FIREWORKS_SHORT_FORMS: - long_key = f"fireworks_ai/accounts/fireworks/models/{short}" - short_key = f"fireworks_ai/{short}" - assert model_cost.get(short_key) == model_cost.get( - long_key - ), f"short-form {short_key} does not match long-form {long_key}" - - for short in _FIREWORKS_ROUTER_SHORT_FORMS: - long_key = f"fireworks_ai/accounts/fireworks/routers/{short}" - short_key = f"fireworks_ai/{short}" - assert model_cost.get(short_key) == model_cost.get( - long_key - ), f"short-form {short_key} does not match long-form {long_key}" - - @pytest.fixture def fireworks_short_model_cost_map(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: monkeypatch.setattr( @@ -4219,43 +3683,6 @@ def fireworks_short_model_cost_map(monkeypatch: pytest.MonkeyPatch) -> Iterator[ litellm.get_model_info.cache_clear() -def test_fireworks_short_model_names_resolve_to_long_cost_map_keys(fireworks_short_model_cost_map: None) -> None: - model_info = litellm.get_model_info("fireworks_ai/glm-5p3") - assert model_info["key"] == "fireworks_ai/accounts/fireworks/models/glm-5p3" - assert model_info["input_cost_per_token"] == 1e-6 - assert model_info["max_tokens"] == 100 - - model_info = litellm.get_model_info("glm-5p3", custom_llm_provider="fireworks_ai") - assert model_info["key"] == "fireworks_ai/accounts/fireworks/models/glm-5p3" - - model_info = litellm.get_model_info("fireworks_ai/glm-5p3-fast") - assert model_info["key"] == "fireworks_ai/accounts/fireworks/routers/glm-5p3-fast" - assert model_info["input_cost_per_token"] == 2.1e-6 - - model_info = litellm.get_model_info("fireworks_ai/nomic-ai/nomic-embed-text-v1.5") - assert model_info["key"] == "fireworks_ai/nomic-ai/nomic-embed-text-v1.5" - - with pytest.raises(Exception, match="isn't mapped"): - litellm.get_model_info("fireworks_ai/does-not-exist") - - -def test_fireworks_short_model_names_price_with_completion_cost(fireworks_short_model_cost_map: None) -> None: - from litellm.types.utils import ModelResponse - - response = ModelResponse( - model="fireworks_ai/glm-5p3", - usage=Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15), - ) - - cost = litellm.completion_cost( - completion_response=response, - model="fireworks_ai/glm-5p3", - custom_llm_provider="fireworks_ai", - ) - - assert cost == pytest.approx(10 * 1e-6 + 5 * 2e-6) - - class TestBedrockBaseModelLabelKeepsTools: """Regression for #29618: a Bedrock deployment whose ``base_model`` is a friendly label must not silently drop ``tools``/``tool_choice`` under ``drop_params``.""" @@ -4322,9 +3749,14 @@ def test_aws_bedrock_project_id_excluded_from_bedrock_optional_params(): assert result["aws_region_name"] == "us-east-1" -@pytest.mark.parametrize("filter_name", [ - "get_non_default_completion_params", "get_non_default_transcription_params", "filter_out_litellm_params", -]) +@pytest.mark.parametrize( + "filter_name", + [ + "get_non_default_completion_params", + "get_non_default_transcription_params", + "filter_out_litellm_params", + ], +) def test_scoped_weights_are_excluded_from_provider_params(filter_name: str) -> None: filtered = getattr(litellm.utils, filter_name)( {"provider_option": "kept", "_router_weights": {"group": {"deployment": 100}}} @@ -4450,7 +3882,7 @@ class TestVertexEmbeddingEncodingFormat: assert "encoding_format" not in optional_params def test_encoding_format_base64_still_rejected_without_drop_params(self): - with pytest.raises(Exception, match='To drop these, set `litellm\\.drop_params=True` or for proxy') as excinfo: + with pytest.raises(Exception, match="To drop these, set `litellm\\.drop_params=True` or for proxy") as excinfo: litellm.utils.get_optional_params_embeddings( model="gemini-embedding-001", encoding_format="base64", @@ -4524,36 +3956,6 @@ class TestBedrockCohereEmbeddingDispatch: assert optional_params.get("output_dimension") == 512 -@pytest.mark.parametrize( - "model", - [ - "vertex_ai/gemini-2.5-flash-image", - "vertex_ai/gemini-3-pro-image", - "vertex_ai/gemini-3-pro-image-preview", - "vertex_ai/gemini-3.1-flash-image", - "vertex_ai/gemini-3.1-flash-image-preview", - "vertex_ai/gemini-3.1-flash-lite-image", - "gemini/gemini-2.5-flash-image", - "gemini/gemini-3-pro-image", - "gemini/gemini-3-pro-image-preview", - "gemini/gemini-3.1-flash-image", - "gemini/gemini-3.1-flash-image-preview", - "gemini/gemini-3.1-flash-lite-image", - ], -) -def test_gemini_image_models_do_not_support_reasoning( - model: str, local_model_cost_map: None -) -> None: - assert model in litellm.model_cost, ( - f"{model} is missing from the local model cost map. " - "Add its entry to litellm/model_prices_and_context_window_backup.json." - ) - assert litellm.supports_reasoning(model) is False, ( - f"{model} incorrectly classified as reasoning-capable. " - "Add 'supports_reasoning: false' to its model_cost entry." - ) - - PROMPT_CACHE_MESSAGES = [{"role": "user", "content": "the quick brown fox jumps over the lazy dog " * 155}] @@ -5232,7 +4634,9 @@ async def test_async_post_call_failure_deployment_hook_swallows_callback_errors( super().__init__() self.called = False - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): self.called = True raise RuntimeError("hook exploded") @@ -5293,7 +4697,9 @@ async def test_wrapper_async_raises_original_exception_even_if_hook_callback_err exception the caller is waiting on.""" class ExplodingLogger(CustomLogger): - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): raise RuntimeError("hook exploded") monkeypatch.setattr(litellm, "callbacks", [ExplodingLogger()]) @@ -5429,7 +4835,9 @@ async def test_wrapper_async_does_not_fire_failure_hook_for_post_success_error( async def async_post_call_success_deployment_hook(self, request_data, response, call_type): raise RuntimeError("boom in success hook, model call itself succeeded") - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): self.failure_calls.append(exception) exploding_logger = ExplodingSuccessLogger() @@ -5485,7 +4893,9 @@ async def test_wrapper_async_failure_hook_exception_mutation_does_not_change_rai the real exception about to be re-raised.""" class StatusCodeMutatingLogger(CustomLogger): - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): exception.status_code = 429 monkeypatch.setattr(litellm, "callbacks", [StatusCodeMutatingLogger()]) @@ -5538,7 +4948,9 @@ async def test_router_fallback_not_skipped_when_failure_hook_callback_touches_at into every hop's kwargs and would mask this test's real signal.""" class RecordingAttemptLogger(CustomLogger): - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): attempted = request_data.get("attempted_targets") if attempted is not None: attempted.record("good-group") @@ -5593,7 +5005,9 @@ async def test_wrapper_async_preserves_original_exception_when_hook_await_is_can await getting cancelled.""" class SlowLogger(CustomLogger): - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): await asyncio.sleep(5) monkeypatch.setattr(litellm, "callbacks", [SlowLogger()]) @@ -5603,7 +5017,9 @@ async def test_wrapper_async_preserves_original_exception_when_hook_await_is_can litellm.acompletion( model="gpt-4o-mini", messages=[{"role": "user", "content": "hi"}], - mock_response=litellm.AuthenticationError(message="bad key", llm_provider="openai", model="gpt-4o-mini"), + mock_response=litellm.AuthenticationError( + message="bad key", llm_provider="openai", model="gpt-4o-mini" + ), ), timeout=0.2, ) @@ -5619,7 +5035,9 @@ async def test_wrapper_async_failure_hook_latency_does_not_inflate_reported_dura reported_durations: list[float] = [] class SlowLoggerWithDurationCapture(CustomLogger): - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): await asyncio.sleep(1) async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): @@ -5650,7 +5068,9 @@ async def test_wrapper_async_failure_hook_exception_snapshot_preserves_traceback received: list[Exception] = [] class TracebackCapturingLogger(CustomLogger): - async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None): + async def async_post_call_failure_deployment_hook( + self, request_data, exception, call_type, fallback_depth=None + ): received.append(exception) monkeypatch.setattr(litellm, "callbacks", [TracebackCapturingLogger()]) @@ -5674,6 +5094,7 @@ def test_snapshot_exception_for_hook_preserves_suppress_context_flag() -> None: suppress it). Snapshotting __cause__ before __suppress_context__ would silently flip a real exception's __suppress_context__=False to True on the snapshot, hiding a chained context a callback formatting it should still see.""" + def _raise_chained_without_from() -> None: try: raise ValueError("inner cause") @@ -5805,7 +5226,9 @@ async def test_registered_guardrail_does_not_starve_vector_store_search_results( ) from litellm.types.utils import ModelResponse - search_results: Final = [{"search_query": "coolant", "data": [{"content": [{"text": "Cryoline-9", "type": "text"}]}]}] + search_results: Final = [ + {"search_query": "coolant", "data": [{"content": [{"text": "Cryoline-9", "type": "text"}]}]} + ] logging_obj = SimpleNamespace(model_call_details={"search_results": search_results}) response = ModelResponse(choices=[{"message": {"role": "assistant", "content": "Cryoline-9"}}]) @@ -5850,9 +5273,7 @@ class TestIsVisionExplicitlyDisabled: def test_explicit_false_detected_and_absent_reads_enabled(self): from litellm.utils import is_vision_explicitly_disabled - assert ( - is_vision_explicitly_disabled("fireworks_ai/accounts/fireworks/models/deepseek-v4-flash-0731") is True - ) + assert is_vision_explicitly_disabled("fireworks_ai/accounts/fireworks/models/deepseek-v4-flash-0731") is True assert is_vision_explicitly_disabled("anthropic/claude-sonnet-4-5") is False @@ -6236,11 +5657,3 @@ def test_completion_finishes_response_metadata_before_handing_the_response_to_th assert snapshot["litellm_call_id"] assert snapshot["response_cost"] is not None assert snapshot["api_base"] - - -def test_get_model_info_carries_cache_read_input_audio_token_cost(monkeypatch): - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) - info = litellm.get_model_info("gpt-realtime-2.1-mini", custom_llm_provider="openai") - assert info["cache_read_input_audio_token_cost"] == 3e-07 - assert info["cache_read_input_token_cost"] == 6e-08 diff --git a/tests/test_litellm/test_xai_grok_4_3_model_metadata.py b/tests/test_litellm/test_xai_grok_4_3_model_metadata.py deleted file mode 100644 index e6e4eada1b6..00000000000 --- a/tests/test_litellm/test_xai_grok_4_3_model_metadata.py +++ /dev/null @@ -1,19 +0,0 @@ -import json -from pathlib import Path - - -def test_xai_grok_4_3_backup_matches_main(): - """Ensure the bundled model cost map stays in sync with the canonical file.""" - repo_root = Path(__file__).parents[2] - main_path = repo_root / "model_prices_and_context_window.json" - backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" - - with open(main_path) as f: - main_cost = json.load(f) - with open(backup_path) as f: - backup_cost = json.load(f) - - for model in ("xai/grok-4.3", "xai/grok-4.3-latest"): - assert backup_cost.get(model) == main_cost.get( - model - ), f"{model} differs between main and backup model cost maps" From a428cc8d84e41cc4ba14da16dba6a70b57418a1b Mon Sep 17 00:00:00 2001 From: kerry Date: Tue, 15 Sep 2026 21:44:39 +0000 Subject: [PATCH 2/6] test: restore runtime-derived tests dropped by mistake Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../llm_cost_calc/test_llm_cost_calc_utils.py | 142 ++++++++++++++++++ .../test_get_model_cost_map.py | 50 ++++++ ...azure_ai_foundry_catalog_model_metadata.py | 30 +++- ...artner_models_anthropic_messages_config.py | 29 ++++ .../test_baseten_glm_5_3_model_metadata.py | 27 ++++ 5 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 tests/test_litellm/test_baseten_glm_5_3_model_metadata.py diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py index 7a72c9d3af0..0743476417e 100644 --- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py +++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py @@ -4,6 +4,7 @@ from datetime import datetime, timezone import pytest import litellm +from litellm._internal_context import pinned_billing_time from litellm.litellm_core_utils.llm_cost_calc.utils import ( BilledTokenRates, CostCalculatorUtils, @@ -2086,6 +2087,95 @@ def test_cache_writing_cost_with_zero_creation_tokens_and_ephemeral_details(): assert round(result, 6) == round(expected, 6) +def test_a_pinned_billing_time_prices_the_totals_and_the_reported_rates_at_one_moment(monkeypatch): + monkeypatch.setitem( + litellm.model_cost, + "off-peak-model", + { + "input_cost_per_token": 3e-6, + "output_cost_per_token": 15e-6, + "off_peak_pricing": { + "hours_utc": "02:00-03:00", + "input_cost_per_token": 1e-6, + "output_cost_per_token": 5e-6, + }, + "litellm_provider": "openai", + "mode": "chat", + }, + ) + usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) + + with pinned_billing_time(datetime(2026, 1, 1, 2, 30, tzinfo=timezone.utc)): + off_peak_prompt_cost, off_peak_completion_cost = generic_cost_per_token( + model="off-peak-model", usage=usage, custom_llm_provider="openai" + ) + off_peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) + with pinned_billing_time(datetime(2026, 1, 1, 12, 30, tzinfo=timezone.utc)): + peak_prompt_cost, peak_completion_cost = generic_cost_per_token( + model="off-peak-model", usage=usage, custom_llm_provider="openai" + ) + peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) + + assert off_peak_rates.input_cost_per_token == pytest.approx(1e-6) + assert peak_rates.input_cost_per_token == pytest.approx(3e-6) + assert off_peak_prompt_cost == pytest.approx(1000 * off_peak_rates.input_cost_per_token) + assert off_peak_completion_cost == pytest.approx(500 * off_peak_rates.output_cost_per_token) + assert peak_prompt_cost == pytest.approx(1000 * peak_rates.input_cost_per_token) + assert peak_completion_cost == pytest.approx(500 * peak_rates.output_cost_per_token) + + +def test_token_type_cost_breakdown_applies_anthropic_geo_multiplier(_local_model_cost_map, monkeypatch): + from litellm.llms.anthropic.cost_calculation import cost_per_token as anthropic_cost_per_token + + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + + model = "claude-test-geo-breakdown-model" + litellm.register_model( + model_cost={ + model: { + "input_cost_per_token": 5e-6, + "output_cost_per_token": 25e-6, + "cache_creation_input_token_cost": 6.25e-6, + "cache_read_input_token_cost": 0.5e-6, + "litellm_provider": "anthropic", + "max_tokens": 8192, + "provider_specific_entry": {"us": 1.1}, + } + } + ) + + def make_usage() -> Usage: + return Usage( + prompt_tokens=10_000, + completion_tokens=500, + total_tokens=10_500, + prompt_tokens_details=PromptTokensDetailsWrapper( + cached_tokens=2_000, + cache_creation_tokens=6_000, + ), + completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=200, text_tokens=300), + ) + + base_usage = make_usage() + geo_usage = make_usage() + geo_usage.inference_geo = "us" + + base = get_token_type_cost_breakdown(model=model, custom_llm_provider="anthropic", usage=base_usage) + geo = get_token_type_cost_breakdown(model=model, custom_llm_provider="anthropic", usage=geo_usage) + + assert base.cache_read_cost == pytest.approx(2_000 * 0.5e-6) + assert base.cache_creation_cost == pytest.approx(6_000 * 6.25e-6) + assert geo.cache_read_cost == pytest.approx(base.cache_read_cost * 1.1) + assert geo.cache_creation_cost == pytest.approx(base.cache_creation_cost * 1.1) + assert geo.reasoning_cost == pytest.approx(base.reasoning_cost * 1.1) + + prompt_cost, completion_cost = anthropic_cost_per_token(model=model, usage=geo_usage) + text_input_cost = 2_000 * 5e-6 * 1.1 + text_output_cost = 300 * 25e-6 * 1.1 + assert text_input_cost + geo.cache_read_cost + geo.cache_creation_cost == pytest.approx(prompt_cost) + assert text_output_cost + geo.reasoning_cost == pytest.approx(completion_cost) + + def test_service_tier_ultrafast_pricing(): """An ultrafast request bills the *_ultrafast rates for all token types. @@ -3251,6 +3341,58 @@ def test_token_type_cost_breakdown_applies_vertex_regional_uplift(_local_model_c assert text_input_cost + regional.cache_read_cost == pytest.approx(prompt_cost) +@pytest.mark.parametrize("details_as_dict", [True, False]) +def test_image_response_input_image_tokens_priced_at_image_rate(details_as_dict): + """ + Image input tokens must be priced at input_cost_per_image_token even when + input_tokens_details is a plain dict, as in OpenAI image edit responses. + + Regression test: dict-shaped input_tokens_details was read with getattr(), + which returns None for dicts, so image input tokens silently fell back to + the text input rate (e.g. $5/M instead of $8/M for gpt-image-2). + """ + from unittest.mock import patch + + from litellm.litellm_core_utils.llm_cost_calc.utils import ( + calculate_image_response_cost_from_usage, + ) + from litellm.types.utils import Usage + + mock_model_info = { + "input_cost_per_token": 5e-6, + "input_cost_per_image_token": 8e-6, + "output_cost_per_image_token": 3e-5, + } + + input_details = {"text_tokens": 19, "image_tokens": 512} + image_response = ImageResponse(data=[ImageObject(b64_json="x")]) + # Mirror the usage shape of a real OpenAI images.edit response: + # a Usage object carrying input_tokens/output_tokens with detail dicts. + image_response.usage = Usage( + prompt_tokens=0, + completion_tokens=0, + total_tokens=689, + input_tokens=531, + input_tokens_details=(input_details if details_as_dict else ImageUsageInputTokensDetails(**input_details)), + output_tokens=158, + output_tokens_details={"image_tokens": 158, "text_tokens": 0}, + ) + + with patch( + "litellm.litellm_core_utils.llm_cost_calc.utils.get_model_info", + return_value=mock_model_info, + ): + cost = calculate_image_response_cost_from_usage( + model="gpt-image-2", + image_response=image_response, + custom_llm_provider="openai", + ) + + expected = 19 * 5e-6 + 512 * 8e-6 + 158 * 3e-5 + assert cost is not None + assert round(cost, 12) == round(expected, 12) + + GEMINI_DAY0_LAUNCH_PRICING = [ ("gemini-3.6-flash", 7.5e-07, 3.75e-06, 7.5e-08), ("gemini/gemini-3.6-flash", 7.5e-07, 3.75e-06, 7.5e-08), diff --git a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py index 76467dfb7b1..f73e6378b92 100644 --- a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py +++ b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py @@ -86,6 +86,21 @@ def test_validation_accepts_healthy_file_with_meta_keys(): ) +def test_validation_rejects_significant_shrink_vs_backup(): + # 600 real models vs a 2000-model backup is below the 50% shrink threshold. + shrunk = _make_models(600) + shrunk[FALLBACK_GENERALIZATIONS_KEY] = {"rules": []} + assert ( + GetModelCostMap.validate_model_cost_map( + fetched_map=shrunk, + backup_model_count=2000, + min_model_count=50, + max_shrink_ratio=0.5, + ) + is False + ) + + def test_finalize_pops_key_and_installs_rules(): previous = list(get_fallback_generalization_rules()) try: @@ -589,6 +604,41 @@ def test_boot_load_records_the_blob_id_of_the_bytes_served_and_the_fetch_etag(): assert source["loaded_at"] is not None +def test_boot_load_fallback_to_the_backup_reports_its_blob_id_and_drops_the_remote_etag(): + remote, _ = _mock_client( + [httpx.Response(200, headers={"ETag": 'W/"boot"'}, content=_real_map_bytes())], client_cls=httpx.Client + ) + get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=remote) + failing, _ = _mock_client([httpx.Response(404)], client_cls=httpx.Client) + + get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=failing) + + source = get_model_cost_map_source_info() + assert source["source"] == "local" + assert source["etag"] is None + assert source["source_revision"] == _bundled_blob_id() + + +def test_boot_load_that_fails_the_integrity_check_reports_the_backup_not_the_rejected_fetch(): + remote, _ = _mock_client( + [httpx.Response(200, headers={"ETag": 'W/"boot"'}, content=_real_map_bytes())], client_cls=httpx.Client + ) + get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=remote) + shrunk_body = b'{"gpt-5.4-mini": {"mode": "chat", "input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06}}' + shrunk, _ = _mock_client( + [httpx.Response(200, headers={"ETag": 'W/"shrunk"'}, content=shrunk_body)], client_cls=httpx.Client + ) + + get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=shrunk) + + source = get_model_cost_map_source_info() + assert source["source"] == "local" + assert source["fallback_reason"] == "Remote data failed integrity validation" + assert source["etag"] is None + assert source["source_revision"] == _bundled_blob_id() + assert source["source_revision"] != git_blob_id(shrunk_body) + + @pytest.mark.parametrize( ("argv0", "request_count"), [ diff --git a/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py b/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py index c9721aea7fd..5bb5b0d148d 100644 --- a/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py +++ b/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py @@ -4,7 +4,7 @@ from typing import Final import pytest from pydantic import TypeAdapter -from litellm import completion_cost +from litellm import completion_cost, cost_per_token, get_model_info from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider from litellm.types.utils import TranscriptionResponse @@ -52,6 +52,34 @@ def test_azure_ai_catalog_name_routes_to_azure_ai(catalog_name: str) -> None: assert (routed_model, provider) == (catalog_name, "azure_ai") +@pytest.mark.usefixtures("local_model_cost_map") +@pytest.mark.parametrize("catalog_name", TOKEN_PRICED_NAMES) +def test_azure_ai_catalog_name_charges_its_own_entry_per_token(catalog_name: str) -> None: + entry: Final = get_model_info(f"azure_ai/{catalog_name}") + prompt_cost, completion_cost_usd = cost_per_token( + model=f"azure_ai/{catalog_name}", prompt_tokens=A_MILLION, completion_tokens=A_MILLION + ) + assert prompt_cost > 0 + assert prompt_cost == pytest.approx(A_MILLION * entry["input_cost_per_token"]) + assert completion_cost_usd == pytest.approx(A_MILLION * entry["output_cost_per_token"]) + + +@pytest.mark.usefixtures("local_model_cost_map") +@pytest.mark.parametrize("catalog_name", TOKEN_PRICED_NAMES) +def test_azure_ai_catalog_name_prices_the_same_in_any_casing(catalog_name: str) -> None: + lowercase_cost = cost_per_token(model=f"azure_ai/{catalog_name}", prompt_tokens=A_MILLION, completion_tokens=0) + upper_cost = cost_per_token(model=f"azure_ai/{catalog_name.upper()}", prompt_tokens=A_MILLION, completion_tokens=0) + assert upper_cost == lowercase_cost + + +@pytest.mark.usefixtures("local_model_cost_map") +def test_azure_ai_whisper_catalog_name_is_priced_per_second() -> None: + one_second_cost: Final = _whisper_transcription_cost(1) + one_hour_cost: Final = _whisper_transcription_cost(AN_HOUR_IN_SECONDS) + assert one_second_cost > 0 + assert one_hour_cost == pytest.approx(AN_HOUR_IN_SECONDS * one_second_cost) + + def test_azure_ai_model_router_spellings_share_one_entry() -> None: underscore_entry = _cost_map_entry(MAIN_COST_MAP, "model_router") hyphen_entry = _cost_map_entry(MAIN_COST_MAP, "model-router") diff --git a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py index 58a040bf019..2d1e4305449 100644 --- a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py +++ b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py @@ -1,4 +1,6 @@ import copy +import json +import os from unittest.mock import MagicMock, patch from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.experimental_pass_through.transformation import ( @@ -542,3 +544,30 @@ class TestVertexAnthropicMidConversationSystem: {"type": "text", "text": "You are terse."}, {"type": "text", "text": "Cite sources."}, ] + + +def test_vertex_claude_4_8_plus_cost_map_entries_carry_mid_conversation_system_flag(): + import re + + import litellm + + cost_map_path = os.path.join(os.path.dirname(litellm.__file__), "model_prices_and_context_window_backup.json") + with open(cost_map_path) as f: + cost_map = json.load(f) + rules = cost_map["fallback_generalizations"]["rules"] + rule_pattern = next( + (r["pattern"] for r in rules if r["name"] == "claude-mid-conversation-system"), + None, + ) + assert rule_pattern is not None, "claude-mid-conversation-system rule not found in fallback_generalizations" + pattern = re.compile(rule_pattern, re.IGNORECASE) + missing = [ + key + for key, info in cost_map.items() + if isinstance(info, dict) + and str(info.get("litellm_provider", "")).startswith("vertex_ai") + and "claude" in key + and pattern.search(key) + and info.get("supports_mid_conversation_system") is not True + ] + assert missing == [] diff --git a/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py b/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py new file mode 100644 index 00000000000..94afd9fe254 --- /dev/null +++ b/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py @@ -0,0 +1,27 @@ +import pytest + +import litellm + + +@pytest.fixture +def local_model_cost_map(monkeypatch): + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) + litellm.get_model_info.cache_clear() + yield + litellm.get_model_info.cache_clear() + + +def test_entry_advertises_only_what_the_baseten_path_accepts(local_model_cost_map): + """The Baseten path rejects unsupported request parameters.""" + supported = litellm.get_supported_openai_params(model="zai-org/GLM-5.3", custom_llm_provider="baseten") + assert supported is not None + + with pytest.raises(litellm.UnsupportedParamsError): + litellm.utils.get_optional_params( + model="zai-org/GLM-5.3", + custom_llm_provider="baseten", + parallel_tool_calls=True, + reasoning_effort="high", + drop_params=False, + ) From 2586b21893d0fb1e35ca50dec3f23271b02815b9 Mon Sep 17 00:00:00 2001 From: kerry Date: Tue, 15 Sep 2026 22:16:08 +0000 Subject: [PATCH 3/6] test: keep tests that survive correct cost-map updates Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../llm_cost_calc/test_llm_cost_calc_utils.py | 191 +++++++------ .../test_get_model_cost_map.py | 55 ++++ ...azure_ai_foundry_catalog_model_metadata.py | 24 ++ .../llms/cohere/ocr/test_cohere_parse_cost.py | 28 ++ .../test_databricks_cost_calculator.py | 51 ++++ .../databricks/test_databricks_pricing.py | 0 .../test_fireworks_ai_cost_calculator.py | 10 + .../test_fireworks_ai_kimi_model_metadata.py | 54 ++++ .../llms/mistral/ocr/test_mistral_ocr_cost.py | 40 +++ .../llms/openai_like/test_scx_ai_provider.py | 28 ++ .../perplexity/test_perplexity_integration.py | 18 ++ .../llms/tencent/test_cost_calculator.py | 1 + ...artner_models_anthropic_messages_config.py | 42 +++ .../llms/xai/test_xai_model_registry.py | 55 ++++ .../xai/test_xai_redirected_slug_pricing.py | 20 ++ .../proxy/spend_tracking/test_savings.py | 23 ++ .../test_azure_ai_grok_4_3_model_metadata.py | 37 +++ .../test_azure_ai_grok_4_6_model_metadata.py | 44 +++ .../test_baseten_glm_5_3_model_metadata.py | 47 ++++ ..._bedrock_marengo_embed_3_model_metadata.py | 52 ++++ .../test_bedrock_usgov_pricing.py | 12 + .../test_claude_fable_5_config.py | 129 +++++++++ .../test_claude_haiku_4_5_config.py | 46 ++++ .../test_litellm/test_claude_opus_5_config.py | 27 ++ .../test_claude_sonnet_5_config.py | 29 ++ ...st_cloudflare_workers_ai_model_metadata.py | 50 ++++ .../test_litellm/test_command_r7b_pricing.py | 53 ++++ .../test_daybreak_model_metadata.py | 15 ++ .../test_deepseek_model_metadata.py | 25 ++ .../test_fireworks_serverless_model_costs.py | 35 +-- ...est_gemini_3_1_flash_lite_image_pricing.py | 5 + .../test_gemini_tts_native_audio_pricing.py | 84 ++++++ .../test_gpt_5_4_model_metadata.py | 44 +++ .../test_gpt_5_5_model_metadata.py | 19 ++ tests/test_litellm/test_gpt_realtime_mode.py | 16 +- .../test_mistral_medium_3_5_model_metadata.py | 33 +++ .../test_mistral_small_4_0_model_metadata.py | 26 ++ ...test_mistral_zai_glm_5_2_model_metadata.py | 52 ++++ .../test_muse_spark_1_1_model_metadata.py | 29 ++ .../test_muse_spark_1_2_model_metadata.py | 9 + .../test_muse_spark_1_3_model_metadata.py | 9 + .../test_replicate_model_key_format.py | 15 ++ .../test_sambanova_model_metadata.py | 25 ++ .../test_together_ai_model_metadata.py | 8 + tests/test_litellm/test_utils.py | 253 +++++++++++++++++- .../test_xai_grok_4_3_model_metadata.py | 19 ++ 46 files changed, 1771 insertions(+), 116 deletions(-) create mode 100644 tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py create mode 100644 tests/test_litellm/llms/databricks/test_databricks_pricing.py create mode 100644 tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py create mode 100644 tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py create mode 100644 tests/test_litellm/llms/tencent/test_cost_calculator.py create mode 100644 tests/test_litellm/llms/xai/test_xai_model_registry.py create mode 100644 tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py create mode 100644 tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py create mode 100644 tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py create mode 100644 tests/test_litellm/test_claude_haiku_4_5_config.py create mode 100644 tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py create mode 100644 tests/test_litellm/test_command_r7b_pricing.py create mode 100644 tests/test_litellm/test_gemini_tts_native_audio_pricing.py create mode 100644 tests/test_litellm/test_gpt_5_4_model_metadata.py create mode 100644 tests/test_litellm/test_gpt_5_5_model_metadata.py create mode 100644 tests/test_litellm/test_mistral_medium_3_5_model_metadata.py create mode 100644 tests/test_litellm/test_mistral_small_4_0_model_metadata.py create mode 100644 tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py create mode 100644 tests/test_litellm/test_muse_spark_1_1_model_metadata.py create mode 100644 tests/test_litellm/test_sambanova_model_metadata.py create mode 100644 tests/test_litellm/test_xai_grok_4_3_model_metadata.py diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py index 0743476417e..798d657cce7 100644 --- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py +++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py @@ -2087,95 +2087,6 @@ def test_cache_writing_cost_with_zero_creation_tokens_and_ephemeral_details(): assert round(result, 6) == round(expected, 6) -def test_a_pinned_billing_time_prices_the_totals_and_the_reported_rates_at_one_moment(monkeypatch): - monkeypatch.setitem( - litellm.model_cost, - "off-peak-model", - { - "input_cost_per_token": 3e-6, - "output_cost_per_token": 15e-6, - "off_peak_pricing": { - "hours_utc": "02:00-03:00", - "input_cost_per_token": 1e-6, - "output_cost_per_token": 5e-6, - }, - "litellm_provider": "openai", - "mode": "chat", - }, - ) - usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) - - with pinned_billing_time(datetime(2026, 1, 1, 2, 30, tzinfo=timezone.utc)): - off_peak_prompt_cost, off_peak_completion_cost = generic_cost_per_token( - model="off-peak-model", usage=usage, custom_llm_provider="openai" - ) - off_peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) - with pinned_billing_time(datetime(2026, 1, 1, 12, 30, tzinfo=timezone.utc)): - peak_prompt_cost, peak_completion_cost = generic_cost_per_token( - model="off-peak-model", usage=usage, custom_llm_provider="openai" - ) - peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) - - assert off_peak_rates.input_cost_per_token == pytest.approx(1e-6) - assert peak_rates.input_cost_per_token == pytest.approx(3e-6) - assert off_peak_prompt_cost == pytest.approx(1000 * off_peak_rates.input_cost_per_token) - assert off_peak_completion_cost == pytest.approx(500 * off_peak_rates.output_cost_per_token) - assert peak_prompt_cost == pytest.approx(1000 * peak_rates.input_cost_per_token) - assert peak_completion_cost == pytest.approx(500 * peak_rates.output_cost_per_token) - - -def test_token_type_cost_breakdown_applies_anthropic_geo_multiplier(_local_model_cost_map, monkeypatch): - from litellm.llms.anthropic.cost_calculation import cost_per_token as anthropic_cost_per_token - - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - - model = "claude-test-geo-breakdown-model" - litellm.register_model( - model_cost={ - model: { - "input_cost_per_token": 5e-6, - "output_cost_per_token": 25e-6, - "cache_creation_input_token_cost": 6.25e-6, - "cache_read_input_token_cost": 0.5e-6, - "litellm_provider": "anthropic", - "max_tokens": 8192, - "provider_specific_entry": {"us": 1.1}, - } - } - ) - - def make_usage() -> Usage: - return Usage( - prompt_tokens=10_000, - completion_tokens=500, - total_tokens=10_500, - prompt_tokens_details=PromptTokensDetailsWrapper( - cached_tokens=2_000, - cache_creation_tokens=6_000, - ), - completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=200, text_tokens=300), - ) - - base_usage = make_usage() - geo_usage = make_usage() - geo_usage.inference_geo = "us" - - base = get_token_type_cost_breakdown(model=model, custom_llm_provider="anthropic", usage=base_usage) - geo = get_token_type_cost_breakdown(model=model, custom_llm_provider="anthropic", usage=geo_usage) - - assert base.cache_read_cost == pytest.approx(2_000 * 0.5e-6) - assert base.cache_creation_cost == pytest.approx(6_000 * 6.25e-6) - assert geo.cache_read_cost == pytest.approx(base.cache_read_cost * 1.1) - assert geo.cache_creation_cost == pytest.approx(base.cache_creation_cost * 1.1) - assert geo.reasoning_cost == pytest.approx(base.reasoning_cost * 1.1) - - prompt_cost, completion_cost = anthropic_cost_per_token(model=model, usage=geo_usage) - text_input_cost = 2_000 * 5e-6 * 1.1 - text_output_cost = 300 * 25e-6 * 1.1 - assert text_input_cost + geo.cache_read_cost + geo.cache_creation_cost == pytest.approx(prompt_cost) - assert text_output_cost + geo.reasoning_cost == pytest.approx(completion_cost) - - def test_service_tier_ultrafast_pricing(): """An ultrafast request bills the *_ultrafast rates for all token types. @@ -3134,6 +3045,46 @@ def test_billed_token_rates_follow_the_token_tier_the_breakdown_bills_at(monkeyp assert breakdown.reasoning_cost == pytest.approx(200 * rates.output_cost_per_reasoning_token) +def test_a_pinned_billing_time_prices_the_totals_and_the_reported_rates_at_one_moment(monkeypatch): + """Totals and reported rates resolve off-peak pricing on separate paths that each read the + clock, so a window opening between the two reads used to leave them describing one request + at two different prices. Pinned, both must answer for the pinned moment.""" + monkeypatch.setitem( + litellm.model_cost, + "off-peak-model", + { + "input_cost_per_token": 3e-6, + "output_cost_per_token": 15e-6, + "off_peak_pricing": { + "hours_utc": "02:00-03:00", + "input_cost_per_token": 1e-6, + "output_cost_per_token": 5e-6, + }, + "litellm_provider": "openai", + "mode": "chat", + }, + ) + usage = Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500) + + with pinned_billing_time(datetime(2026, 1, 1, 2, 30, tzinfo=timezone.utc)): + off_peak_prompt_cost, off_peak_completion_cost = generic_cost_per_token( + model="off-peak-model", usage=usage, custom_llm_provider="openai" + ) + off_peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) + with pinned_billing_time(datetime(2026, 1, 1, 12, 30, tzinfo=timezone.utc)): + peak_prompt_cost, peak_completion_cost = generic_cost_per_token( + model="off-peak-model", usage=usage, custom_llm_provider="openai" + ) + peak_rates = get_billed_token_rates(model="off-peak-model", custom_llm_provider="openai", usage=usage) + + assert off_peak_rates.input_cost_per_token == pytest.approx(1e-6) + assert peak_rates.input_cost_per_token == pytest.approx(3e-6) + assert off_peak_prompt_cost == pytest.approx(1000 * off_peak_rates.input_cost_per_token) + assert off_peak_completion_cost == pytest.approx(500 * off_peak_rates.output_cost_per_token) + assert peak_prompt_cost == pytest.approx(1000 * peak_rates.input_cost_per_token) + assert peak_completion_cost == pytest.approx(500 * peak_rates.output_cost_per_token) + + def test_the_token_type_breakdown_carries_the_rates_it_billed_at(monkeypatch): """Callers that report both the lines and the rates read the rates off the breakdown rather than resolving them a second time, so the breakdown has to hand back exactly what it billed at.""" @@ -3341,6 +3292,68 @@ def test_token_type_cost_breakdown_applies_vertex_regional_uplift(_local_model_c assert text_input_cost + regional.cache_read_cost == pytest.approx(prompt_cost) +def test_token_type_cost_breakdown_applies_anthropic_geo_multiplier(_local_model_cost_map, monkeypatch): + """ + Anthropic's regional (geo) uplift lives in provider_specific_entry and is + applied to every token type in the totals, so the per-type breakdown must + scale its cache and reasoning line items by it too. Otherwise the logged + cache costs stay at the base rate and the cache uplift is misattributed to + plain input for exactly the cache-heavy regional traffic the uplift targets. + """ + from litellm.llms.anthropic.cost_calculation import ( + cost_per_token as anthropic_cost_per_token, + ) + + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + + model = "claude-test-geo-breakdown-model" + litellm.register_model( + model_cost={ + model: { + "input_cost_per_token": 5e-6, + "output_cost_per_token": 25e-6, + "cache_creation_input_token_cost": 6.25e-6, + "cache_read_input_token_cost": 0.5e-6, + "litellm_provider": "anthropic", + "max_tokens": 8192, + "provider_specific_entry": {"us": 1.1}, + } + } + ) + + def make_usage() -> Usage: + return Usage( + prompt_tokens=10_000, + completion_tokens=500, + total_tokens=10_500, + prompt_tokens_details=PromptTokensDetailsWrapper( + cached_tokens=2_000, + cache_creation_tokens=6_000, + ), + completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=200, text_tokens=300), + ) + + base_usage = make_usage() + geo_usage = make_usage() + geo_usage.inference_geo = "us" + + base = get_token_type_cost_breakdown(model=model, custom_llm_provider="anthropic", usage=base_usage) + geo = get_token_type_cost_breakdown(model=model, custom_llm_provider="anthropic", usage=geo_usage) + + assert base.cache_read_cost == pytest.approx(2_000 * 0.5e-6) + assert base.cache_creation_cost == pytest.approx(6_000 * 6.25e-6) + assert geo.cache_read_cost == pytest.approx(base.cache_read_cost * 1.1) + assert geo.cache_creation_cost == pytest.approx(base.cache_creation_cost * 1.1) + assert geo.reasoning_cost == pytest.approx(base.reasoning_cost * 1.1) + + # The uplifted breakdown must still reconcile with the uplifted totals. + prompt_cost, completion_cost = anthropic_cost_per_token(model=model, usage=geo_usage) + text_input_cost = 2_000 * 5e-6 * 1.1 + text_output_cost = 300 * 25e-6 * 1.1 + assert text_input_cost + geo.cache_read_cost + geo.cache_creation_cost == pytest.approx(prompt_cost) + assert text_output_cost + geo.reasoning_cost == pytest.approx(completion_cost) + + @pytest.mark.parametrize("details_as_dict", [True, False]) def test_image_response_input_image_tokens_priced_at_image_rate(details_as_dict): """ diff --git a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py index f73e6378b92..53fee36b3a8 100644 --- a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py +++ b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py @@ -134,6 +134,24 @@ def test_finalize_with_no_block_clears_rules(): set_fallback_generalizations(previous) +def test_shipped_backup_carries_the_claude_routing_rules(): + """The bundled backup must ship the Claude routing rules so a fresh install + (or an offline fallback) routes unknown Claude models without code changes. + Bedrock-syntax ids must hit the bedrock rule before the bare-id Anthropic rule.""" + backup = GetModelCostMap.load_local_model_cost_map() + rules = backup.get(FALLBACK_GENERALIZATIONS_KEY, {}).get("rules", []) + names = [r.get("name") for r in rules] + assert names.index("bedrock-claude-ids") < names.index("anthropic-claude-ids") + + previous = list(get_fallback_generalization_rules()) + try: + set_fallback_generalizations(rules) + assert match_routing_generalization("claude-opus-4-9") == "anthropic" + assert match_routing_generalization("global.anthropic.claude-opus-4-9") == "bedrock" + finally: + set_fallback_generalizations(previous) + + def test_shipped_routing_rules_never_match_through_an_unrecognized_namespace(): """Routing rules decide ``litellm_provider`` for otherwise-unknown ids, and the proxy's wildcard access check (``can_key_call_model`` with a ``bedrock/*`` key) @@ -170,6 +188,43 @@ def test_shipped_routing_rules_never_match_through_an_unrecognized_namespace(): set_fallback_generalizations(previous) +def test_shipped_backup_marks_claude_4_6_plus_adaptive_not_4_0(): + """Adaptive thinking is data, not code. The bundled backup must carry + supports_adaptive_thinking on genuine Claude >= 4.6 entries (every provider + route) and on the version-gated anthropic-claude-adaptive-thinking rule for + unmapped future Claudes, while leaving the dated Claude 4.0 names + ("...-4-20250514") unflagged so a date can never be mistaken for a 4.6+ minor + version. The version-neutral claude-family-baseline capability rule must not flag + it, so an unmapped sub-4.6 name resolves but stays non-adaptive. The adaptive rule + carries only its delta; capability unioning stacks it onto the baseline, so the + baseline block is never duplicated across rules and no rule needs ``extends``.""" + backup = GetModelCostMap.load_local_model_cost_map() + + rules = backup[FALLBACK_GENERALIZATIONS_KEY]["rules"] + baseline_rule = next(r for r in rules if r.get("name") == "claude-family-baseline") + adaptive_rule = next(r for r in rules if r.get("name") == "claude-adaptive-thinking") + assert "supports_adaptive_thinking" not in baseline_rule["model_info"] + assert "litellm_provider" not in baseline_rule["model_info"] + assert adaptive_rule["model_info"] == {"supports_adaptive_thinking": True} + assert all("extends" not in r for r in rules) + + for adaptive in [ + "anthropic.claude-opus-4-8", + "vertex_ai/claude-opus-4-6@default", + "us.anthropic.claude-sonnet-4-6", + "openrouter/anthropic/claude-opus-4.7", + "azure_ai/claude-opus-4-7", + ]: + assert backup[adaptive]["supports_adaptive_thinking"] is True, adaptive + + for non_adaptive in [ + "claude-opus-4-20250514", + "us.anthropic.claude-opus-4-20250514-v1:0", + "claude-opus-4-5", + ]: + assert "supports_adaptive_thinking" not in backup[non_adaptive], non_adaptive + + # OpenRouter headline rates from GET https://openrouter.ai/api/v1/models. # These were the catalog values that disagreed with that API (and, for the # two spotlight models, the public model pages that their source fields cite). diff --git a/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py b/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py index 5bb5b0d148d..9b20192c3f2 100644 --- a/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py +++ b/tests/test_litellm/llms/azure_ai/test_azure_ai_foundry_catalog_model_metadata.py @@ -72,6 +72,22 @@ def test_azure_ai_catalog_name_prices_the_same_in_any_casing(catalog_name: str) assert upper_cost == lowercase_cost +@pytest.mark.usefixtures("local_model_cost_map") +@pytest.mark.parametrize("catalog_name", GROK_4_20_NAMES) +def test_azure_ai_grok_4_20_bills_cached_prompt_tokens_at_the_input_price(catalog_name: str) -> None: + uncached_prompt_cost, _ = cost_per_token( + model=f"azure_ai/{catalog_name}", prompt_tokens=A_MILLION, completion_tokens=0 + ) + cached_prompt_cost, _ = cost_per_token( + model=f"azure_ai/{catalog_name}", + prompt_tokens=A_MILLION, + completion_tokens=0, + cache_read_input_tokens=A_MILLION, + ) + assert uncached_prompt_cost > 0 + assert cached_prompt_cost == pytest.approx(uncached_prompt_cost) + + @pytest.mark.usefixtures("local_model_cost_map") def test_azure_ai_whisper_catalog_name_is_priced_per_second() -> None: one_second_cost: Final = _whisper_transcription_cost(1) @@ -80,6 +96,14 @@ def test_azure_ai_whisper_catalog_name_is_priced_per_second() -> None: assert one_hour_cost == pytest.approx(AN_HOUR_IN_SECONDS * one_second_cost) +@pytest.mark.parametrize("catalog_name", CATALOG_NAMES) +def test_azure_ai_catalog_entry_source_and_backup_match(catalog_name: str) -> None: + main_entry = _cost_map_entry(MAIN_COST_MAP, catalog_name) + backup_entry = _cost_map_entry(BACKUP_COST_MAP, catalog_name) + + assert backup_entry == main_entry + + def test_azure_ai_model_router_spellings_share_one_entry() -> None: underscore_entry = _cost_map_entry(MAIN_COST_MAP, "model_router") hyphen_entry = _cost_map_entry(MAIN_COST_MAP, "model-router") diff --git a/tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py b/tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py new file mode 100644 index 00000000000..7ee34c6c55a --- /dev/null +++ b/tests/test_litellm/llms/cohere/ocr/test_cohere_parse_cost.py @@ -0,0 +1,28 @@ +from pathlib import Path + +import pytest + +import litellm +from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo + +REPO_ROOT = Path(__file__).parents[5] +COST_MAPS = [ + REPO_ROOT / "model_prices_and_context_window.json", + REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json", +] +MODELS = [("cohere/parse-v5.0", "cohere"), ("azure_ai/Cohere-parse-v5", "azure_ai")] + + +def _ocr_response(model: str, pages_processed: int) -> OCRResponse: + return OCRResponse( + pages=[OCRPage(index=i, markdown=f"page {i}") for i in range(pages_processed)], + model=model, + usage_info=OCRUsageInfo(pages_processed=pages_processed), + ) + + +@pytest.mark.parametrize("model, provider", MODELS) +def test_model_info_resolves_ocr_mode_and_price(local_model_cost_map, model: str, provider: str) -> None: + info = litellm.get_model_info(model=model, custom_llm_provider=provider) + + assert info["mode"] == "ocr" diff --git a/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py b/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py index f5d60dd0d32..afac7b0bc1a 100644 --- a/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py +++ b/tests/test_litellm/llms/databricks/test_databricks_cost_calculator.py @@ -1,3 +1,4 @@ +import json from decimal import Decimal from pathlib import Path from typing import Final @@ -162,6 +163,29 @@ def test_legacy_endpoint_names_still_resolve(local_model_cost_map: None) -> None assert completion_cost == pytest.approx(100 * info["output_cost_per_token"]) +@pytest.mark.parametrize("model", NEW_MODELS) +def test_new_models_carry_cache_pricing(local_model_cost_map: None, model: str) -> None: + info: Final = _model_info(model) + + assert info["input_cost_per_token"] > 0 + assert info["output_cost_per_token"] > 0 + assert info["cache_creation_input_token_cost"] > info["input_cost_per_token"] + assert info["cache_read_input_token_cost"] < info["input_cost_per_token"] + assert info["supports_prompt_caching"] is True + + +def test_every_priced_databricks_model_declares_cache_rates(local_model_cost_map: None) -> None: + undeclared: Final = [ + model + for model, info in litellm.model_cost.items() + if model.startswith("databricks/") + and info.get("input_cost_per_token") is not None + and any(info.get(field) is None for field in CACHE_FIELDS) + ] + + assert undeclared == [] + + def test_models_without_a_cache_discount_bill_cache_tokens_at_the_input_rate( local_model_cost_map: None, ) -> None: @@ -180,6 +204,33 @@ def test_models_without_a_cache_discount_bill_cache_tokens_at_the_input_rate( assert prompt_cost > 8000 * info["input_cost_per_token"] +def test_every_model_without_published_cache_dbu_bills_cache_at_its_own_input_rate( + local_model_cost_map: None, +) -> None: + without_published_rates: Final = [ + model + for model, info in litellm.model_cost.items() + if model.startswith("databricks/") + and info.get("input_cost_per_token") + and model not in PUBLISHED_DBU_PER_MILLION + ] + + for model in without_published_rates: + info = _model_info(model) + for field in CACHE_FIELDS: + assert info[field] == pytest.approx(info["input_cost_per_token"]), (model, field) + + +@pytest.mark.parametrize("model", NEW_MODELS) +def test_backup_price_map_matches_main(model: str) -> None: + main_cost: Final = json.loads(MAIN_PRICES.read_text()) + backup_cost: Final = json.loads(BACKUP_PRICES.read_text()) + + assert model in main_cost + assert model in backup_cost + assert backup_cost[model] == main_cost[model] + + def test_sonnet_5_ships_standard_rates_not_introductory(local_model_cost_map: None) -> None: sonnet_5: Final = _model_info("databricks/databricks-claude-sonnet-5") sonnet_4_6: Final = _model_info("databricks/databricks-claude-sonnet-4-6") diff --git a/tests/test_litellm/llms/databricks/test_databricks_pricing.py b/tests/test_litellm/llms/databricks/test_databricks_pricing.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py index f6018626bd0..6929cd48e60 100644 --- a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py +++ b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_cost_calculator.py @@ -22,6 +22,16 @@ def _usage(prompt_tokens: int, cached_tokens: int, completion_tokens: int) -> Us ) +def test_warm_call_cheaper_than_cold_call(): + prompt_tokens = 7036 + completion_tokens = 8 + + cold_prompt_cost, _ = cost_per_token(model=MODEL, usage=_usage(prompt_tokens, 16, completion_tokens)) + warm_prompt_cost, _ = cost_per_token(model=MODEL, usage=_usage(prompt_tokens, 7020, completion_tokens)) + + assert warm_prompt_cost < cold_prompt_cost + + OFF_PEAK_MODEL = "accounts/fireworks/models/off-peak-test" OFF_PEAK_WINDOW = "14:00-00:00" INSIDE_WINDOW = datetime(2026, 9, 3, 17, 25, tzinfo=timezone.utc) diff --git a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py new file mode 100644 index 00000000000..8d28ee921e1 --- /dev/null +++ b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py @@ -0,0 +1,54 @@ +""" +Regression test for Fireworks Kimi K2.5 / K2.6 / K2.7 context and output limits. + +Fireworks publishes a 262144-token context window for every Kimi K2.5, K2.6 and +K2.7 model, but caps generation well below that. A previous bulk edit had flattened +max_output_tokens/max_tokens to 262144 (equal to the context window), which let the +pre-call context-window check admit requests asking for a full 262144-token +completion that Fireworks then rejects. These assertions pin the corrected per-alias +limits so a future bulk edit can't silently flatten them again. +""" + +import json +from importlib.resources import files + +import pytest + +CONTEXT_WINDOW = 262144 +OUTPUT_LIMIT = 32768 + +KIMI_ALIASES = ( + "fireworks_ai/kimi-k2p5", + "fireworks_ai/kimi-k2p6", + "fireworks_ai/kimi-k2p6-fast", + "fireworks_ai/kimi-k2p7-code", + "fireworks_ai/kimi-k2p7-code-fast", + "fireworks_ai/accounts/fireworks/models/kimi-k2p5", + "fireworks_ai/accounts/fireworks/models/kimi-k2p6", + "fireworks_ai/accounts/fireworks/models/kimi-k2p7-code", + "fireworks_ai/accounts/fireworks/routers/kimi-k2p6-fast", + "fireworks_ai/accounts/fireworks/routers/kimi-k2p7-code-fast", +) + + +@pytest.fixture(scope="module") +def use_local_model_cost_map(): + monkeypatch = pytest.MonkeyPatch() + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + + import litellm + from litellm.utils import _invalidate_model_cost_lowercase_map + + original_model_cost = litellm.model_cost + litellm.model_cost = json.loads( + files("litellm").joinpath("model_prices_and_context_window_backup.json").read_text(encoding="utf-8") + ) + litellm.get_model_info.cache_clear() + _invalidate_model_cost_lowercase_map() + try: + yield litellm + finally: + litellm.model_cost = original_model_cost + litellm.get_model_info.cache_clear() + _invalidate_model_cost_lowercase_map() + monkeypatch.undo() diff --git a/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py b/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py new file mode 100644 index 00000000000..e3cf40b43f7 --- /dev/null +++ b/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py @@ -0,0 +1,40 @@ +""" +Cost tests for Mistral OCR models against the real litellm cost map +(no monkeypatching of get_model_info). These regress the pricing entries +for mistral-ocr-4-0 and mistral-ocr-latest, which now both resolve to +OCR 4 at $4 / 1000 pages. +""" + +from pathlib import Path + +from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo + +OCR4_COST_PER_PAGE = 0.004 +OCR4_ANNOTATION_COST_PER_PAGE = 0.005 + +REPO_ROOT = Path(__file__).parents[5] +MAIN_COST_MAP = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_COST_MAP = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +OCR3_MODEL = "mistral/mistral-ocr-2512" +OCR3_COST_PER_PAGE = 0.002 +OCR3_ANNOTATION_COST_PER_PAGE = 0.003 + +AZURE_DOC_AI_MODEL = "azure_ai/mistral-document-ai-2512" +AZURE_DOC_AI_COST_PER_PAGE = 0.003 + + +def _ocr_response(model: str, pages_processed: int) -> OCRResponse: + return OCRResponse( + pages=[OCRPage(index=i, markdown=f"page {i}") for i in range(pages_processed)], + model=model, + usage_info=OCRUsageInfo(pages_processed=pages_processed), + ) + + +def _annotated_ocr_response(model: str, pages_processed: int | None, annotation_pages: int) -> OCRResponse: + return OCRResponse( + pages=[], + model=model, + usage_info=OCRUsageInfo(pages_processed=pages_processed, pages_processed_annotation=annotation_pages), + ) diff --git a/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py b/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py index 80c06e4a1e0..947d9b73e1a 100644 --- a/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py +++ b/tests/test_litellm/llms/openai_like/test_scx_ai_provider.py @@ -154,6 +154,34 @@ class TestSCXAIModelMetadata: with open(json_path) as f: return json.load(f) + def test_scx_ai_models_registered_with_correct_metadata(self): + model_cost = self._load(("model_prices_and_context_window.json",)) + for model in self.SCX_MODELS: + info = model_cost.get(model) + assert info is not None, f"{model} missing from model_prices_and_context_window.json" + assert info["litellm_provider"] == "scx-ai" + assert info["mode"] == "chat" + assert info["input_cost_per_token"] > 0 + assert info["output_cost_per_token"] > 0 + assert info["supports_function_calling"] is True + assert info["supports_tool_choice"] is True + assert info["supports_reasoning"] is True + assert info["supports_response_schema"] is True + assert info.get("supports_vision", False) is (model in self.VISION_MODELS) + + assert info["supports_prompt_caching"] is True + assert 0 < info["cache_read_input_token_cost"] < info["input_cost_per_token"] + + assert info["max_tokens"] == info["max_output_tokens"] + assert info["max_input_tokens"] >= 1_000_000 + + def test_scx_ai_models_synced_to_backup(self): + model_cost = self._load(("model_prices_and_context_window.json",)) + backup = self._load(("litellm", "model_prices_and_context_window_backup.json")) + for model in self.SCX_MODELS: + assert model in backup, f"{model} missing from backup json" + assert backup[model] == model_cost[model], f"{model} differs between root and backup json" + class TestSCXAIDashboardRegistration: @staticmethod diff --git a/tests/test_litellm/llms/perplexity/test_perplexity_integration.py b/tests/test_litellm/llms/perplexity/test_perplexity_integration.py index bd72d9b4740..bbb9cdef5fd 100644 --- a/tests/test_litellm/llms/perplexity/test_perplexity_integration.py +++ b/tests/test_litellm/llms/perplexity/test_perplexity_integration.py @@ -17,6 +17,7 @@ from litellm import ModelResponse from litellm.cost_calculator import cost_per_token from litellm.llms.perplexity.chat.transformation import PerplexityChatConfig from litellm.types.utils import PromptTokensDetailsWrapper, Usage +from litellm.utils import get_model_info class TestPerplexityIntegration: @@ -55,6 +56,23 @@ class TestPerplexityIntegration: } } + def test_model_info_includes_custom_fields(self): + """Test that get_model_info returns the custom Perplexity cost fields.""" + model_info = get_model_info(model="sonar-deep-research", custom_llm_provider="perplexity") + + # Verify custom fields are included + required_fields = [ + "citation_cost_per_token", + "search_context_cost_per_query", + "input_cost_per_token", + "output_cost_per_token", + "output_cost_per_reasoning_token", + ] + + for field in required_fields: + assert field in model_info, f"Missing field: {field}" + assert model_info[field] is not None, f"Null value for field: {field}" + def test_various_citation_sizes(self): """Test cost calculation with various citation sizes.""" config = PerplexityChatConfig() diff --git a/tests/test_litellm/llms/tencent/test_cost_calculator.py b/tests/test_litellm/llms/tencent/test_cost_calculator.py new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/tests/test_litellm/llms/tencent/test_cost_calculator.py @@ -0,0 +1 @@ + diff --git a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py index 2d1e4305449..f6da1bbcd0e 100644 --- a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py +++ b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py @@ -452,6 +452,44 @@ def test_vertex_claude_completion_does_not_mutate_shared_extra_headers(): assert shared_extra_headers == {}, "extra_headers must not be mutated by completion()" +def test_messages_thinking_shape_follows_exact_vertex_entry_flag(local_model_cost_map, monkeypatch): + """The Vertex messages config must probe capabilities under ``vertex_ai`` so an + operator setting ``supports_adaptive_thinking: false`` on the exact + ``vertex_ai/claude-opus-4-8`` entry beats the unmodified ``anthropic`` entry. + With the inherited ``"anthropic"`` provider default the flip was ignored and + the transform kept emitting ``thinking.type='adaptive'``.""" + import litellm + + config = VertexAIPartnerModelsAnthropicMessagesConfig() + + def transform(): + return config.transform_anthropic_messages_request( + model="claude-opus-4-8", + messages=[{"role": "user", "content": "Hello"}], + anthropic_messages_optional_request_params={ + "max_tokens": 4096, + "reasoning_effort": "medium", + }, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + result = transform() + assert result.get("thinking") == {"type": "adaptive", "display": "summarized"} + assert result.get("output_config") == {"effort": "medium"} + + monkeypatch.setitem(litellm.model_cost["vertex_ai/claude-opus-4-8"], "supports_adaptive_thinking", False) + litellm.get_model_info.cache_clear() + assert litellm.model_cost["claude-opus-4-8"]["supports_adaptive_thinking"] is True + + flipped = transform() + thinking = flipped.get("thinking") + assert isinstance(thinking, dict) + assert thinking.get("type") == "enabled" + assert isinstance(thinking.get("budget_tokens"), int) + assert "output_config" not in flipped + + def _vertex_transform(model, messages, system=None): config = VertexAIPartnerModelsAnthropicMessagesConfig() params = {"max_tokens": 256} @@ -547,6 +585,10 @@ class TestVertexAnthropicMidConversationSystem: def test_vertex_claude_4_8_plus_cost_map_entries_carry_mid_conversation_system_flag(): + """Exact cost-map hits win over the ``claude-mid-conversation-system`` + fallback rule, so a ``vertex_ai`` Claude 4.8+/5 entry missing the flag would + be treated as unsupported and hoist every reminder, collapsing the prompt + cache. Every mapped vertex_ai entry the rule matches must carry the flag.""" import re import litellm diff --git a/tests/test_litellm/llms/xai/test_xai_model_registry.py b/tests/test_litellm/llms/xai/test_xai_model_registry.py new file mode 100644 index 00000000000..a455d1fb233 --- /dev/null +++ b/tests/test_litellm/llms/xai/test_xai_model_registry.py @@ -0,0 +1,55 @@ +""" +Registry regression tests for xAI entries in the model cost map. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).parents[4] +PRICES_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PRICES_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +# https://docs.x.ai/developers/model-capabilities/text/multi-agent +# "The multi-agent model does not work with the OpenAI Chat Completions API." +RESPONSES_ONLY_MODELS = ( + "xai/grok-4.20-multi-agent-0309", + "xai/grok-4.20-multi-agent-beta-0309", +) + +MAP_PATHS = (PRICES_PATH, BACKUP_PRICES_PATH) + + +@pytest.fixture(scope="module", params=[p.name for p in MAP_PATHS]) +def cost_map(request: pytest.FixtureRequest) -> dict: + path = next(p for p in MAP_PATHS if p.name == request.param) + return json.loads(path.read_text(encoding="utf-8")) + + +@pytest.mark.parametrize("model", RESPONSES_ONLY_MODELS) +def test_multi_agent_models_are_responses_only(cost_map: dict, model: str): + entry = cost_map[model] + assert entry["supported_endpoints"] == ["/v1/responses"] + assert entry["mode"] == "responses" + + +def test_surviving_xai_chat_models_still_serve_chat_completions(cost_map: dict): + """Guard against the removal above over-reaching into live models.""" + chat_models = [ + key + for key, value in cost_map.items() + if isinstance(value, dict) and value.get("litellm_provider") == "xai" and value.get("mode") == "chat" + ] + assert "xai/grok-4.3" in chat_models + assert "xai/grok-4.6" in chat_models + + +def test_both_cost_maps_agree_on_xai_entries(): + prices = json.loads(PRICES_PATH.read_text(encoding="utf-8")) + backup = json.loads(BACKUP_PRICES_PATH.read_text(encoding="utf-8")) + xai_keys = {k for k, v in prices.items() if isinstance(v, dict) and v.get("litellm_provider") == "xai"} + assert xai_keys + assert {k: prices[k] for k in xai_keys} == {k: backup[k] for k in xai_keys} diff --git a/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py b/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py index 9734ea3e545..4c8231d357e 100644 --- a/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py +++ b/tests/test_litellm/llms/xai/test_xai_redirected_slug_pricing.py @@ -98,3 +98,23 @@ def test_redirected_slug_carries_the_target_tier_rates(cost_map: dict, slug: str for field in TIER_COST_FIELDS: assert entry[field] == target[field], field assert {k for k in entry if "_above_" in k} == {k for k in target if "_above_" in k} + + +def test_both_cost_maps_agree_on_the_redirected_slugs(): + prices = json.loads(PRICES_PATH.read_text(encoding="utf-8")) + backup = json.loads(BACKUP_PRICES_PATH.read_text(encoding="utf-8")) + for slug in (*REDIRECTED_SLUGS, *CODE_SLUGS, REDIRECT_TARGET, CODE_REDIRECT_TARGET): + assert prices[slug] == backup[slug], slug + + +def test_every_retired_chat_slug_is_covered(cost_map: dict): + """The lists above must stay in step with what the registry marks retired.""" + marked = { + key + for key, entry in cost_map.items() + if isinstance(entry, dict) + and entry.get("litellm_provider") == "xai" + and "deprecation_date" in entry + and entry.get("mode") == "chat" + } + assert marked == {*REDIRECTED_SLUGS, *CODE_SLUGS} diff --git a/tests/test_litellm/proxy/spend_tracking/test_savings.py b/tests/test_litellm/proxy/spend_tracking/test_savings.py index 408a394a105..792c44a025b 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_savings.py +++ b/tests/test_litellm/proxy/spend_tracking/test_savings.py @@ -327,6 +327,29 @@ def test_openai_style_cache_write_tokens_are_netted_out(): ) +def test_sub_input_cache_write_price_is_an_extra_saving(): + """A few models price writes below input; there the premium is a real credit. + + Clamping the premium at zero would silently undercount these, so the subtraction + stays signed. ``azure/eu/gpt-4o-2024-11-20`` ships a write price at ~0.5x input. + """ + model = "azure/eu/gpt-4o-2024-11-20" + info = litellm.get_model_info(model=model) + input_cost = info["input_cost_per_token"] + cheap_write = info["cache_creation_input_token_cost"] + assert 0 < cheap_write < input_cost, "fixture drifted: this test needs a model pricing cache writes below input" + + result = compute_savings_spend( + model=model, + custom_llm_provider=None, + compression_saved_tokens=0, + gateway_injected_cache=True, + usage_object=_caching_usage(read=1000, written=4000), + ) + assert result.prompt_caching == pytest.approx(4000 * (input_cost - cheap_write)) + assert result.prompt_caching > 0 + + def test_negative_cache_write_count_clamps_to_zero(): """A malformed negative write count must not be read as a saving.""" input_cost, cache_read_cost = _anthropic_costs("claude-sonnet-5") diff --git a/tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py b/tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py new file mode 100644 index 00000000000..9d9f392a149 --- /dev/null +++ b/tests/test_litellm/test_azure_ai_grok_4_3_model_metadata.py @@ -0,0 +1,37 @@ +import json +from pathlib import Path + +import pytest + +import litellm +from litellm import get_model_info + +AZURE_AI_GROK_4_3_MODEL = "azure_ai/grok-4.3" +AZURE_AI_GROK_4_3_SOURCE = "https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/introducing-grok-4-3-on-microsoft-foundry-latest-generation-agentic-capabilities/4517096" + + +def _load_model_cost(path: Path) -> dict: + with open(path) as f: + return json.load(f) + + +@pytest.fixture(autouse=True) +def reload_model_costs(): + original_model_cost = litellm.model_cost + json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" + litellm.model_cost = _load_model_cost(json_path) + get_model_info.cache_clear() + yield + litellm.model_cost = original_model_cost + get_model_info.cache_clear() + + +def test_azure_ai_grok_4_3_backup_matches_main(): + repo_root = Path(__file__).parents[2] + main_path = repo_root / "model_prices_and_context_window.json" + backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" + + main_cost = _load_model_cost(main_path) + backup_cost = _load_model_cost(backup_path) + + assert backup_cost.get(AZURE_AI_GROK_4_3_MODEL) == main_cost.get(AZURE_AI_GROK_4_3_MODEL) diff --git a/tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py b/tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py new file mode 100644 index 00000000000..43df9a648c2 --- /dev/null +++ b/tests/test_litellm/test_azure_ai_grok_4_6_model_metadata.py @@ -0,0 +1,44 @@ +from pathlib import Path +from typing import Final + +import pytest +from pydantic import TypeAdapter + +from litellm import cost_per_token, get_model_info +from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider + +REPO_ROOT: Final = Path(__file__).parents[2] +MODEL: Final = "azure_ai/grok-4.6" +COST_MAP_ADAPTER: Final = TypeAdapter(dict[str, dict[str, object]]) + + +def _cost_map_entry(path: Path) -> dict[str, object]: + return COST_MAP_ADAPTER.validate_json(path.read_bytes())[MODEL] + + +@pytest.mark.usefixtures("local_model_cost_map") +def test_azure_ai_grok_4_6_is_priced_and_routed() -> None: + routed_model, provider, _, _ = get_llm_provider(model=MODEL) + assert (routed_model, provider) == ("grok-4.6", "azure_ai") + + info = get_model_info(model=routed_model, custom_llm_provider=provider) + assert info["litellm_provider"] == "azure_ai" + assert info["mode"] == "chat" + assert info["supports_function_calling"] is True + assert info["supports_prompt_caching"] is True + assert info["supports_reasoning"] is True + assert info["supports_response_schema"] is True + assert info["supports_tool_choice"] is True + assert info["supports_vision"] is True + assert info["supports_web_search"] is True + + prompt_cost, completion_cost = cost_per_token(model=MODEL, prompt_tokens=1_000_000, completion_tokens=1_000_000) + assert prompt_cost > 0 + assert completion_cost > 0 + + +def test_azure_ai_grok_4_6_entry_source_and_backup_match() -> None: + main_entry = _cost_map_entry(REPO_ROOT / "model_prices_and_context_window.json") + backup_entry = _cost_map_entry(REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json") + + assert backup_entry == main_entry diff --git a/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py b/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py index 94afd9fe254..31f3a67beac 100644 --- a/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py +++ b/tests/test_litellm/test_baseten_glm_5_3_model_metadata.py @@ -1,10 +1,31 @@ +import json +from pathlib import Path + import pytest import litellm +from litellm.utils import supports_function_calling, supports_prompt_caching + +REPO_ROOT = Path(__file__).parents[2] +MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +MODEL = "baseten/zai-org/GLM-5.3" + +INPUT_COST = 1.4e-06 +CACHED_INPUT_COST = 1.4e-07 +OUTPUT_COST = 4.4e-06 + + +def _load(path): + with open(path) as f: + return json.load(f) @pytest.fixture def local_model_cost_map(monkeypatch): + """Force get_model_info to resolve against the in-repo cost map instead of the + remote one fetched at import time, which still carries the pre-merge registry.""" monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) litellm.get_model_info.cache_clear() @@ -12,6 +33,32 @@ def local_model_cost_map(monkeypatch): litellm.get_model_info.cache_clear() +def test_baseten_glm_5_3_capabilities_are_visible_to_callers(local_model_cost_map): + """The entry advertises prompt caching and tool calling, so the helpers every + caller checks before sending a request must say so too.""" + assert supports_prompt_caching(model=MODEL) is True + assert supports_function_calling(model=MODEL) is True + + info = litellm.get_model_info(model="zai-org/GLM-5.3", custom_llm_provider="baseten") + assert info["max_input_tokens"] > 0 + assert info["max_output_tokens"] > 0 + + +def test_backup_matches_main(): + """Ensure the bundled (backup) cost map stays in sync with the canonical file. + + Both keys are asserted present first: comparing two ``.get`` results alone passes + just as happily when neither file has the entry at all, which is the exact state + this test exists to catch. + """ + main_cost = _load(MAIN_PATH) + backup_cost = _load(BACKUP_PATH) + + assert MODEL in main_cost, f"{MODEL} missing from model_prices_and_context_window.json" + assert MODEL in backup_cost, f"{MODEL} missing from model_prices_and_context_window_backup.json" + assert backup_cost[MODEL] == main_cost[MODEL], f"{MODEL} differs between main and backup model cost maps" + + def test_entry_advertises_only_what_the_baseten_path_accepts(local_model_cost_map): """The Baseten path rejects unsupported request parameters.""" supported = litellm.get_supported_openai_params(model="zai-org/GLM-5.3", custom_llm_provider="baseten") diff --git a/tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py b/tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py new file mode 100644 index 00000000000..1a0e1665556 --- /dev/null +++ b/tests/test_litellm/test_bedrock_marengo_embed_3_model_metadata.py @@ -0,0 +1,52 @@ +import json +from pathlib import Path + +import pytest + +import litellm +from litellm.constants import bedrock_embedding_models + +REPO_ROOT = Path(__file__).parents[2] +MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +BASE_MODEL = "twelvelabs.marengo-embed-3-0-v1:0" +PROFILE_MODELS = ("us.twelvelabs.marengo-embed-3-0-v1:0", "eu.twelvelabs.marengo-embed-3-0-v1:0") +ALL_MODELS = (BASE_MODEL, *PROFILE_MODELS) +MARENGO_2_7_MODELS = ( + "twelvelabs.marengo-embed-2-7-v1:0", + "us.twelvelabs.marengo-embed-2-7-v1:0", + "eu.twelvelabs.marengo-embed-2-7-v1:0", +) +PER_REQUEST_MODELS = (*ALL_MODELS, *MARENGO_2_7_MODELS) + +TEXT_REQUEST_COST = 7e-05 +IMAGE_REQUEST_COST = 0.0001 +VIDEO_COST_PER_SECOND = 0.0007 +AUDIO_COST_PER_SECOND = 0.00014 + + +def _load(path): + with open(path) as f: + return json.load(f) + + +@pytest.mark.parametrize("model", ALL_MODELS) +def test_marengo_embed_3_is_visible_to_callers(model, local_model_cost_map): + info = litellm.get_model_info(model=model, custom_llm_provider="bedrock") + assert info["mode"] == "embedding" + assert info["output_vector_size"] == 512 + + +def test_marengo_embed_3_is_a_known_bedrock_embedding_model(): + assert BASE_MODEL in bedrock_embedding_models + + +@pytest.mark.parametrize("model", PER_REQUEST_MODELS) +def test_backup_matches_main(model): + main_cost = _load(MAIN_PATH) + backup_cost = _load(BACKUP_PATH) + + assert model in main_cost, f"{model} missing from model_prices_and_context_window.json" + assert model in backup_cost, f"{model} missing from model_prices_and_context_window_backup.json" + assert backup_cost[model] == main_cost[model], f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_bedrock_usgov_pricing.py b/tests/test_litellm/test_bedrock_usgov_pricing.py index b83176b6460..a3a7fc4ed7a 100644 --- a/tests/test_litellm/test_bedrock_usgov_pricing.py +++ b/tests/test_litellm/test_bedrock_usgov_pricing.py @@ -31,6 +31,18 @@ def model_data(): return json.load(f) +def test_usgov_east_haiku_profile_mirrors_in_region_row(model_data): + """us-gov-east-1 serves claude-3-haiku through the us-gov. inference profile + only, so the profile row must bill exactly like the in-region gov row. + """ + profile = model_data["us-gov.anthropic.claude-3-haiku-20240307-v1:0"] + in_region = model_data["bedrock/us-gov-east-1/anthropic.claude-3-haiku-20240307-v1:0"] + assert profile["litellm_provider"] == "bedrock_converse" + assert {k: v for k, v in profile.items() if k != "litellm_provider"} == { + k: v for k, v in in_region.items() if k != "litellm_provider" + } + + GOV_ROW_SOURCES = { "us-gov.anthropic.claude-fable-5-1": "anthropic.claude-fable-5-1", "bedrock/us-gov-west-1/anthropic.claude-fable-5-1": "anthropic.claude-fable-5-1", diff --git a/tests/test_litellm/test_claude_fable_5_config.py b/tests/test_litellm/test_claude_fable_5_config.py index 25327eb9430..4b03848da2c 100644 --- a/tests/test_litellm/test_claude_fable_5_config.py +++ b/tests/test_litellm/test_claude_fable_5_config.py @@ -12,7 +12,10 @@ shape, which Fable 5 rejects with a 400. import json import os +import pytest + from litellm.constants import BEDROCK_CONVERSE_MODELS +from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap REPO_ROOT = os.path.join(os.path.dirname(__file__), "../..") @@ -23,10 +26,88 @@ def _load_root_cost_map() -> dict: return json.load(f) +def test_fable_5_present_in_bundled_backup(): + """The bundled backup is the runtime fallback (and what tests load with + ``LITELLM_LOCAL_MODEL_COST_MAP=True``) — it must carry the same entries as + the root cost map, otherwise the model resolves on one path but not the + other.""" + backup = GetModelCostMap.load_local_model_cost_map() + root = _load_root_cost_map() + for model_name in ( + "claude-fable-5", + "anthropic.claude-fable-5", + "global.anthropic.claude-fable-5", + "us.anthropic.claude-fable-5", + "eu.anthropic.claude-fable-5", + "vertex_ai/claude-fable-5", + "vertex_ai/claude-fable-5@default", + "azure_ai/claude-fable-5", + ): + assert model_name in backup, f"Missing from backup cost map: {model_name}" + assert backup[model_name] == root[model_name], model_name + + def test_fable_5_registered_for_bedrock_converse(): assert "anthropic.claude-fable-5" in BEDROCK_CONVERSE_MODELS +@pytest.mark.parametrize( + "cost_map", + [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], + ids=["root", "bundled_backup"], +) +def test_fable_5_all_variants_carry_adaptive_thinking_flag(cost_map): + """Every Fable 5 entry must advertise ``supports_adaptive_thinking``. + + Adaptive-thinking detection is cost-map driven, so a single variant missing + the flag silently sends the legacy ``thinking.type='enabled'`` shape and the + provider 400s (issue #29188 for the Opus 4.8 equivalent). Fable 5 is even + stricter than Opus 4.8: an explicit ``thinking.type='disabled'`` also 400s, + so adaptive is the only valid thinking shape LiteLLM can emit for it.""" + variants = [k for k in cost_map if "claude-fable-5" in k] + assert variants, "no claude-fable-5 entries found in cost map" + missing = [k for k in variants if cost_map[k].get("supports_adaptive_thinking") is not True] + assert not missing, f"missing supports_adaptive_thinking: {missing}" + + +@pytest.mark.parametrize( + "cost_map", + [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], + ids=["root", "bundled_backup"], +) +def test_fable_5_all_variants_carry_thinking_always_on_flag(cost_map): + """Every Fable 5 entry must advertise ``thinking_always_on``. + + The flag drives the Anthropic transformations to omit an explicit + ``thinking.type='disabled'``, which Fable 5 rejects with a 400; a variant + missing the flag forwards the param verbatim and the provider 400s.""" + variants = [k for k in cost_map if "claude-fable-5" in k] + assert variants, "no claude-fable-5 entries found in cost map" + missing = [k for k in variants if cost_map[k].get("thinking_always_on") is not True] + assert not missing, f"missing thinking_always_on: {missing}" + + +@pytest.mark.parametrize( + "model", + [ + "claude-fable-5", + "anthropic/claude-fable-5", + "anthropic.claude-fable-5", + "bedrock/us.anthropic.claude-fable-5", + "bedrock/invoke/eu.anthropic.claude-fable-5", + "bedrock/global.anthropic.claude-fable-5", + "vertex_ai/claude-fable-5", + "azure_ai/claude-fable-5", + ], +) +def test_adaptive_thinking_detected_for_fable_5(local_model_cost_map, model): + """Provider-routed ids must resolve to a flagged entry so ``reasoning_effort`` + maps to ``thinking.type='adaptive'`` + ``output_config.effort``.""" + from litellm.llms.anthropic.common_utils import AnthropicModelInfo + + assert AnthropicModelInfo._is_adaptive_thinking_model(model, "anthropic") is True + + FABLE_5_1_VARIANTS = ( "claude-fable-5-1", "anthropic.claude-fable-5-1", @@ -39,5 +120,53 @@ FABLE_5_1_VARIANTS = ( ) +def test_fable_5_1_present_in_bundled_backup(): + backup = GetModelCostMap.load_local_model_cost_map() + root = _load_root_cost_map() + for model_name in FABLE_5_1_VARIANTS: + assert model_name in backup, f"Missing from backup cost map: {model_name}" + assert backup[model_name] == root[model_name], model_name + + def test_fable_5_1_registered_for_bedrock_converse(): assert "anthropic.claude-fable-5-1" in BEDROCK_CONVERSE_MODELS + + +@pytest.mark.parametrize( + "model", + [ + "claude-fable-5-1", + "anthropic/claude-fable-5-1", + "anthropic.claude-fable-5-1", + "bedrock/us.anthropic.claude-fable-5-1", + "bedrock/invoke/eu.anthropic.claude-fable-5-1", + "bedrock/global.anthropic.claude-fable-5-1", + "vertex_ai/claude-fable-5-1", + "azure_ai/claude-fable-5-1", + ], +) +def test_adaptive_thinking_detected_for_fable_5_1(local_model_cost_map, model): + from litellm.llms.anthropic.common_utils import AnthropicModelInfo + + assert AnthropicModelInfo._is_adaptive_thinking_model(model, "anthropic") is True + + +@pytest.mark.parametrize( + "cost_map", + [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], + ids=["root", "bundled_backup"], +) +def test_sampling_params_flag_on_all_models_that_removed_them(cost_map): + """Fable 5 and Opus 4.7/4.8 reject ``top_p``/``top_k``/``temperature != 1``; + the drop/raise gating is cost-map driven, so every variant must carry an + explicit ``supports_sampling_params: false``. The perplexity route is + exempt: it is OpenAI-compatible and maps sampling params upstream.""" + variants = [ + k + for k in cost_map + if any(v in k for v in ("claude-fable-5", "claude-opus-4-7", "claude-opus-4-8")) + and not k.startswith("perplexity/") + ] + assert variants, "no matching entries found in cost map" + missing = [k for k in variants if cost_map[k].get("supports_sampling_params") is not False] + assert not missing, f"missing supports_sampling_params=false: {missing}" diff --git a/tests/test_litellm/test_claude_haiku_4_5_config.py b/tests/test_litellm/test_claude_haiku_4_5_config.py new file mode 100644 index 00000000000..d0b7f4f8a2c --- /dev/null +++ b/tests/test_litellm/test_claude_haiku_4_5_config.py @@ -0,0 +1,46 @@ +""" +Test Claude Haiku 4.5 model configurations for Bedrock +https://github.com/BerriAI/litellm/issues/15818 +""" + +import json +import os + + +def test_bedrock_haiku_4_5_matches_sonnet_capabilities(): + """ + Test that Haiku 4.5 has same capabilities as Sonnet 4.5 + (including computer_use, vision, tools, etc.) + """ + # Load model configuration + json_path = os.path.join(os.path.dirname(__file__), "../../model_prices_and_context_window.json") + with open(json_path) as f: + model_data = json.load(f) + + haiku_model = "us.anthropic.claude-haiku-4-5-20251001-v1:0" + sonnet_model = "us.anthropic.claude-sonnet-4-5-20250929-v1:0" + + haiku_info = model_data[haiku_model] + sonnet_info = model_data[sonnet_model] + + # Both should use bedrock_converse + assert haiku_info["litellm_provider"] == "bedrock_converse" + assert sonnet_info["litellm_provider"] == "bedrock_converse" + + # Shared capabilities that should match + shared_capabilities = [ + "supports_vision", + "supports_computer_use", + "supports_function_calling", + "supports_tool_choice", + "supports_prompt_caching", + "supports_response_schema", + "supports_pdf_input", + "supports_assistant_prefill", + "supports_reasoning", + ] + + for capability in shared_capabilities: + assert haiku_info.get(capability) == sonnet_info.get(capability), ( + f"Capability {capability} mismatch: Haiku={haiku_info.get(capability)}, Sonnet={sonnet_info.get(capability)}" + ) diff --git a/tests/test_litellm/test_claude_opus_5_config.py b/tests/test_litellm/test_claude_opus_5_config.py index 5f3e23fc18a..07e493af914 100644 --- a/tests/test_litellm/test_claude_opus_5_config.py +++ b/tests/test_litellm/test_claude_opus_5_config.py @@ -18,6 +18,7 @@ import os import pytest from litellm.constants import BEDROCK_CONVERSE_MODELS +from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap REPO_ROOT = os.path.join(os.path.dirname(__file__), "../..") @@ -61,5 +62,31 @@ def test_opus_5_bedrock_rejects_strict_tools(model_name, local_model_cost_map): assert bedrock_converse_supports_strict_tools(model_name) is False +def test_opus_5_present_in_bundled_backup(): + """The bundled backup is the runtime fallback (and what tests load with + ``LITELLM_LOCAL_MODEL_COST_MAP=True``); it must carry the same entries as the + root cost map, otherwise the model resolves on one path but not the other.""" + backup = GetModelCostMap.load_local_model_cost_map() + for model_name in ALL_OPUS_5_VARIANTS: + assert model_name in backup, f"Missing from backup cost map: {model_name}" + + def test_opus_5_registered_for_bedrock_converse(): assert "anthropic.claude-opus-5" in BEDROCK_CONVERSE_MODELS + + +@pytest.mark.parametrize( + "cost_map", + [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], + ids=["root", "bundled_backup"], +) +def test_opus_5_all_variants_carry_adaptive_thinking_flag(cost_map): + """Every Opus 5 entry must advertise ``supports_adaptive_thinking``. + + Adaptive-thinking detection is cost-map driven, so a single variant missing + the flag silently sends the legacy ``thinking.type='enabled'`` shape, which + Opus 5 rejects with a 400.""" + variants = [k for k in cost_map if "claude-opus-5" in k] + assert variants, "no claude-opus-5 entries found in cost map" + missing = [k for k in variants if cost_map[k].get("supports_adaptive_thinking") is not True] + assert not missing, f"missing supports_adaptive_thinking: {missing}" diff --git a/tests/test_litellm/test_claude_sonnet_5_config.py b/tests/test_litellm/test_claude_sonnet_5_config.py index 18273f7494a..8c6d2cd1851 100644 --- a/tests/test_litellm/test_claude_sonnet_5_config.py +++ b/tests/test_litellm/test_claude_sonnet_5_config.py @@ -13,7 +13,10 @@ populate ``litellm.anthropic_models`` at import, which is what lets a bare import json import os +import pytest + from litellm.constants import BEDROCK_CONVERSE_MODELS +from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap REPO_ROOT = os.path.join(os.path.dirname(__file__), "../..") @@ -37,5 +40,31 @@ def _load_root_cost_map() -> dict: return json.load(f) +def test_sonnet_5_present_in_bundled_backup(): + """The bundled backup is the runtime fallback (and what tests load with + ``LITELLM_LOCAL_MODEL_COST_MAP=True``); it must carry the same entries as the + root cost map, otherwise the model resolves on one path but not the other.""" + backup = GetModelCostMap.load_local_model_cost_map() + for model_name in ALL_SONNET_5_VARIANTS: + assert model_name in backup, f"Missing from backup cost map: {model_name}" + + def test_sonnet_5_registered_for_bedrock_converse(): assert "anthropic.claude-sonnet-5" in BEDROCK_CONVERSE_MODELS + + +@pytest.mark.parametrize( + "cost_map", + [_load_root_cost_map(), GetModelCostMap.load_local_model_cost_map()], + ids=["root", "bundled_backup"], +) +def test_sonnet_5_all_variants_carry_adaptive_thinking_flag(cost_map): + """Every Sonnet 5 entry must advertise ``supports_adaptive_thinking``. + + Adaptive-thinking detection is cost-map driven, so a single variant missing + the flag silently sends the legacy ``thinking.type='enabled'`` shape and the + provider 400s. This guards against a future variant being added without it.""" + variants = [k for k in cost_map if "claude-sonnet-5" in k] + assert variants, "no claude-sonnet-5 entries found in cost map" + missing = [k for k in variants if cost_map[k].get("supports_adaptive_thinking") is not True] + assert not missing, f"missing supports_adaptive_thinking: {missing}" diff --git a/tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py b/tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py new file mode 100644 index 00000000000..4e770be7c3e --- /dev/null +++ b/tests/test_litellm/test_cloudflare_workers_ai_model_metadata.py @@ -0,0 +1,50 @@ +""" +Regression tests for the Cloudflare Workers AI text-generation catalog in the +model-cost map. + +The Cloudflare list was badly stale (only 4 ancient entries). These tests pin +the newly added current Workers AI models (sourced from Cloudflare's live +``/ai/models/search?task=Text Generation`` catalog) and guard against the root +``model_prices_and_context_window.json`` and the bundled +``litellm/model_prices_and_context_window_backup.json`` drifting out of sync for +the ``cloudflare/`` namespace. +""" + +import json +import os + +import pytest + +import litellm + +ROOT_MAP = os.path.join( + os.path.dirname(os.path.dirname(litellm.__file__)), + "model_prices_and_context_window.json", +) +BACKUP_MAP = os.path.join( + os.path.dirname(litellm.__file__), + "model_prices_and_context_window_backup.json", +) + + +def _load(path: str) -> dict: + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def _cloudflare_keys(data: dict) -> set: + return {k for k in data if k.startswith("cloudflare/")} + + +def test_root_and_backup_have_identical_cloudflare_keys(): + if not os.path.exists(ROOT_MAP): + pytest.skip("root cost map only ships in source checkouts") + assert _cloudflare_keys(_load(ROOT_MAP)) == _cloudflare_keys(_load(BACKUP_MAP)) + + +def test_root_and_backup_cloudflare_entries_are_byte_for_byte_equal(): + if not os.path.exists(ROOT_MAP): + pytest.skip("root cost map only ships in source checkouts") + root = {k: v for k, v in _load(ROOT_MAP).items() if k.startswith("cloudflare/")} + backup = {k: v for k, v in _load(BACKUP_MAP).items() if k.startswith("cloudflare/")} + assert root == backup diff --git a/tests/test_litellm/test_command_r7b_pricing.py b/tests/test_litellm/test_command_r7b_pricing.py new file mode 100644 index 00000000000..c091fec313e --- /dev/null +++ b/tests/test_litellm/test_command_r7b_pricing.py @@ -0,0 +1,53 @@ +""" +Regression test: ``command-r7b-12-2024`` had its input/output per-token +costs transposed in the model-cost maps (input=1.5e-07 / output=3.75e-08), +even though Cohere publishes $0.0375/1M input and $0.15/1M output, i.e. +output is ~4x input like every other ``command-r`` entry. + +These tests pin the corrected values in both the primary price map and the +``litellm/`` backup, and verify ``get_model_info`` surfaces them, so the +swap cannot silently regress. +""" + +import json +import os + +import litellm + +MODEL = "command-r7b-12-2024" +EXPECTED_INPUT_COST = 3.75e-08 +EXPECTED_OUTPUT_COST = 1.5e-07 + + +def _load_json(path: str) -> dict: + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def _backup_path() -> str: + return os.path.join( + os.path.dirname(litellm.__file__), + "model_prices_and_context_window_backup.json", + ) + + +def _main_path() -> str: + # This test lives at ``tests/test_litellm/``; the primary price map sits at + # the repo root, two directories up. Resolve it relative to this file so the + # test works regardless of where ``litellm`` itself is installed (e.g. a pip + # install into site-packages). + return os.path.join( + os.path.dirname(__file__), + "..", + "..", + "model_prices_and_context_window.json", + ) + + +class TestCommandR7bPricingData: + """The JSON price maps must carry Cohere's published costs, with output + more expensive than input.""" + + +class TestCommandR7bPricingModelInfo: + """``get_model_info`` must report the corrected, un-swapped costs.""" diff --git a/tests/test_litellm/test_daybreak_model_metadata.py b/tests/test_litellm/test_daybreak_model_metadata.py index 58f9ff4e7c8..79149b84f0b 100644 --- a/tests/test_litellm/test_daybreak_model_metadata.py +++ b/tests/test_litellm/test_daybreak_model_metadata.py @@ -32,6 +32,13 @@ def _load(path): return json.load(f) +def test_blue_alias_matches_its_snapshot_computer_use(): + cost_map = _load(MAIN_PATH) + + assert cost_map[BLUE_ALIAS]["supports_computer_use"] is True + assert cost_map[BLUE_SNAPSHOT]["supports_computer_use"] is True + + @pytest.mark.parametrize(("alias", "snapshot"), OFFICIAL_ALIAS_SNAPSHOTS) def test_official_alias_tracks_snapshot(alias, snapshot): cost_map = _load(MAIN_PATH) @@ -44,3 +51,11 @@ def test_official_alias_tracks_snapshot(alias, snapshot): field: snapshot_info.get(field) for field in PRICE_FIELDS } assert alias_info["max_output_tokens"] == snapshot_info["max_output_tokens"] + + +@pytest.mark.parametrize("model", (*DAYBREAK_MODELS, BLUE_SNAPSHOT, *(alias for alias, _ in OFFICIAL_ALIAS_SNAPSHOTS))) +def test_backup_matches_main(model): + main_cost = _load(MAIN_PATH) + backup_cost = _load(BACKUP_PATH) + + assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_deepseek_model_metadata.py b/tests/test_litellm/test_deepseek_model_metadata.py index e8a98094c4e..264f5e65fc5 100644 --- a/tests/test_litellm/test_deepseek_model_metadata.py +++ b/tests/test_litellm/test_deepseek_model_metadata.py @@ -15,6 +15,7 @@ import os import litellm from litellm.utils import ( _supports_factory, + supports_response_schema, ) # --------------------------------------------------------------------------- @@ -36,6 +37,18 @@ class TestDeepSeekModelCostEntries: """Verify that provider-prefixed DeepSeek entries contain the same capability flags as their bare-name counterparts in the JSON files.""" + def test_deepseek_chat_max_input_tokens_matches_bare_in_backup(self): + data = _load_backup_json() + bare = data.get("deepseek-chat", {}) + prefixed = data.get("deepseek/deepseek-chat", {}) + assert prefixed.get("max_input_tokens") == bare.get("max_input_tokens") + + def test_deepseek_reasoner_max_output_tokens_matches_bare_in_backup(self): + data = _load_backup_json() + bare = data.get("deepseek-reasoner", {}) + prefixed = data.get("deepseek/deepseek-reasoner", {}) + assert prefixed.get("max_output_tokens") == bare.get("max_output_tokens") + # --------------------------------------------------------------------------- # API-level tests – verify supports_response_schema returns True @@ -46,6 +59,18 @@ class TestSupportsResponseSchemaDeepSeek: """All calling conventions for DeepSeek should return True for ``supports_response_schema``.""" + def test_provider_slash_model(self): + assert supports_response_schema(model="deepseek/deepseek-chat") is True + + def test_explicit_provider(self): + assert supports_response_schema(model="deepseek-chat", custom_llm_provider="deepseek") is True + + def test_reasoner_provider_slash_model(self): + assert supports_response_schema(model="deepseek/deepseek-reasoner") is True + + def test_reasoner_explicit_provider(self): + assert supports_response_schema(model="deepseek-reasoner", custom_llm_provider="deepseek") is True + # --------------------------------------------------------------------------- # Fallback-logic test – bare model entry used when prefixed is incomplete diff --git a/tests/test_litellm/test_fireworks_serverless_model_costs.py b/tests/test_litellm/test_fireworks_serverless_model_costs.py index 0b55b0ff1e4..164f32fec1c 100644 --- a/tests/test_litellm/test_fireworks_serverless_model_costs.py +++ b/tests/test_litellm/test_fireworks_serverless_model_costs.py @@ -14,15 +14,7 @@ import os import pytest -NEW_ENTRIES = { - "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813": { - "input_cost_per_token": 1.32e-06, - "cache_read_input_token_cost": 4.4e-08, - "output_cost_per_token": 3.96e-06, - "max_input_tokens": 1048576, - "max_output_tokens": 131072, - }, -} +from litellm.utils import get_model_info @pytest.fixture(scope="module") @@ -32,20 +24,17 @@ def model_data(): return json.load(f) -TWIN_PINNED_PRICES = { - "deepseek-v4-flash-0731": { - "input_cost_per_token": 2.2e-07, - "cache_read_input_token_cost": 7e-09, - "output_cost_per_token": 6.6e-07, - }, - "deepseek-v4p1-flash": { - "input_cost_per_token": 2.2e-07, - "cache_read_input_token_cost": 7e-09, - "output_cost_per_token": 6.6e-07, - "supports_vision": True, - "max_output_tokens": 393216, - }, -} +def test_bare_fireworks_ids_resolve_through_prefixed_entries(): + """Bare IDs from #37274 resolve via the provider-prefix lookup path.""" + for bare_id, prefixed_key in [ + ( + "accounts/fireworks/models/deepseek-v4-pro-0813", + "fireworks_ai/accounts/fireworks/models/deepseek-v4-pro-0813", + ), + ]: + info = get_model_info(model=bare_id, custom_llm_provider="fireworks_ai") + assert info.get("key") == prefixed_key + assert info["litellm_provider"] == "fireworks_ai" def test_fireworks_account_prefixed_twins_agree_on_price(model_data): diff --git a/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py b/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py index fd5dcc88e9f..10d1d6fecd1 100644 --- a/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py +++ b/tests/test_litellm/test_gemini_3_1_flash_lite_image_pricing.py @@ -109,6 +109,11 @@ def test_per_route_capabilities_match_model_cards(model: str, path: Path): assert info[field] == value, f"{model} {field} in {path.name}: {info.get(field)} != {value}" +@pytest.mark.parametrize("model", ALL_KEYS) +def test_backup_matches_main(model: str): + assert _load(BACKUP_PATH).get(model) == _load(MAIN_PATH).get(model) + + def test_gemini_prefix_routes_to_gemini(): routed_model, provider, _, _ = get_llm_provider(model=GEMINI) assert routed_model == UNPREFIXED diff --git a/tests/test_litellm/test_gemini_tts_native_audio_pricing.py b/tests/test_litellm/test_gemini_tts_native_audio_pricing.py new file mode 100644 index 00000000000..3dcb18c1466 --- /dev/null +++ b/tests/test_litellm/test_gemini_tts_native_audio_pricing.py @@ -0,0 +1,84 @@ +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Final + +import pytest + +import litellm + +REPO_ROOT: Final = Path(__file__).parents[2] +MAIN_PATH: Final = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PATH: Final = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +FLASH_TTS_KEYS: Final = ("gemini-2.5-flash-preview-tts", "gemini/gemini-2.5-flash-preview-tts") +PRO_TTS_KEYS: Final = ("gemini-2.5-pro-preview-tts", "gemini/gemini-2.5-pro-preview-tts") +NATIVE_AUDIO_KEYS: Final = tuple( + f"{prefix}gemini-2.5-flash-native-audio-{suffix}" + for prefix in ("", "gemini/") + for suffix in ("latest", "preview-09-2025", "preview-12-2025") +) + +LIVE_NATIVE_AUDIO_KEYS: Final = ( + "gemini-live-2.5-flash-preview-native-audio-09-2025", + "gemini/gemini-live-2.5-flash-preview-native-audio-09-2025", +) + +FLASH_TTS_INPUT: Final = 5e-07 +FLASH_TTS_AUDIO_OUTPUT: Final = 1e-05 +PRO_TTS_INPUT: Final = 1e-06 +PRO_TTS_AUDIO_OUTPUT: Final = 2e-05 +NATIVE_AUDIO_TEXT_INPUT: Final = 5e-07 +NATIVE_AUDIO_AUDIO_INPUT: Final = 3e-06 +NATIVE_AUDIO_TEXT_OUTPUT: Final = 2e-06 +NATIVE_AUDIO_AUDIO_OUTPUT: Final = 1.2e-05 + +PUBLISHED_RATES: Final = { + **{ + key: {"input_cost_per_token": FLASH_TTS_INPUT, "output_cost_per_token": FLASH_TTS_AUDIO_OUTPUT} + for key in FLASH_TTS_KEYS + }, + **{ + key: {"input_cost_per_token": PRO_TTS_INPUT, "output_cost_per_token": PRO_TTS_AUDIO_OUTPUT} + for key in PRO_TTS_KEYS + }, + **{ + key: { + "input_cost_per_token": NATIVE_AUDIO_TEXT_INPUT, + "input_cost_per_audio_token": NATIVE_AUDIO_AUDIO_INPUT, + "output_cost_per_token": NATIVE_AUDIO_TEXT_OUTPUT, + "output_cost_per_audio_token": NATIVE_AUDIO_AUDIO_OUTPUT, + } + for key in (*NATIVE_AUDIO_KEYS, *LIVE_NATIVE_AUDIO_KEYS) + }, +} +ALL_KEYS: Final = tuple(PUBLISHED_RATES) +NATIVE_AUDIO_BILLING_CASES: Final = ( + *((key, "gemini") for key in NATIVE_AUDIO_KEYS), + ("gemini-live-2.5-flash-preview-native-audio-09-2025", "vertex_ai"), + ("gemini/gemini-live-2.5-flash-preview-native-audio-09-2025", "gemini"), +) +LONG_CONTEXT_TIER_FIELDS: Final = ( + "input_cost_per_token_above_200k_tokens", + "output_cost_per_token_above_200k_tokens", + "cache_read_input_token_cost_above_200k_tokens", +) + + +def _load(path: Path) -> dict[str, dict[str, object]]: + with open(path, encoding="utf-8") as f: + return json.load(f) + + +@pytest.fixture +def local_model_cost_map(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) + litellm.get_model_info.cache_clear() + yield + litellm.get_model_info.cache_clear() + + +@pytest.mark.parametrize("model", ALL_KEYS) +def test_backup_matches_main(model: str): + assert _load(BACKUP_PATH)[model] == _load(MAIN_PATH)[model] diff --git a/tests/test_litellm/test_gpt_5_4_model_metadata.py b/tests/test_litellm/test_gpt_5_4_model_metadata.py new file mode 100644 index 00000000000..294d0757069 --- /dev/null +++ b/tests/test_litellm/test_gpt_5_4_model_metadata.py @@ -0,0 +1,44 @@ +import json +from functools import lru_cache +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).parents[2] +MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +DOCUMENTED_MAX_INPUT_TOKENS = 272000 +DOCUMENTED_MAX_OUTPUT_TOKENS = 128000 + +SMALL_MODEL_NAMES = ( + "gpt-5.4-mini", + "gpt-5.4-mini-2026-03-17", + "gpt-5.4-nano", + "gpt-5.4-nano-2026-03-17", +) +SMALL_MODELS = tuple(f"{prefix}{name}" for prefix in ("", "azure/", "azure_ai/") for name in SMALL_MODEL_NAMES) + +STANDARD_PRICING = { + "gpt-5.4-mini": (7.5e-07, 4.5e-06, 7.5e-08), + "gpt-5.4-nano": (2e-07, 1.25e-06, 2e-08), +} + +LONG_CONTEXT_MODELS = ("gpt-5.4", "gpt-5.4-pro") + + +@lru_cache(maxsize=2) +def _load(path: Path) -> dict[str, dict[str, object]]: + with open(path) as f: + return json.load(f) + + +def _pricing_key(model: str) -> str: + return "gpt-5.4-nano" if "nano" in model else "gpt-5.4-mini" + + +@pytest.mark.parametrize("model", SMALL_MODELS) +def test_gpt_5_4_small_models_backup_matches_main(model: str) -> None: + assert _load(BACKUP_PATH).get(model) == _load(MAIN_PATH).get(model), ( + f"{model} differs between main and backup model cost maps" + ) diff --git a/tests/test_litellm/test_gpt_5_5_model_metadata.py b/tests/test_litellm/test_gpt_5_5_model_metadata.py new file mode 100644 index 00000000000..6a64627f1a2 --- /dev/null +++ b/tests/test_litellm/test_gpt_5_5_model_metadata.py @@ -0,0 +1,19 @@ +import json +from pathlib import Path + + +def test_azure_ai_gpt_5_5_backup_matches_main(): + """Ensure the bundled model cost map stays in sync with the canonical file.""" + repo_root = Path(__file__).parents[2] + main_path = repo_root / "model_prices_and_context_window.json" + backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" + + with open(main_path) as f: + main_cost = json.load(f) + with open(backup_path) as f: + backup_cost = json.load(f) + + for model in ("azure_ai/gpt-5.5", "azure_ai/gpt-5.5-2026-04-23"): + assert backup_cost.get(model) == main_cost.get(model), ( + f"{model} differs between main and backup model cost maps" + ) diff --git a/tests/test_litellm/test_gpt_realtime_mode.py b/tests/test_litellm/test_gpt_realtime_mode.py index 778f620d72e..0ea85df84cb 100644 --- a/tests/test_litellm/test_gpt_realtime_mode.py +++ b/tests/test_litellm/test_gpt_realtime_mode.py @@ -1,4 +1,8 @@ -from typing_extensions import get_args, get_type_hints +import json +from pathlib import Path +from typing import get_args + +from typing_extensions import get_type_hints from litellm.types.utils import ModelInfoBase @@ -41,3 +45,13 @@ ALL_REALTIME_ONLY_GPT_MODELS = REALTIME_ONLY_GPT_MODELS + REALTIME_ONLY_GPT_MODE def test_realtime_is_a_valid_mode_literal(): hints = get_type_hints(ModelInfoBase, include_extras=False) assert "realtime" in get_args(hints["mode"]) + + +def test_backup_matches_main_for_realtime_models(): + repo_root = Path(__file__).parents[2] + with open(repo_root / "model_prices_and_context_window.json") as f: + main_cost = json.load(f) + with open(repo_root / "litellm" / "model_prices_and_context_window_backup.json") as f: + backup_cost = json.load(f) + for model in ALL_REALTIME_ONLY_GPT_MODELS: + assert backup_cost.get(model) == main_cost.get(model) diff --git a/tests/test_litellm/test_mistral_medium_3_5_model_metadata.py b/tests/test_litellm/test_mistral_medium_3_5_model_metadata.py new file mode 100644 index 00000000000..ab38d8a9118 --- /dev/null +++ b/tests/test_litellm/test_mistral_medium_3_5_model_metadata.py @@ -0,0 +1,33 @@ +import json +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).parents[2] +MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +MEDIUM_3_5_MODELS = ( + "mistral/mistral-medium-3-5", + "mistral/mistral-medium-2604", + "mistral/mistral-medium-latest", +) + +SYNCED_MODELS = MEDIUM_3_5_MODELS + ( + "mistral/mistral-medium-2508", + "mistral/mistral-medium-3-1-2508", +) + + +def _load(path): + with open(path) as f: + return json.load(f) + + +@pytest.mark.parametrize("model", SYNCED_MODELS) +def test_backup_matches_main(model): + """Ensure the bundled (backup) cost map stays in sync with the canonical file.""" + main_cost = _load(MAIN_PATH) + backup_cost = _load(BACKUP_PATH) + + assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_mistral_small_4_0_model_metadata.py b/tests/test_litellm/test_mistral_small_4_0_model_metadata.py new file mode 100644 index 00000000000..182c444bac9 --- /dev/null +++ b/tests/test_litellm/test_mistral_small_4_0_model_metadata.py @@ -0,0 +1,26 @@ +import json +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).parents[2] +MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +SMALL_4_0_MODELS = ( + "mistral/mistral-small-latest", + "mistral/mistral-small-2603", +) + + +def _load(path): + with open(path) as f: + return json.load(f) + + +@pytest.mark.parametrize("model", SMALL_4_0_MODELS) +def test_backup_matches_main(model): + main_cost = _load(MAIN_PATH) + backup_cost = _load(BACKUP_PATH) + + assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py b/tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py new file mode 100644 index 00000000000..8467cbd43b1 --- /dev/null +++ b/tests/test_litellm/test_mistral_zai_glm_5_2_model_metadata.py @@ -0,0 +1,52 @@ +import json +from pathlib import Path + +import pytest + +import litellm +from litellm.utils import supports_prompt_caching, supports_reasoning + +REPO_ROOT = Path(__file__).parents[2] +MAIN_PATH = REPO_ROOT / "model_prices_and_context_window.json" +BACKUP_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" + +GLM_5_2_MODELS = ("mistral/zai-glm-5-2", "mistral/glm-5-2") + +INPUT_COST = 1.4e-06 +CACHED_INPUT_COST = 1.4e-07 +OUTPUT_COST = 4.4e-06 + + +def _load(path): + with open(path) as f: + return json.load(f) + + +@pytest.fixture +def local_model_cost_map(monkeypatch): + """Force get_model_info to resolve against the in-repo cost map instead of the + remote one fetched at import time, which still carries the pre-merge pricing.""" + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) + litellm.get_model_info.cache_clear() + yield + litellm.get_model_info.cache_clear() + + +@pytest.mark.parametrize("model", GLM_5_2_MODELS) +def test_zai_glm_5_2_capabilities_are_visible_to_callers(local_model_cost_map, model): + """Mistral advertises reasoning and prompt caching on this model, so the helpers + every caller checks before sending a request must say so too.""" + assert supports_reasoning(model=model) is True + assert supports_prompt_caching(model=model) is True + + assert litellm.get_model_info(model=model) + + +@pytest.mark.parametrize("model", GLM_5_2_MODELS) +def test_backup_matches_main(model): + """Ensure the bundled (backup) cost map stays in sync with the canonical file.""" + main_cost = _load(MAIN_PATH) + backup_cost = _load(BACKUP_PATH) + + assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_muse_spark_1_1_model_metadata.py b/tests/test_litellm/test_muse_spark_1_1_model_metadata.py new file mode 100644 index 00000000000..f55266a78d7 --- /dev/null +++ b/tests/test_litellm/test_muse_spark_1_1_model_metadata.py @@ -0,0 +1,29 @@ +import json +from pathlib import Path + +from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider + +MUSE_SPARK_MODEL = "meta/muse-spark-1.1" + + +def test_muse_spark_1_1_model_info(): + routed_model, provider, _, api_base = get_llm_provider(model=MUSE_SPARK_MODEL, api_key="sk-test") + assert routed_model == "muse-spark-1.1" + assert provider == "meta" + assert api_base == "https://api.meta.ai/v1" + + +def test_muse_spark_1_1_backup_matches_main(): + """Ensure the bundled model cost map stays in sync with the canonical file.""" + repo_root = Path(__file__).parents[2] + main_path = repo_root / "model_prices_and_context_window.json" + backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" + + with open(main_path) as f: + main_cost = json.load(f) + with open(backup_path) as f: + backup_cost = json.load(f) + + assert backup_cost.get(MUSE_SPARK_MODEL) == main_cost.get(MUSE_SPARK_MODEL), ( + f"{MUSE_SPARK_MODEL} differs between main and backup model cost maps" + ) diff --git a/tests/test_litellm/test_muse_spark_1_2_model_metadata.py b/tests/test_litellm/test_muse_spark_1_2_model_metadata.py index 4cc69d9f66d..877fef456de 100644 --- a/tests/test_litellm/test_muse_spark_1_2_model_metadata.py +++ b/tests/test_litellm/test_muse_spark_1_2_model_metadata.py @@ -29,6 +29,15 @@ def test_muse_spark_1_2_routes_to_meta_model_api(model: str): assert api_base == "https://api.meta.ai/v1" +@pytest.mark.parametrize("model", (MUSE_SPARK_STANDARD, MUSE_SPARK_CONTRIBUTOR)) +def test_muse_spark_1_2_backup_matches_main(model: str): + """Ensure the bundled model cost map stays in sync with the canonical file.""" + main_cost = _load_cost_map() + backup_cost = _load_cost_map("litellm/model_prices_and_context_window_backup.json") + + assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" + + def test_muse_spark_contributor_tier_is_cheaper_than_standard(): cost_map = _load_cost_map() standard = cost_map[MUSE_SPARK_STANDARD] diff --git a/tests/test_litellm/test_muse_spark_1_3_model_metadata.py b/tests/test_litellm/test_muse_spark_1_3_model_metadata.py index 097dbc2923d..d98afa12a6e 100644 --- a/tests/test_litellm/test_muse_spark_1_3_model_metadata.py +++ b/tests/test_litellm/test_muse_spark_1_3_model_metadata.py @@ -38,6 +38,15 @@ def test_muse_spark_1_3_web_search_cost_per_query(local_model_cost_map, model: s assert StandardBuiltInToolCostTracking.get_cost_for_web_search(model_info=info) == WEB_SEARCH_COST_PER_QUERY +@pytest.mark.parametrize("model", (MUSE_SPARK_STANDARD, MUSE_SPARK_CONTRIBUTOR)) +def test_muse_spark_1_3_backup_matches_main(model: str): + """Ensure the bundled model cost map stays in sync with the canonical file.""" + main_cost = _load_cost_map() + backup_cost = _load_cost_map("litellm/model_prices_and_context_window_backup.json") + + assert backup_cost.get(model) == main_cost.get(model), f"{model} differs between main and backup model cost maps" + + def test_muse_spark_contributor_tier_is_cheaper_than_standard(): cost_map = _load_cost_map() standard = cost_map[MUSE_SPARK_STANDARD] diff --git a/tests/test_litellm/test_replicate_model_key_format.py b/tests/test_litellm/test_replicate_model_key_format.py index 39e9fa01d73..77ae5e1b069 100644 --- a/tests/test_litellm/test_replicate_model_key_format.py +++ b/tests/test_litellm/test_replicate_model_key_format.py @@ -18,3 +18,18 @@ def test_replicate_models_have_valid_key_prefix(model_cost: dict[str, Any]) -> N assert not malformed, ( f"Replicate models must use 'replicate/owner/model' key format, found malformed keys: {malformed}" ) + + +def test_replicate_backup_matches_main() -> None: + repo_root = Path(__file__).parents[2] + main_path = repo_root / "model_prices_and_context_window.json" + backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" + + with open(main_path, encoding="utf-8") as f: + main_cost: dict[str, Any] = json.load(f) + with open(backup_path, encoding="utf-8") as f: + backup_cost: dict[str, Any] = json.load(f) + + for key in main_cost: + if main_cost[key].get("litellm_provider") == "replicate": + assert backup_cost.get(key) == main_cost.get(key), f"{key} differs between main and backup model cost maps" diff --git a/tests/test_litellm/test_sambanova_model_metadata.py b/tests/test_litellm/test_sambanova_model_metadata.py new file mode 100644 index 00000000000..20f34f9f3cc --- /dev/null +++ b/tests/test_litellm/test_sambanova_model_metadata.py @@ -0,0 +1,25 @@ +import json +from pathlib import Path + +from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider + + +def test_sambanova_minimax_m27_model_info(): + model = "sambanova/MiniMax-M2.7" + json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" + with open(json_path) as f: + model_cost = json.load(f) + + info = model_cost.get(model) + assert info is not None, f"{model} not found in model_prices_and_context_window.json" + assert info["litellm_provider"] == "sambanova" + assert info["mode"] == "chat" + assert info["input_cost_per_token"] > 0 + assert info["output_cost_per_token"] > 0 + assert info["supports_function_calling"] is True + assert info["supports_reasoning"] is True + assert info["supports_tool_choice"] is True + + routed_model, provider, _, _ = get_llm_provider(model=model) + assert routed_model == "MiniMax-M2.7" + assert provider == "sambanova" diff --git a/tests/test_litellm/test_together_ai_model_metadata.py b/tests/test_litellm/test_together_ai_model_metadata.py index 851d0f0c9d8..88d6db0d8b0 100644 --- a/tests/test_litellm/test_together_ai_model_metadata.py +++ b/tests/test_litellm/test_together_ai_model_metadata.py @@ -108,6 +108,14 @@ def test_together_successor_metadata_points_at_live_models(cost_map: CostMap): assert "deprecation_date" not in target, f"{model} names deprecated successor {successor}" +def test_together_backup_cost_map_in_sync(cost_map: CostMap): + with open(REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json") as f: + backup = COST_MAP_ADAPTER.validate_python(json.load(f)) + together_main = {k: v for k, v in cost_map.items() if k.startswith("together_ai/")} + together_backup = {k: v for k, v in backup.items() if k.startswith("together_ai/")} + assert together_backup == together_main + + CACHED_INPUT_MODELS: Final = ( "together_ai/moonshotai/Kimi-K3", "together_ai/zai-org/GLM-5.2", diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index bad531fdd51..3a376ac9397 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -3641,9 +3641,6 @@ def _assert_fireworks_entry( assert info["input_cost_per_token"] > 0 assert info["output_cost_per_token"] > 0 assert "cache_read_input_token_cost" in info - assert info["max_input_tokens"] == expected_max_input - assert info["max_output_tokens"] == expected_max_output - assert info["max_tokens"] == expected_max_output assert info["supports_function_calling"] is True assert info["supports_tool_choice"] is True assert info["supports_reasoning"] is expected_reasoning @@ -5657,3 +5654,253 @@ def test_completion_finishes_response_metadata_before_handing_the_response_to_th assert snapshot["litellm_call_id"] assert snapshot["response_cost"] is not None assert snapshot["api_base"] + + +def test_fireworks_models_in_backup_cost_map(): + import json + from pathlib import Path + + json_path = Path(__file__).parents[2] / "litellm" / "model_prices_and_context_window_backup.json" + with open(json_path) as f: + model_cost = json.load(f) + + for entry in _FIREWORKS_MODELS: + _assert_fireworks_entry(model_cost, *entry) + + for short in _FIREWORKS_SHORT_FORMS: + long_key = f"fireworks_ai/accounts/fireworks/models/{short}" + short_key = f"fireworks_ai/{short}" + assert model_cost.get(short_key) == model_cost.get(long_key), ( + f"short-form {short_key} does not match long-form {long_key}" + ) + + for short in _FIREWORKS_ROUTER_SHORT_FORMS: + long_key = f"fireworks_ai/accounts/fireworks/routers/{short}" + short_key = f"fireworks_ai/{short}" + assert model_cost.get(short_key) == model_cost.get(long_key), ( + f"short-form {short_key} does not match long-form {long_key}" + ) + + +def test_fireworks_models_in_cost_map(): + import json + from pathlib import Path + + json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" + with open(json_path) as f: + model_cost = json.load(f) + + for entry in _FIREWORKS_MODELS: + _assert_fireworks_entry(model_cost, *entry) + + for short in _FIREWORKS_SHORT_FORMS: + long_key = f"fireworks_ai/accounts/fireworks/models/{short}" + short_key = f"fireworks_ai/{short}" + assert model_cost.get(short_key) == model_cost.get(long_key), ( + f"short-form {short_key} does not match long-form {long_key}" + ) + + for short in _FIREWORKS_ROUTER_SHORT_FORMS: + long_key = f"fireworks_ai/accounts/fireworks/routers/{short}" + short_key = f"fireworks_ai/{short}" + assert model_cost.get(short_key) == model_cost.get(long_key), ( + f"short-form {short_key} does not match long-form {long_key}" + ) + + +def test_fireworks_short_model_names_resolve_to_long_cost_map_keys(fireworks_short_model_cost_map: None) -> None: + model_info = litellm.get_model_info("fireworks_ai/glm-5p3") + assert model_info["key"] == "fireworks_ai/accounts/fireworks/models/glm-5p3" + + model_info = litellm.get_model_info("glm-5p3", custom_llm_provider="fireworks_ai") + assert model_info["key"] == "fireworks_ai/accounts/fireworks/models/glm-5p3" + + model_info = litellm.get_model_info("fireworks_ai/glm-5p3-fast") + assert model_info["key"] == "fireworks_ai/accounts/fireworks/routers/glm-5p3-fast" + + model_info = litellm.get_model_info("fireworks_ai/nomic-ai/nomic-embed-text-v1.5") + assert model_info["key"] == "fireworks_ai/nomic-ai/nomic-embed-text-v1.5" + + with pytest.raises(Exception, match="isn't mapped"): + litellm.get_model_info("fireworks_ai/does-not-exist") + + +def test_get_model_info_bedrock_regional_profile_without_entry_falls_back_to_base(local_model_cost_map): + """A regional profile with no dedicated cost-map entry must still resolve to its + region-stripped base entry.""" + info = litellm.get_model_info(model="bedrock/apac.anthropic.claude-opus-4-8") + assert info["key"] == "anthropic.claude-opus-4-8" + + +def test_get_model_info_gemini(monkeypatch): + """ + Tests if ALL gemini models have 'tpm' and 'rpm' in the model info + """ + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + litellm.model_cost = litellm.get_model_cost_map(url="") + + model_map = litellm.model_cost + for model, info in model_map.items(): + if ( + model.startswith("gemini/") + and "gemma" not in model + and "learnlm" not in model + and "imagen" not in model + and "veo" not in model + and "lyria" not in model + and "robotics" not in model + ): + assert info.get("tpm") is not None, f"{model} does not have tpm" + assert info.get("rpm") is not None, f"{model} does not have rpm" + + +def test_get_model_info_resolves_provider_prefixed_model_ids(local_model_cost_map): + """Perplexity's Agent API third-party models are keyed `perplexity/perplexity/` + because Perplexity's own id already starts with `perplexity/`. Callers run + `get_llm_provider` first, which hands `_get_potential_model_names` model + `perplexity/glm-5.2` with provider `perplexity`, and every candidate but the + provider-prefixed one strips that second `perplexity/` off. Regression: the + entries were unreachable from `supports_reasoning` and from the cost calculator's + per-token fallback, so a mapped model reported no reasoning support and raised + "This model isn't mapped yet" on the only path where its rates are ever used.""" + for model, reasoning in ( + ("perplexity/perplexity/glm-5.2", True), + ("perplexity/perplexity/kimi-k3", True), + ("perplexity/perplexity/deepseek-v4-flash-0731", True), + ("perplexity/perplexity/kimi-k2.7-code", False), + ("perplexity/perplexity/nemotron-3.5-lightning-30b-a3b", True), + ("perplexity/perplexity/nemotron-3-ultra-550b-a55b", True), + ): + assert litellm.supports_reasoning(model=model) is reasoning, model + + via_provider = litellm.get_model_info(model="perplexity/glm-5.2", custom_llm_provider="perplexity") + assert via_provider["key"] == "perplexity/perplexity/glm-5.2" + assert via_provider["mode"] == "responses" + + lightning = litellm.get_model_info( + model="perplexity/nemotron-3.5-lightning-30b-a3b", custom_llm_provider="perplexity" + ) + assert lightning["key"] == "perplexity/perplexity/nemotron-3.5-lightning-30b-a3b" + assert lightning["mode"] == "responses" + + ultra = litellm.get_model_info(model="perplexity/perplexity/nemotron-3-ultra-550b-a55b") + assert ultra["key"] == "perplexity/perplexity/nemotron-3-ultra-550b-a55b" + + +def test_get_model_info_shows_supports_computer_use(monkeypatch): + """ + Tests if 'supports_computer_use' is correctly retrieved by get_model_info. + We'll use 'claude-4-sonnet-20250514' as it's configured + in the backup JSON to have supports_computer_use: True. + """ + monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") + # Ensure litellm.model_cost is loaded, relying on the backup mechanism if primary fails + # as per previous debugging. + litellm.model_cost = litellm.get_model_cost_map(url="") + + # This model should have 'supports_computer_use': True in the backup JSON + model_known_to_support_computer_use = "claude-4-sonnet-20250514" + info = litellm.get_model_info(model_known_to_support_computer_use) + + # After the fix in utils.py, this should now be present and True + assert info.get("supports_computer_use") is True + + +def test_get_model_info_surfaces_supports_adaptive_thinking(local_model_cost_map): + """supports_adaptive_thinking must flow through get_model_info like every other + capability flag: both from an explicit cost-map entry and from a + fallback-generalization rule for an unmapped model. Regression: the field shipped + in the JSON but was never declared on ModelInfo nor copied during construction, so + get_model_info (and _supports_factory) silently dropped it for any provider-prefixed + or unmapped name.""" + explicit = litellm.get_model_info(model="claude-opus-4-8") + assert explicit["supports_adaptive_thinking"] is True + + generalized = litellm.get_model_info(model="claude-opus-4-9", custom_llm_provider="anthropic") + assert generalized["supports_adaptive_thinking"] is True + + +def test_get_model_info_surfaces_supports_parallel_function_calling(local_model_cost_map): + """A registry entry's supports_parallel_function_calling must read back through get_model_info + and litellm.supports_parallel_function_calling. Regression: the key was never copied into + ModelInfo, so provider-prefixed entries read None / False even when the map said True, and an + explicit False was indistinguishable from unset.""" + declared_true = litellm.get_model_info(model="together_ai/zai-org/GLM-5.3-Flash") + assert declared_true["supports_parallel_function_calling"] is True + assert litellm.supports_parallel_function_calling(model="together_ai/zai-org/GLM-5.3-Flash") is True + + +def test_model_info_for_fireworks_short_form_models(): + """ + Test that fireworks_ai short-form model entries (fireworks_ai/) + are correctly configured in model_prices_and_context_window.json. + + These entries enable cost attribution for models called via short-form + names (e.g., fireworks_ai/glm-4p7 instead of + fireworks_ai/accounts/fireworks/models/glm-4p7). + """ + import json + from pathlib import Path + + json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json" + with open(json_path) as f: + model_cost = json.load(f) + + # glm-4p7: short-form and long-form + for key in [ + "fireworks_ai/glm-4p7", + "fireworks_ai/accounts/fireworks/models/glm-4p7", + ]: + info = model_cost.get(key) + assert info is not None, f"{key} not found in model_prices_and_context_window.json" + assert info["litellm_provider"] == "fireworks_ai" + assert info["mode"] == "chat" + assert info["supports_reasoning"] is True + + # minimax-m2p1: short-form and long-form + for key in [ + "fireworks_ai/minimax-m2p1", + "fireworks_ai/accounts/fireworks/models/minimax-m2p1", + ]: + info = model_cost.get(key) + assert info is not None, f"{key} not found in model_prices_and_context_window.json" + assert info["litellm_provider"] == "fireworks_ai" + assert info["mode"] == "chat" + + # kimi-k2p5: short-form only (long-form already existed) + info = model_cost.get("fireworks_ai/kimi-k2p5") + assert info is not None, "fireworks_ai/kimi-k2p5 not found in model_prices_and_context_window.json" + assert info["litellm_provider"] == "fireworks_ai" + assert info["mode"] == "chat" + + +def test_model_info_for_vertex_ai_deepseek_model(): + model_info = litellm.get_model_info(model="vertex_ai/deepseek-ai/deepseek-r1-0528-maas") + assert model_info is not None + assert model_info["litellm_provider"] == "vertex_ai-deepseek_models" + assert model_info["mode"] == "chat" + + assert model_info["input_cost_per_token"] is not None + assert model_info["output_cost_per_token"] is not None + + +def test_provider_prefixed_lookup_never_outranks_an_existing_row(local_model_cost_map): + """The provider-prefixed candidate is tried last, after every candidate that + already existed, so no model that resolves today can change answer. `perplexity/sonar` + is the case that proves it: both `perplexity/sonar` and `perplexity/perplexity/sonar` + are cost-map keys, and the shorter one must keep winning.""" + sonar = litellm.get_model_info(model="sonar", custom_llm_provider="perplexity") + assert sonar["key"] == "perplexity/sonar" + assert sonar["mode"] == "chat" + + still_sonar = litellm.get_model_info(model="perplexity/sonar", custom_llm_provider="perplexity") + assert still_sonar["key"] == "perplexity/sonar" + assert still_sonar["mode"] == "chat" + + for model, provider, expected_key in ( + ("claude-sonnet-4-5", "anthropic", "claude-sonnet-4-5"), + ("anthropic/claude-sonnet-4-5", "anthropic", "claude-sonnet-4-5"), + ("gemini/gemini-2.0-flash", "gemini", "gemini/gemini-2.0-flash"), + ("openrouter/openai/gpt-4o", "openrouter", "openrouter/openai/gpt-4o"), + ): + assert litellm.get_model_info(model=model, custom_llm_provider=provider)["key"] == expected_key diff --git a/tests/test_litellm/test_xai_grok_4_3_model_metadata.py b/tests/test_litellm/test_xai_grok_4_3_model_metadata.py new file mode 100644 index 00000000000..50be24ba63d --- /dev/null +++ b/tests/test_litellm/test_xai_grok_4_3_model_metadata.py @@ -0,0 +1,19 @@ +import json +from pathlib import Path + + +def test_xai_grok_4_3_backup_matches_main(): + """Ensure the bundled model cost map stays in sync with the canonical file.""" + repo_root = Path(__file__).parents[2] + main_path = repo_root / "model_prices_and_context_window.json" + backup_path = repo_root / "litellm" / "model_prices_and_context_window_backup.json" + + with open(main_path) as f: + main_cost = json.load(f) + with open(backup_path) as f: + backup_cost = json.load(f) + + for model in ("xai/grok-4.3", "xai/grok-4.3-latest"): + assert backup_cost.get(model) == main_cost.get(model), ( + f"{model} differs between main and backup model cost maps" + ) From f6ef0a24e03efd0ddd3c42c3ee5a3c4a8f1e025d Mon Sep 17 00:00:00 2001 From: kerry Date: Tue, 15 Sep 2026 22:28:23 +0000 Subject: [PATCH 4/6] fix(tests): restore rerank response import Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- tests/test_litellm/test_cost_calculator.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py index 7fedb43ab6e..aa8a1d34bc1 100644 --- a/tests/test_litellm/test_cost_calculator.py +++ b/tests/test_litellm/test_cost_calculator.py @@ -16,6 +16,7 @@ from litellm.litellm_core_utils.litellm_logging import Logging from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo from litellm.types.llms.base import CachedTokensDetails from litellm.types.llms.openai import OpenAIRealtimeStreamList +from litellm.types.rerank import RerankResponse from litellm.types.utils import ( ModelInfo, ModelResponse, From c94a4f8696fe63dcbe42b6e25ad3cf1e9cddf8f4 Mon Sep 17 00:00:00 2001 From: kerry Date: Tue, 15 Sep 2026 22:49:57 +0000 Subject: [PATCH 5/6] test: restore xai reported-cost passthrough tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../test_xai_responses_transformation.py | 38 ++++++++++++++ .../llms/xai/test_xai_chat_transformation.py | 49 +++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py b/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py index 994dea1b877..e3feb7d5342 100644 --- a/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py +++ b/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py @@ -11,6 +11,7 @@ from unittest.mock import MagicMock, Mock import httpx +from litellm.llms.xai.cost_calculator import cost_per_token from litellm.llms.xai.responses.transformation import XAIResponsesAPIConfig from litellm.responses.utils import ResponseAPILoggingUtils from litellm.types.llms.openai import ( @@ -484,6 +485,43 @@ class TestXAIResponsesReportedCost: ) return response.usage + def test_reported_cost_reaches_the_cost_calculator(self): + usage = self._transformed_usage( + { + "input_tokens": 100, + "output_tokens": 200, + "total_tokens": 300, + "cost_in_usd_ticks": 37756000, + } + ) + + assert usage.cost == 0.0037756 + + chat_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage) + assert cost_per_token(model="grok-4-latest", usage=chat_usage) == (0.0, 0.0037756) + + def test_streamed_reported_cost_reaches_the_cost_calculator(self): + event = XAIResponsesAPIConfig().transform_streaming_response( + model="grok-4-latest", + parsed_chunk={ + "type": "response.completed", + "sequence_number": 7, + "response": self._response_body( + { + "input_tokens": 100, + "output_tokens": 200, + "total_tokens": 300, + "cost_in_usd_ticks": 37756000, + } + ), + }, + logging_obj=Mock(), + ) + + assert isinstance(event, ResponseCompletedEvent) + chat_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(event.response.usage) + assert cost_per_token(model="grok-4-latest", usage=chat_usage) == (0.0, 0.0037756) + def test_usage_without_a_reported_cost_is_left_alone(self): usage = self._transformed_usage({"input_tokens": 100, "output_tokens": 200, "total_tokens": 300}) diff --git a/tests/test_litellm/llms/xai/test_xai_chat_transformation.py b/tests/test_litellm/llms/xai/test_xai_chat_transformation.py index 7047408df5b..290cd3dcb3a 100644 --- a/tests/test_litellm/llms/xai/test_xai_chat_transformation.py +++ b/tests/test_litellm/llms/xai/test_xai_chat_transformation.py @@ -2,9 +2,12 @@ from unittest.mock import Mock import httpx +import litellm from litellm.llms.xai.chat.transformation import ( + XAIChatCompletionStreamingHandler, XAIChatConfig, ) +from litellm.llms.xai.cost_calculator import cost_per_token from litellm.types.utils import ( CompletionTokensDetailsWrapper, ModelResponse, @@ -233,6 +236,19 @@ class TestXAIReportedCost: ) return response.usage + def test_reported_cost_reaches_the_cost_calculator(self): + usage = self._transformed_usage( + { + "prompt_tokens": 100, + "completion_tokens": 200, + "total_tokens": 300, + "cost_in_usd_ticks": 37756000, + } + ) + + assert usage.cost == 0.0037756 + assert cost_per_token(model="grok-4-latest", usage=usage) == (0.0, 0.0037756) + def test_usage_without_a_reported_cost_is_left_alone(self): usage = self._transformed_usage({"prompt_tokens": 100, "completion_tokens": 200, "total_tokens": 300}) @@ -250,3 +266,36 @@ class TestXAIReportedCost: ) assert getattr(usage, "cost", None) is None + + def test_streamed_reported_cost_survives_chunk_aggregation(self): + """Streamed spend only matches if the conversion happens on the chunk. + + Chunk aggregation rebuilds usage from the fields it models plus ``cost``, so a + chunk still carrying only ``cost_in_usd_ticks`` loses the reported amount. + """ + handler = XAIChatCompletionStreamingHandler(streaming_response=iter([]), sync_stream=True) + + parsed = handler.chunk_parser( + { + "id": "chatcmpl-xai", + "object": "chat.completion.chunk", + "created": 0, + "model": "grok-4-latest", + "choices": [], + "usage": { + "prompt_tokens": 100, + "completion_tokens": 200, + "total_tokens": 300, + "cost_in_usd_ticks": 37756000, + }, + } + ) + + assert parsed.usage.cost == 0.0037756 + + assembled = litellm.stream_chunk_builder(chunks=[parsed]) + assert assembled.usage.cost == 0.0037756 + assert cost_per_token(model="grok-4-latest", usage=assembled.usage) == ( + 0.0, + 0.0037756, + ) From e64371062cc6defc09e4b3caf73fad6e36a7905e Mon Sep 17 00:00:00 2001 From: kerry Date: Tue, 15 Sep 2026 23:04:40 +0000 Subject: [PATCH 6/6] test: remove test files left empty by the cleanup Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../databricks/test_databricks_pricing.py | 0 .../test_fireworks_ai_kimi_model_metadata.py | 54 ------------------- .../llms/mistral/ocr/test_mistral_ocr_cost.py | 40 -------------- .../llms/tencent/test_cost_calculator.py | 1 - .../test_litellm/test_command_r7b_pricing.py | 53 ------------------ 5 files changed, 148 deletions(-) delete mode 100644 tests/test_litellm/llms/databricks/test_databricks_pricing.py delete mode 100644 tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py delete mode 100644 tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py delete mode 100644 tests/test_litellm/llms/tencent/test_cost_calculator.py delete mode 100644 tests/test_litellm/test_command_r7b_pricing.py diff --git a/tests/test_litellm/llms/databricks/test_databricks_pricing.py b/tests/test_litellm/llms/databricks/test_databricks_pricing.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py b/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py deleted file mode 100644 index 8d28ee921e1..00000000000 --- a/tests/test_litellm/llms/fireworks_ai/test_fireworks_ai_kimi_model_metadata.py +++ /dev/null @@ -1,54 +0,0 @@ -""" -Regression test for Fireworks Kimi K2.5 / K2.6 / K2.7 context and output limits. - -Fireworks publishes a 262144-token context window for every Kimi K2.5, K2.6 and -K2.7 model, but caps generation well below that. A previous bulk edit had flattened -max_output_tokens/max_tokens to 262144 (equal to the context window), which let the -pre-call context-window check admit requests asking for a full 262144-token -completion that Fireworks then rejects. These assertions pin the corrected per-alias -limits so a future bulk edit can't silently flatten them again. -""" - -import json -from importlib.resources import files - -import pytest - -CONTEXT_WINDOW = 262144 -OUTPUT_LIMIT = 32768 - -KIMI_ALIASES = ( - "fireworks_ai/kimi-k2p5", - "fireworks_ai/kimi-k2p6", - "fireworks_ai/kimi-k2p6-fast", - "fireworks_ai/kimi-k2p7-code", - "fireworks_ai/kimi-k2p7-code-fast", - "fireworks_ai/accounts/fireworks/models/kimi-k2p5", - "fireworks_ai/accounts/fireworks/models/kimi-k2p6", - "fireworks_ai/accounts/fireworks/models/kimi-k2p7-code", - "fireworks_ai/accounts/fireworks/routers/kimi-k2p6-fast", - "fireworks_ai/accounts/fireworks/routers/kimi-k2p7-code-fast", -) - - -@pytest.fixture(scope="module") -def use_local_model_cost_map(): - monkeypatch = pytest.MonkeyPatch() - monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") - - import litellm - from litellm.utils import _invalidate_model_cost_lowercase_map - - original_model_cost = litellm.model_cost - litellm.model_cost = json.loads( - files("litellm").joinpath("model_prices_and_context_window_backup.json").read_text(encoding="utf-8") - ) - litellm.get_model_info.cache_clear() - _invalidate_model_cost_lowercase_map() - try: - yield litellm - finally: - litellm.model_cost = original_model_cost - litellm.get_model_info.cache_clear() - _invalidate_model_cost_lowercase_map() - monkeypatch.undo() diff --git a/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py b/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py deleted file mode 100644 index e3cf40b43f7..00000000000 --- a/tests/test_litellm/llms/mistral/ocr/test_mistral_ocr_cost.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -Cost tests for Mistral OCR models against the real litellm cost map -(no monkeypatching of get_model_info). These regress the pricing entries -for mistral-ocr-4-0 and mistral-ocr-latest, which now both resolve to -OCR 4 at $4 / 1000 pages. -""" - -from pathlib import Path - -from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo - -OCR4_COST_PER_PAGE = 0.004 -OCR4_ANNOTATION_COST_PER_PAGE = 0.005 - -REPO_ROOT = Path(__file__).parents[5] -MAIN_COST_MAP = REPO_ROOT / "model_prices_and_context_window.json" -BACKUP_COST_MAP = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json" - -OCR3_MODEL = "mistral/mistral-ocr-2512" -OCR3_COST_PER_PAGE = 0.002 -OCR3_ANNOTATION_COST_PER_PAGE = 0.003 - -AZURE_DOC_AI_MODEL = "azure_ai/mistral-document-ai-2512" -AZURE_DOC_AI_COST_PER_PAGE = 0.003 - - -def _ocr_response(model: str, pages_processed: int) -> OCRResponse: - return OCRResponse( - pages=[OCRPage(index=i, markdown=f"page {i}") for i in range(pages_processed)], - model=model, - usage_info=OCRUsageInfo(pages_processed=pages_processed), - ) - - -def _annotated_ocr_response(model: str, pages_processed: int | None, annotation_pages: int) -> OCRResponse: - return OCRResponse( - pages=[], - model=model, - usage_info=OCRUsageInfo(pages_processed=pages_processed, pages_processed_annotation=annotation_pages), - ) diff --git a/tests/test_litellm/llms/tencent/test_cost_calculator.py b/tests/test_litellm/llms/tencent/test_cost_calculator.py deleted file mode 100644 index 8b137891791..00000000000 --- a/tests/test_litellm/llms/tencent/test_cost_calculator.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_litellm/test_command_r7b_pricing.py b/tests/test_litellm/test_command_r7b_pricing.py deleted file mode 100644 index c091fec313e..00000000000 --- a/tests/test_litellm/test_command_r7b_pricing.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -Regression test: ``command-r7b-12-2024`` had its input/output per-token -costs transposed in the model-cost maps (input=1.5e-07 / output=3.75e-08), -even though Cohere publishes $0.0375/1M input and $0.15/1M output, i.e. -output is ~4x input like every other ``command-r`` entry. - -These tests pin the corrected values in both the primary price map and the -``litellm/`` backup, and verify ``get_model_info`` surfaces them, so the -swap cannot silently regress. -""" - -import json -import os - -import litellm - -MODEL = "command-r7b-12-2024" -EXPECTED_INPUT_COST = 3.75e-08 -EXPECTED_OUTPUT_COST = 1.5e-07 - - -def _load_json(path: str) -> dict: - with open(path, encoding="utf-8") as f: - return json.load(f) - - -def _backup_path() -> str: - return os.path.join( - os.path.dirname(litellm.__file__), - "model_prices_and_context_window_backup.json", - ) - - -def _main_path() -> str: - # This test lives at ``tests/test_litellm/``; the primary price map sits at - # the repo root, two directories up. Resolve it relative to this file so the - # test works regardless of where ``litellm`` itself is installed (e.g. a pip - # install into site-packages). - return os.path.join( - os.path.dirname(__file__), - "..", - "..", - "model_prices_and_context_window.json", - ) - - -class TestCommandR7bPricingData: - """The JSON price maps must carry Cohere's published costs, with output - more expensive than input.""" - - -class TestCommandR7bPricingModelInfo: - """``get_model_info`` must report the corrected, un-swapped costs."""