From d792af887b916ab681bce67caf435ffb09ae2de1 Mon Sep 17 00:00:00 2001 From: Chenglun Hu Date: Thu, 27 Aug 2026 06:03:06 +0800 Subject: [PATCH] fix(utils): strip include_usage from stream_options for non-streaming requests include_usage is only meaningful when streaming; OpenAI-compatible backends (e.g. vLLM) return 400 if stream_options.include_usage is sent without stream=True. Strip only that key for non-streaming requests so other keys (e.g. include_obfuscation, used by the /v1/responses bridge) survive. Fixes #29431. --- litellm/utils.py | 14 + tests/test_litellm/test_utils.py | 651 +++++++++++-------------------- 2 files changed, 237 insertions(+), 428 deletions(-) diff --git a/litellm/utils.py b/litellm/utils.py index c2770a1a26d..0f448f417d2 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -4115,6 +4115,20 @@ def get_optional_params( model=model, provider_config=provider_config, ) + # include_usage in stream_options is only meaningful for streaming requests; + # OpenAI-compatible backends (e.g. vLLM) reject it with a 400 when stream is + # not True. Strip just that key for non-streaming requests (other keys such as + # include_obfuscation stay). Fixes #29431. + if stream is not True: + _stream_options: Final = non_default_params.get("stream_options") + if isinstance(_stream_options, dict) and "include_usage" in _stream_options: + _without_usage: Final = { # mutable-ok: normalized stream_options for the non-streaming request + k: v for k, v in _stream_options.items() if k != "include_usage" + } + if _without_usage: + non_default_params["stream_options"] = _without_usage + else: + non_default_params.pop("stream_options", None) optional_params = pre_process_optional_params( passed_params=passed_params, non_default_params=non_default_params, diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index 366e510a94d..c024b380be1 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -103,7 +103,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 @@ -114,9 +113,7 @@ def test_get_model_info_surfaces_supports_adaptive_thinking(local_model_cost_map 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" - ) + generalized = litellm.get_model_info(model="claude-opus-4-9", custom_llm_provider="anthropic") assert generalized["supports_adaptive_thinking"] is True @@ -134,9 +131,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" @@ -163,9 +158,7 @@ def test_get_model_info_resolves_provider_prefixed_model_ids(local_model_cost_ma ): assert litellm.supports_reasoning(model=model) is reasoning, model - via_provider = litellm.get_model_info( - model="perplexity/glm-5.2", custom_llm_provider="perplexity" - ) + 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 @@ -182,9 +175,7 @@ def test_provider_prefixed_lookup_never_outranks_an_existing_row(local_model_cos 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" - ) + still_sonar = litellm.get_model_info(model="perplexity/sonar", custom_llm_provider="perplexity") assert still_sonar["key"] == "perplexity/sonar" assert still_sonar["mode"] == "chat" @@ -203,28 +194,13 @@ def test_check_provider_match_azure_ai_allows_openai_and_azure(): 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(): @@ -259,21 +235,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(): @@ -281,21 +247,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(): @@ -348,9 +304,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 @@ -385,21 +339,14 @@ def test_gpt_image_2_provider_and_model_info(local_model_cost_map): assert model_info["input_cost_per_image_token"] == 8e-06 assert model_info["output_cost_per_token"] == 1e-05 assert model_info["output_cost_per_image_token"] == 3e-05 - assert ( - "/v1/images/generations" - in litellm.model_cost["gpt-image-2"]["supported_endpoints"] - ) - assert ( - "/v1/images/edits" in litellm.model_cost["gpt-image-2"]["supported_endpoints"] - ) + assert "/v1/images/generations" in litellm.model_cost["gpt-image-2"]["supported_endpoints"] + assert "/v1/images/edits" in litellm.model_cost["gpt-image-2"]["supported_endpoints"] assert model_info["supports_vision"] is True assert model_info["supports_pdf_input"] is True def test_gpt_image_2_snapshot_model_info(local_model_cost_map): - model, custom_llm_provider, _, _ = litellm.get_llm_provider( - model="gpt-image-2-2026-04-21" - ) + model, custom_llm_provider, _, _ = litellm.get_llm_provider(model="gpt-image-2-2026-04-21") assert model == "gpt-image-2-2026-04-21" assert custom_llm_provider == "openai" @@ -411,16 +358,12 @@ def test_gpt_image_2_snapshot_model_info(local_model_cost_map): def test_azure_gpt_image_2_model_info(local_model_cost_map): - model, custom_llm_provider, _, _ = litellm.get_llm_provider( - model="azure/gpt-image-2" - ) + model, custom_llm_provider, _, _ = litellm.get_llm_provider(model="azure/gpt-image-2") assert model == "gpt-image-2" assert custom_llm_provider == "azure" - model_info = litellm.get_model_info( - model="gpt-image-2", custom_llm_provider="azure" - ) + model_info = litellm.get_model_info(model="gpt-image-2", custom_llm_provider="azure") assert model_info["litellm_provider"] == "azure" assert model_info["mode"] == "image_generation" assert model_info["input_cost_per_token"] == 5e-06 @@ -437,26 +380,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}, @@ -466,9 +402,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}, @@ -478,9 +412,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}, @@ -490,9 +422,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}, @@ -504,10 +434,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}, @@ -519,9 +446,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}, @@ -531,9 +456,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}, @@ -543,9 +466,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}, @@ -556,11 +477,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", @@ -573,10 +491,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}, @@ -586,11 +501,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( @@ -600,10 +512,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}, @@ -627,12 +536,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}, @@ -646,9 +550,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", @@ -657,12 +559,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", @@ -671,9 +568,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", @@ -696,12 +591,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(): @@ -807,9 +700,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: @@ -851,24 +742,16 @@ def test_aaamodel_prices_and_context_window_json_is_valid(): "cache_creation_input_token_cost_above_1hr": {"type": "number"}, "cache_creation_input_token_cost_above_200k_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"}, "cache_read_input_token_cost_above_200k_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"}, @@ -887,12 +770,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"}, @@ -917,9 +796,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"}, @@ -1123,18 +1000,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) @@ -1170,9 +1041,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) @@ -1202,7 +1071,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" @@ -1277,15 +1148,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(): @@ -1293,18 +1159,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( @@ -1314,17 +1170,10 @@ def test_supports_tool_choice_simple_tests(): is True ) + assert litellm.utils.supports_tool_choice(model="us.amazon.nova-micro-v1:0") is False + assert litellm.utils.supports_tool_choice(model="bedrock/us.amazon.nova-micro-v1:0") is False assert ( - litellm.utils.supports_tool_choice(model="us.amazon.nova-micro-v1:0") is False - ) - assert ( - litellm.utils.supports_tool_choice(model="bedrock/us.amazon.nova-micro-v1:0") - is False - ) - assert ( - litellm.utils.supports_tool_choice( - model="us.amazon.nova-micro-v1:0", custom_llm_provider="bedrock_converse" - ) + litellm.utils.supports_tool_choice(model="us.amazon.nova-micro-v1:0", custom_llm_provider="bedrock_converse") is False ) @@ -1364,14 +1213,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 @@ -1443,9 +1286,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) @@ -1488,9 +1329,7 @@ def test_get_model_info_shows_supports_computer_use(monkeypatch): 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 + assert info_gpt.get("supports_computer_use") is None # Expecting None due to the default in ModelInfoBase @pytest.mark.parametrize( @@ -1580,9 +1419,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, @@ -1648,25 +1485,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", @@ -1733,9 +1564,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. @@ -1746,17 +1575,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): """ @@ -1770,9 +1597,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" @@ -1809,9 +1634,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. @@ -1823,14 +1646,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", @@ -1855,9 +1674,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}") @@ -1897,17 +1714,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.""" @@ -1922,9 +1733,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 @@ -1944,9 +1755,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 @@ -1959,11 +1768,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", [ @@ -2134,13 +1941,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) @@ -2225,9 +2030,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}") @@ -2477,17 +2280,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!") @@ -2514,9 +2313,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) @@ -2572,17 +2369,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(): @@ -2604,9 +2397,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( @@ -2649,9 +2440,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( @@ -2683,9 +2472,7 @@ if __name__ == "__main__": def test_model_info_for_vertex_ai_deepseek_model(): - model_info = litellm.get_model_info( - model="vertex_ai/deepseek-ai/deepseek-r1-0528-maas" - ) + 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" @@ -2715,9 +2502,7 @@ def test_model_info_for_openrouter_kimi_k2_5(): model_cost = json.load(f) model_info = model_cost.get("openrouter/moonshotai/kimi-k2.5") - assert ( - model_info is not None - ), "Model not found in model_prices_and_context_window.json" + assert model_info is not None, "Model not found in model_prices_and_context_window.json" assert model_info["litellm_provider"] == "openrouter" assert model_info["mode"] == "chat" @@ -2755,9 +2540,7 @@ def test_gemini_embedding_2_ga_in_cost_map(): ("gemini-embedding-2", "vertex_ai-embedding-models"), ): info = model_cost.get(key) - assert ( - info is not None - ), f"{key} missing from model_prices_and_context_window.json" + assert info is not None, f"{key} missing from model_prices_and_context_window.json" assert info["litellm_provider"] == provider assert info.get("mode") == "embedding" assert info.get("supports_multimodal") is True @@ -2766,9 +2549,9 @@ def test_gemini_embedding_2_ga_in_cost_map(): assert info.get("input_cost_per_audio_per_second") == 0.00016 assert info.get("input_cost_per_video_per_second") == 0.00079 if provider in ("vertex_ai-embedding-models", "vertex_ai"): - assert ( - info.get("uses_embed_content") is True - ), f"{key} must have uses_embed_content=true for correct Vertex AI routing" + assert info.get("uses_embed_content") is True, ( + f"{key} must have uses_embed_content=true for correct Vertex AI routing" + ) def test_gemini_lyria_3_preview_models_in_cost_map(): @@ -2809,9 +2592,7 @@ def test_model_info_for_fireworks_short_form_models(): "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 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 @@ -2825,9 +2606,7 @@ def test_model_info_for_fireworks_short_form_models(): "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 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 @@ -2836,9 +2615,7 @@ def test_model_info_for_fireworks_short_form_models(): # 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 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 @@ -2864,9 +2641,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, @@ -3084,9 +2859,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.""" @@ -3138,9 +2911,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, @@ -3357,9 +3128,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", @@ -3607,65 +3376,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: @@ -4154,27 +3889,23 @@ def test_fireworks_models_in_cost_map(): 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}" + 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}" + 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" - ) + 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) @@ -4184,16 +3915,16 @@ def test_fireworks_models_in_backup_cost_map(): 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}" + 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}" + assert model_cost.get(short_key) == model_cost.get(long_key), ( + f"short-form {short_key} does not match long-form {long_key}" + ) class TestBedrockBaseModelLabelKeepsTools: @@ -4374,7 +4105,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", @@ -4418,16 +4149,13 @@ class TestVertexEmbeddingEncodingFormat: "gemini/gemini-3.1-flash-lite-image", ], ) -def test_gemini_image_models_do_not_support_reasoning( - model: str, local_model_cost_map: None -) -> None: +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." + f"{model} incorrectly classified as reasoning-capable. Add 'supports_reasoning: false' to its model_cost entry." ) @@ -5178,7 +4906,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") @@ -5239,7 +4969,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()]) @@ -5375,7 +5107,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() @@ -5431,7 +5165,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()]) @@ -5484,7 +5220,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") @@ -5539,7 +5277,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()]) @@ -5549,7 +5289,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, ) @@ -5565,7 +5307,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): @@ -5596,7 +5340,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()]) @@ -5620,6 +5366,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") @@ -5634,3 +5381,51 @@ def test_snapshot_exception_for_hook_preserves_suppress_context_flag() -> None: snapshot = _snapshot_exception_for_hook(e) assert snapshot.__suppress_context__ is False assert snapshot.__context__ is e.__context__ + + +class TestStreamOptionsNonStreaming: + """include_usage in stream_options is only valid for streaming requests; + OpenAI-compatible backends (e.g. vLLM) 400 if it's sent without stream=True. + Other keys (e.g. include_obfuscation) must survive. See #29431.""" + + def test_include_usage_dropped_when_stream_not_set(self): + from litellm.utils import get_optional_params + + result = get_optional_params( + model="my-model", + custom_llm_provider="openai", + stream_options={"include_usage": True}, + ) + assert "stream_options" not in result + + def test_include_usage_dropped_when_stream_false(self): + from litellm.utils import get_optional_params + + result = get_optional_params( + model="my-model", + custom_llm_provider="openai", + stream=False, + stream_options={"include_usage": True}, + ) + assert "stream_options" not in result + + def test_other_stream_options_keys_survive_when_not_streaming(self): + from litellm.utils import get_optional_params + + result = get_optional_params( + model="my-model", + custom_llm_provider="openai", + stream_options={"include_usage": True, "include_obfuscation": False}, + ) + assert result["stream_options"] == {"include_obfuscation": False} + + def test_include_usage_kept_when_streaming(self): + from litellm.utils import get_optional_params + + result = get_optional_params( + model="my-model", + custom_llm_provider="openai", + stream=True, + stream_options={"include_usage": True}, + ) + assert result.get("stream_options") == {"include_usage": True}