The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge branch 'litellm_internal_staging' into litellm_lit_4116_drop_params_string_coerce
mateo-berri1a9611d1a0ee
diff --cc litellm/litellm_core_utils/core_helpers.pyindex 838019264c9,2cdcfe4879c..671b2ddce99--- a/litellm/litellm_core_utils/core_helpers.py+++ b/litellm/litellm_core_utils/core_helpers.py@@@ -36,23 -37,11 +37,23 @@@ def safe_divide_seconds(seconds: floatreturn float(seconds / denominator)+def normalize_drop_params(value: object) -> bool | None:+ if isinstance(value, bool):+ return value+ if isinstance(value, str):- lowered = value.strip().lower()++ lowered: Final = value.strip().lower()+ if lowered == "true":+ return True+ if lowered == "false":+ return False+ return None++def safe_divide(- numerator: Union[int, float],- denominator: Union[int, float],- default: Union[int, float] = 0,- ) -> Union[int, float]:+ numerator: float,+ denominator: float,+ default: float = 0,+ ) -> int | float:"""Safely divide two numbers, returning a default value if denominator is zero.diff --cc litellm/types/router.pyindex 77d1815d28d,0db482d8a58..e2a04f9da77--- a/litellm/types/router.py+++ b/litellm/types/router.py@@@ -20,11 -10,13 +10,14 @@@ from typing import TYPE_CHECKING, Any,import httpxfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator- from typing_extensions import Protocol, Required, TypedDict, runtime_checkable+ from typing_extensions import Protocol, ReadOnly, Required, TypedDict, runtime_checkablefrom litellm._uuid import uuid+from litellm.litellm_core_utils.core_helpers import normalize_drop_params+ if TYPE_CHECKING:+ from litellm.router import Router+from .completion import CompletionRequestfrom .embedding import EmbeddingRequestfrom .llms.openai import OpenAIFileObject@@@ -224,25 -306,22 +307,23 @@@ class GenericLiteLLMParams(CredentialLiLiteLLM Params without 'model' arg (used across completion / assistants api)"""- custom_llm_provider: Optional[str] = None- tpm: Optional[int] = None- rpm: Optional[int] = None- itpm: Optional[int] = None- otpm: Optional[int] = None- timeout: Optional[Union[float, str, httpx.Timeout]] = None # if str, pass in as os.environ/- stream_timeout: Optional[Union[float, str]] = (- None # timeout when making stream=True calls, if str, pass in as os.environ/- )- max_retries: Optional[int] = None- drop_params: Optional[bool] = None- organization: Optional[str] = None # for openai orgs+ custom_llm_provider: str | None = None+ tpm: int | None = None+ rpm: int | None = None+ itpm: int | None = None+ otpm: int | None = None+ timeout: float | str | httpx.Timeout | None = None # if str, pass in as os.environ/+ stream_timeout: float | str | None = None # timeout when making stream=True calls, if str, pass in as os.environ/+ max_retries: int | None = None++ drop_params: bool | None = None+ organization: str | None = None # for openai orgsconfigurable_clientside_auth_params: CONFIGURABLE_CLIENTSIDE_AUTH_PARAMS = None- litellm_credential_name: Optional[str] = None+ litellm_credential_name: str | None = None## LOGGING PARAMS ##- litellm_trace_id: Optional[str] = None+ litellm_trace_id: str | None = None- max_file_size_mb: Optional[float] = None+ max_file_size_mb: float | None = None# Proxy-wide default rate limits applied to any API key using this deployment# when the key does not have a model-specific tpm/rpm limit configured.@@@ -313,12 -404,7 +406,12 @@@return filteredreturn data+ @field_validator("drop_params", mode="before")+ @classmethod- def coerce_drop_params(cls, value: object) -> Optional[bool]:++ def coerce_drop_params(cls, value: object) -> bool | None:+ return normalize_drop_params(value)+- def __contains__(self, key):+ def __contains__(self, key) -> bool:# Define custom behavior for the 'in' operatorreturn hasattr(self, key)diff --cc litellm/utils.pyindex e10b63ceb37,b2477d344dc..87d667fd8ee--- a/litellm/utils.py+++ b/litellm/utils.py@@@ -74,11 -74,16 +74,17 @@@ from litellm.constants importJITTER,MAX_RETRY_DELAY,MAX_TOKEN_TRIMMING_ATTEMPTS,- DEFAULT_MINIMUM_PROMPT_CACHE_TOKEN_COUNT,MINIMUM_PROMPT_CACHE_TOKEN_COUNT_OVERRIDE,+ NON_INFERENCE_CALL_TYPES,OPENAI_EMBEDDING_PARAMS,+ PROVIDERS_THAT_AUTHENTICATE_ON_PROVIDER_INFO,TOOL_CHOICE_OBJECT_TOKEN_COUNT,)++from litellm.litellm_core_utils.core_helpers import normalize_drop_params+ from litellm.litellm_core_utils.fallback_generalizations import (+ match_capability_generalizations,+ )+ from litellm.litellm_core_utils.sensitive_data_masker import redact_credentials_in_payload_CachingHandlerResponse = None_LLMCachingHandler = None@@@ -2853,8 -3231,8 +3232,8 @@@ def get_optional_params_transcriptionpassed_params.pop("OPENAI_TRANSCRIPTION_PARAMS")custom_llm_provider = passed_params.pop("custom_llm_provider")- drop_params = passed_params.pop("drop_params")+ drop_params = normalize_drop_params(passed_params.pop("drop_params"))- special_params = passed_params.pop("kwargs")+ special_params: Final[Mapping[str, object]] = passed_params.pop("kwargs")for k, v in special_params.items():passed_params[k] = v@@@ -2961,16 -3339,17 +3340,17 @@@ def get_optional_params_image_genmodel = passed_params.pop("model", None)custom_llm_provider = passed_params.pop("custom_llm_provider")provider_config = passed_params.pop("provider_config", None)- drop_params = passed_params.pop("drop_params", None)+ drop_params = normalize_drop_params(passed_params.pop("drop_params", None))additional_drop_params = passed_params.pop("additional_drop_params", None)- special_params = passed_params.pop("kwargs")+ special_params: Final[Mapping[str, object]] = passed_params.pop("kwargs")for k, v in special_params.items():- if k.startswith("aws_") and (- custom_llm_provider != "bedrock" and custom_llm_provider != "sagemaker"+ if (+ k.startswith("aws_")+ and (custom_llm_provider != "bedrock" and custom_llm_provider != "sagemaker")+ or k == "hf_model_name"+ and custom_llm_provider != "sagemaker"): # allow dynamically setting boto3 init logiccontinue- elif k == "hf_model_name" and custom_llm_provider != "sagemaker":- continueelif (k.startswith("vertex_") and custom_llm_provider != "vertex_ai" and custom_llm_provider != "vertex_ai_beta"): # allow dynamically setting vertex ai init logic@@@ -3078,14 -3460,14 +3461,14 @@@ def get_optional_params_embeddings**kwargs,):# Lazy load get_supported_openai_params- get_supported_openai_params = getattr(sys.modules[__name__], "get_supported_openai_params")+ get_supported_openai_params: Final = getattr(sys.modules[__name__], "get_supported_openai_params")# retrieve all parameters passed to the function- passed_params = locals()+ passed_params: Final = locals()custom_llm_provider = passed_params.pop("custom_llm_provider", None)- special_params = passed_params.pop("kwargs")+ special_params: Final = passed_params.pop("kwargs")- drop_params = passed_params.pop("drop_params", None)+ drop_params = normalize_drop_params(passed_params.pop("drop_params", None))additional_drop_params = passed_params.pop("additional_drop_params", None)allowed_openai_params = passed_params.pop("allowed_openai_params", None) or []# Remove function objects from passed_params to avoid JSON serialization errors@@@ -3789,17 -4185,17 +4186,18 @@@ def get_optional_paramsreasoning_effort=None,verbosity=None,additional_drop_params=None,- messages: Optional[List[AllMessageValues]] = None,- thinking: Optional[AnthropicThinkingParam] = None,- web_search_options: Optional[OpenAIWebSearchOptions] = None,- safety_identifier: Optional[str] = None,- base_model: Optional[str] = None,+ messages: list[AllMessageValues] | None = None,+ thinking: AnthropicThinkingParam | None = None,+ web_search_options: OpenAIWebSearchOptions | None = None,+ safety_identifier: str | None = None,+ store: bool | None = None,+ prompt_cache_key: str | None = None,+ base_model: str | None = None,**kwargs,):- passed_params = locals().copy()- special_params = passed_params.pop("kwargs")- drop_params = normalize_drop_params(drop_params)- passed_params["drop_params"] = drop_params++ drop_params = normalize_drop_params(drop_params) # rebind-ok: config and DB deployments pass "true" as a string+ passed_params: Final = locals().copy()+ special_params: Final = passed_params.pop("kwargs")# Remove base_model from passed_params so it doesn't interfere with# non_default_params / _check_valid_arg — it's a routing hint, not an# OpenAI param.@@@ -3881,20 -4271,20 +4273,20 @@@model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "anthropic_text":optional_params = litellm.AnthropicTextConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)optional_params = litellm.AnthropicTextConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "cohere_chat" or custom_llm_provider == "cohere":@@@ -3903,7 -4293,7 +4295,7 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "triton":optional_params = litellm.TritonConfig().map_openai_params(@@@ -3918,35 -4308,35 +4310,35 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "replicate":optional_params = litellm.ReplicateConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "predibase":optional_params = litellm.PredibaseConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "huggingface":optional_params = litellm.HuggingFaceChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "together_ai":- optional_params = litellm.TogetherAIConfig().map_openai_params(+ optional_params = litellm.TogetherAIChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "vertex_ai" and (model in litellm.vertex_chat_models@@@ -3960,7 -4350,7 +4352,7 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "gemini":@@@ -3968,21 -4358,21 +4360,21 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "vertex_ai_beta" or (custom_llm_provider == "vertex_ai" and "gemini" in model):optional_params = litellm.VertexGeminiConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif litellm.VertexAIAnthropicConfig.is_supported_model(model=model, custom_llm_provider=custom_llm_provider):optional_params = litellm.VertexAIAnthropicConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "vertex_ai":if model in litellm.vertex_mistral_models:@@@ -3991,35 -4381,35 +4383,35 @@@model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)else:optional_params = litellm.MistralConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif model in litellm.vertex_ai_ai21_models:optional_params = litellm.VertexAIAi21Config().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif provider_config is not None:optional_params = provider_config.map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)else: # use generic openai-like param mappingoptional_params = litellm.VertexAILlama3Config().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "sagemaker":@@@ -4028,25 -4418,25 +4420,25 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "bedrock":- BedrockModelInfo = getattr(sys.modules[__name__], "BedrockModelInfo")- bedrock_route = BedrockModelInfo.get_bedrock_route(model)- bedrock_base_model = BedrockModelInfo.get_base_model(model)+ BedrockModelInfo: Final = getattr(sys.modules[__name__], "BedrockModelInfo")+ bedrock_route: Final = BedrockModelInfo.get_bedrock_route(model)+ bedrock_base_model: Final = BedrockModelInfo.get_base_model(model)if bedrock_route == "converse" or bedrock_route == "converse_like":optional_params = litellm.AmazonConverseConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif bedrock_route == "openai":optional_params = litellm.AmazonBedrockOpenAIConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif "anthropic" in bedrock_base_model and bedrock_route == "invoke":if bedrock_base_model in litellm.AmazonAnthropicConfig.get_legacy_anthropic_model_names():@@@ -4054,21 -4444,21 +4446,21 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)else:optional_params = litellm.AmazonAnthropicClaudeConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif provider_config is not None:optional_params = provider_config.map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)if bedrock_route == "claude_platform":optional_params = BedrockModelInfo.map_claude_platform_auth_params(@@@ -4079,28 -4469,28 +4471,28 @@@model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "ollama":optional_params = litellm.OllamaConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "ollama_chat":optional_params = litellm.OllamaChatConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "nlp_cloud":optional_params = litellm.NLPCloudConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "petals":@@@ -4108,35 -4498,35 +4500,35 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "deepinfra":optional_params = litellm.DeepInfraConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "perplexity" and provider_config is not None:optional_params = provider_config.map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "mistral" or custom_llm_provider == "codestral":optional_params = litellm.MistralConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "text-completion-codestral":optional_params = litellm.CodestralTextCompletionConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "text-completion-inception":@@@ -4144,7 -4534,7 +4536,7 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "databricks":@@@ -4152,21 -4542,21 +4544,21 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "nvidia_nim":optional_params = litellm.NvidiaNimConfig().map_openai_params(model=model,non_default_params=non_default_params,optional_params=optional_params,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "cerebras":optional_params = litellm.CerebrasConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "xai":optional_params = litellm.XAIChatConfig().map_openai_params(@@@ -4179,80 -4569,80 +4571,80 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "fireworks_ai":optional_params = litellm.FireworksAIConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "volcengine":optional_params = litellm.VolcEngineConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "hosted_vllm":optional_params = litellm.HostedVLLMChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "vllm":optional_params = litellm.VLLMConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "groq":optional_params = litellm.GroqChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "bedrock_mantle":optional_params = litellm.BedrockMantleChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "deepseek":optional_params = litellm.DeepSeekChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "tencent":optional_params = litellm.TencentChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "openrouter":optional_params = litellm.OpenrouterConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "watsonx":optional_params = litellm.IBMWatsonXChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)# WatsonX-text param check- for param in passed_params.keys():+ for param in passed_params:if litellm.IBMWatsonXAIConfig().is_watsonx_text_param(param):raise ValueError(f"LiteLLM now defaults to Watsonx's `/text/chat` endpoint. Please use the `watsonx_text` provider instead, to call the `/text/generation` endpoint. Param: {param}"@@@ -4262,37 -4652,37 +4654,37 @@@non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "openai":optional_params = litellm.OpenAIConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "nebius":optional_params = litellm.NebiusConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif custom_llm_provider == "azure":- _azure_detection_model = base_model or model+ _azure_detection_model: Final = base_model or modelif litellm.AzureOpenAIO1Config().is_o_series_model(model=_azure_detection_model):optional_params = litellm.AzureOpenAIO1Config().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=_azure_detection_model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model(model=_azure_detection_model):optional_params = litellm.AzureOpenAIGPT5Config().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=_azure_detection_model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)else:verbose_logger.debug(@@@ -4310,22 -4700,22 +4702,22 @@@non_default_params=non_default_params,optional_params=optional_params,model=_azure_detection_model,- api_version=api_version, # type: ignore- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),+ api_version=api_version,- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)elif provider_config is not None:optional_params = provider_config.map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)else: # assume passing in params for openai-like apioptional_params = litellm.OpenAILikeChatConfig().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,-- drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),++ drop_params=bool(drop_params),)# if user passed in non-default kwargs for specific providers/models, pass them alongoptional_params = add_provider_specific_params_to_optional_params(diff --cc tests/test_litellm/litellm_core_utils/test_core_helpers.pyindex a7f93e3c997,93cb01e1969..ab43141af23--- a/tests/test_litellm/litellm_core_utils/test_core_helpers.py+++ b/tests/test_litellm/litellm_core_utils/test_core_helpers.py@@@ -4,8 -4,8 +4,9 @@@ import pytesfrom litellm.litellm_core_utils.core_helpers import (_FINISH_REASON_MAP,+ get_or_create_metadata_bucket,map_finish_reason,+ normalize_drop_params,reconstruct_model_name,redact_nested_match_and_regex_keys,)@@@ -204,22 -257,80 +258,101 @@@ class TestRedactNestedMatchAndRegexKeysassert redact_nested_match_and_regex_keys("plain") == "plain"+ "value, expected",+ [+ (True, True),+ (False, False),+ ("true", True),+ ("True", True),+ (" TRUE ", True),+ ("false", False),+ ("False", False),+ (None, None),+ ("yes", None),+ ("", None),+ (1, None),+ (0, None),+ ],+)+def test_normalize_drop_params(value, expected):+ assert normalize_drop_params(value) is expected+++++ class TestIsExpectedClientError:+ def test_status_ranges(self):+ from litellm.litellm_core_utils.core_helpers import is_expected_client_error++ class WithStatusCode(Exception):+ def __init__(self, status_code):+ self.status_code = status_code++ class WithCode(Exception):+ def __init__(self, code):+ self.code = code++ assert is_expected_client_error(WithStatusCode(400)) is True+ assert is_expected_client_error(WithStatusCode(429)) is True+ assert is_expected_client_error(WithStatusCode(499)) is True+ assert is_expected_client_error(WithStatusCode(500)) is False+ assert is_expected_client_error(WithStatusCode(399)) is False+ assert is_expected_client_error(WithCode("403")) is True+ assert is_expected_client_error(WithCode("invalid_request_error")) is False+ assert is_expected_client_error(Exception("no status")) is False+ assert is_expected_client_error(None) is False++ def test_provider_originated_4xx_is_not_expected(self):+ """Regression for LIT-6163: a 4xx the provider returned is an upstream or+ deployment problem, so it keeps its traceback; only the proxy's own+ pre-call rejections (no llm_provider) are expected client errors."""+ from litellm.exceptions import AuthenticationError, RateLimitError+ from litellm.litellm_core_utils.core_helpers import is_expected_client_error+ from litellm.llms.anthropic.common_utils import AnthropicError+ from litellm.proxy.common_utils.proxy_rate_limit_error import ProxyRateLimitError++ provider_auth_failure = AuthenticationError(+ message="AnthropicException - API key is invalid.", llm_provider="anthropic", model="claude-haiku-4-5"+ )+ assert is_expected_client_error(provider_auth_failure) is False++ provider_rate_limit = RateLimitError(message="rate limited upstream", llm_provider="openai", model="gpt-4o")+ assert is_expected_client_error(provider_rate_limit) is False++ unmapped_provider_failure = AnthropicError(status_code=401, message='{"type":"authentication_error"}')+ assert is_expected_client_error(unmapped_provider_failure) is False++ proxy_rate_limit = ProxyRateLimitError(+ detail={"error": "Max parallel requests reached"}, model="claude-haiku-4-5", llm_provider="anthropic"+ )+ assert proxy_rate_limit.llm_provider == "anthropic"+ assert is_expected_client_error(proxy_rate_limit) is True++ class RouterRejection(Exception):+ def __init__(self):+ self.status_code = 429+ self.llm_provider = ""++ assert is_expected_client_error(RouterRejection()) is True++ def test_budget_rejection_decorated_with_provider_is_expected(self):+ """The auth handler stamps the requested model's provider onto the proxy's+ own BudgetExceededError before logging it, which must not turn a key-over-budget+ 429 into a provider error that keeps its traceback."""+ from litellm.exceptions import BudgetExceededError, RateLimitError, RateLimitErrorCategory+ from litellm.litellm_core_utils.core_helpers import is_expected_client_error++ over_budget = BudgetExceededError(current_cost=0.01, max_budget=0.0, llm_provider="anthropic")+ assert over_budget.llm_provider == "anthropic"+ assert is_expected_client_error(over_budget) is True++ litellm_limit = RateLimitError(+ message="key over rpm", llm_provider="anthropic", model="claude-haiku-4-5",+ category=RateLimitErrorCategory.LITELLM_RATE_LIMIT,+ )+ assert is_expected_client_error(litellm_limit) is True++ vendor_limit = RateLimitError(+ message="rate limited upstream", llm_provider="anthropic", model="claude-haiku-4-5",+ category=RateLimitErrorCategory.VENDOR_RATE_LIMIT,+ )+ assert is_expected_client_error(vendor_limit) is Falsediff --cc tests/test_litellm/test_router.pyindex 81927d7e959,eed34c79a06..201a4d84ebe--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@@ -5283,184 -14234,159 +14234,193 @@@ async def test_async_get_available_depl)- def test_get_deployment_credentials_returns_none_for_blocked_deployment():- router = _router_with_two_deployments([True, False])- assert router.get_deployment_credentials(model_id="dep-0") is None- assert router.get_deployment_credentials(model_id="dep-1") is not None-+ @pytest.mark.asyncio+ async def test_async_get_available_deployment_for_pass_through_failure_logging_is_coordinated():+ router = litellm.Router(+ model_list=[{"model_name": "gpt-5.6", "litellm_params": {"model": "openai/gpt-5.6", "api_key": "sk-fake"}}]+ )+ logging_obj = _make_failure_logging_obj()- def test_get_deployment_credentials_with_provider_returns_none_for_blocked_deployment():- router = _router_with_two_deployments([True, False])- assert router.get_deployment_credentials_with_provider(model_id="dep-0") is None- assert router.get_deployment_credentials_with_provider(model_id="dep-1") is not None+ await _assert_router_failure_logging_is_coordinated(+ logging_obj,+ lambda: router.async_get_available_deployment_for_pass_through(+ model="gpt-5.6",+ request_kwargs={"litellm_logging_obj": logging_obj},+ ),+ litellm.BadRequestError,+ )- def test_is_deployment_blocked_static_helper_reflects_blocked_flag():- """- Exercises Router._is_deployment_blocked so router_code_coverage.py (AST call graph)- marks the helper as covered by router-named tests.- """- import types+ class _InFlightTracker:+ def __init__(self) -> None:+ self.current = 0+ self.peak = 0- import litellm+ def enter(self) -> None:+ self.current += 1+ self.peak = max(self.peak, self.current)- router = _router_with_two_deployments([True, False])- blocked_dep = router.get_deployment("dep-0")- unblocked_dep = router.get_deployment("dep-1")- assert blocked_dep is not None and unblocked_dep is not None- assert litellm.Router._is_deployment_blocked(blocked_dep) is True- assert litellm.Router._is_deployment_blocked(unblocked_dep) is False+ def exit(self) -> None:+ self.current -= 1- # No model_info on deployment object → treated as not blocked- assert litellm.Router._is_deployment_blocked(object()) is False- missing_blocked = types.SimpleNamespace()- assert (- litellm.Router._is_deployment_blocked(- types.SimpleNamespace(model_info=missing_blocked)- )- is False- )- assert (- litellm.Router._is_deployment_blocked(- types.SimpleNamespace(model_info=types.SimpleNamespace(blocked=True))- )- is True- )+ _SSE_CHUNKS: Final[tuple[bytes, ...]] = tuple(+ b'data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"gpt-5.6",'+ b'"choices":[{"index":0,"delta":{"content":"x"},"finish_reason":null}]}\n\n'+ for _ in range(5)+ )- class TestRouterRequestTimeoutPropagation:- """litellm_settings.request_timeout must act as an independent per-attempt timeout.- Regression for LIT-2369: request_timeout was shadowed by router_settings.timeout,- so Bedrock (and other provider) calls fell back to the hardcoded 600s httpx- default instead of the configured value.- """+ class _CountingSSEStream(httpx.AsyncByteStream):+ def __init__(self, tracker: _InFlightTracker) -> None:+ self._tracker = tracker+ self._in_flight = False- def _make_router(self, timeout=None, stream_timeout=None):- return litellm.Router(- model_list=[- {- "model_name": "test-model",- "litellm_params": {- "model": "openai/gpt-4",- "api_key": "sk-test",- },- }- ],- timeout=timeout,- stream_timeout=stream_timeout,- )+ def _finish(self) -> None:+ if self._in_flight:+ self._in_flight = False+ self._tracker.exit()- @pytest.fixture- def explicit_request_timeout(self):- original_value = litellm.request_timeout- original_flag = litellm.request_timeout_explicitly_set- litellm.request_timeout = 300- litellm.request_timeout_explicitly_set = True+ async def __aiter__(self):+ self._in_flight = True+ self._tracker.enter()try:- yield 300+ for chunk in _SSE_CHUNKS:+ await asyncio.sleep(0.02)+ yield chunkfinally:- litellm.request_timeout = original_value- litellm.request_timeout_explicitly_set = original_flag+ await self.aclose()+ yield b"data: [DONE]\n\n"- def test_request_timeout_stored_independently_when_both_set(- self, explicit_request_timeout- ):- router = self._make_router(timeout=330)- assert router.timeout == 330- assert router.request_timeout == 300+ async def aclose(self) -> None:+ await asyncio.sleep(0.02)+ self._finish()- def test_request_timeout_none_when_not_explicitly_configured(self):- original_value = litellm.request_timeout- original_flag = litellm.request_timeout_explicitly_set- litellm.request_timeout = litellm.constants.DEFAULT_REQUEST_TIMEOUT_SECONDS- litellm.request_timeout_explicitly_set = False- try:- router = self._make_router(timeout=330)- assert router.timeout == 330- assert router.request_timeout is None- finally:- litellm.request_timeout = original_value- litellm.request_timeout_explicitly_set = original_flag- def test_non_stream_prefers_request_timeout_over_router_timeout(- self, explicit_request_timeout- ):- router = self._make_router(timeout=330)- assert router._get_non_stream_timeout(kwargs={}, data={}) == 300+ def _max_parallel_router(max_parallel_requests: int) -> Router:+ return Router(+ model_list=[+ {+ "model_name": "gpt-5.6",+ "litellm_params": {+ "model": "openai/gpt-5.6",+ "api_key": "sk-fake",+ "api_base": "https://max-parallel.local/v1",+ "max_parallel_requests": max_parallel_requests,+ },+ }+ ],+ num_retries=0,+ )- def test_stream_prefers_request_timeout_over_router_timeout(- self, explicit_request_timeout- ):- router = self._make_router(timeout=330)- # stream=True resolves through _get_stream_timeout; request_timeout must win.- assert router._get_timeout(kwargs={"stream": True}, data={}) == 300- def test_explicit_stream_timeout_still_wins_over_request_timeout(- self, explicit_request_timeout- ):- router = self._make_router(timeout=330, stream_timeout=45)- assert router._get_stream_timeout(kwargs={}, data={}) == 45+ @pytest.mark.asyncio+ @pytest.mark.parametrize("stream", [False, True])+ async def test_router_max_parallel_requests_bounds_in_flight_upstream_calls(+ monkeypatch: pytest.MonkeyPatch, stream: bool+ ):+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ tracker: Final = _InFlightTracker()+ router: Final = _max_parallel_router(max_parallel_requests=2)++ async def upstream(request: httpx.Request) -> httpx.Response:+ if stream:+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=_CountingSSEStream(tracker)+ )+ tracker.enter()+ await asyncio.sleep(0.05)+ tracker.exit()+ return httpx.Response(+ 200,+ json={+ "id": "c",+ "object": "chat.completion",+ "created": 1,+ "model": "gpt-5.6",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "x"}, "finish_reason": "stop"}],+ },+ )- def test_non_stream_falls_through_to_router_timeout_without_request_timeout(self):- original_value = litellm.request_timeout- original_flag = litellm.request_timeout_explicitly_set- litellm.request_timeout = litellm.constants.DEFAULT_REQUEST_TIMEOUT_SECONDS- litellm.request_timeout_explicitly_set = False- try:- router = self._make_router(timeout=330)- assert router._get_non_stream_timeout(kwargs={}, data={}) == 330- finally:- litellm.request_timeout = original_value- litellm.request_timeout_explicitly_set = original_flag+ async def one_call() -> None:+ response = await router.acompletion(+ model="gpt-5.6", messages=[{"role": "user", "content": "hi"}], stream=stream+ )+ if stream:+ async for _ in response:+ pass- def test_per_deployment_timeout_overrides_request_timeout(- self, explicit_request_timeout- ):- router = self._make_router(timeout=330)- assert router._get_non_stream_timeout(kwargs={}, data={"timeout": 120}) == 120+ with respx.mock(assert_all_called=True) as respx_mock:+ respx_mock.post("https://max-parallel.local/v1/chat/completions").mock(side_effect=upstream)+ await asyncio.wait_for(asyncio.gather(*(one_call() for _ in range(10))), timeout=10)- def test_per_request_timeout_overrides_request_timeout(- self, explicit_request_timeout- ):- router = self._make_router(timeout=330)- assert (- router._get_non_stream_timeout(- kwargs={"timeout": 60}, data={"timeout": 120}+ assert tracker.peak <= 2+ assert tracker.current == 0+++ @pytest.mark.asyncio+ async def test_router_max_parallel_requests_slot_released_when_stream_closed_early(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ tracker: Final = _InFlightTracker()+ router: Final = _max_parallel_router(max_parallel_requests=1)++ with respx.mock() as respx_mock:+ respx_mock.post("https://max-parallel.local/v1/chat/completions").mock(+ side_effect=lambda request: httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=_CountingSSEStream(tracker))- == 60)+ first: Final = await router.acompletion(+ model="gpt-5.6", messages=[{"role": "user", "content": "hi"}], stream=True+ )+ await first.__anext__()++ async def second_call() -> None:+ second = await router.acompletion(+ model="gpt-5.6", messages=[{"role": "user", "content": "hi"}], stream=True+ )+ async for _ in second:+ pass++ second_task: Final = asyncio.create_task(second_call())+ await asyncio.sleep(0.05)+ assert tracker.current == 1+ await first.aclose()+ await asyncio.wait_for(second_task, timeout=2)++ assert tracker.peak == 1+ assert tracker.current == 0+++async def test_router_deployment_drop_params_string_true_is_honored(monkeypatch):+ from litellm import Router++ monkeypatch.setattr(litellm, "drop_params", False)+ router = Router(+ model_list=[+ {+ "model_name": "gpt-5-nano",+ "litellm_params": {+ "model": "openai/gpt-5-nano",+ "api_key": "sk-fake",+ "temperature": 1,+ "reasoning_effort": "minimal",+ "drop_params": "true",+ "mock_response": "Hello, world!",+ },+ }+ ],+ num_retries=0,+ )++ deployment = router.get_deployment_by_model_group_name(model_group_name="gpt-5-nano")+ assert deployment is not None+ assert deployment.litellm_params.drop_params is True++ response = await router.acompletion(+ model="gpt-5-nano",+ messages=[{"role": "user", "content": "hi"}],+ temperature=0.1,+ )+ assert response.choices[0].message.content == "Hello, world!"diff --cc tests/test_litellm/test_utils.pyindex 0fbf9c0db20,8a56a84ade7..c65af1179a6--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@@ -3178,1667 -4039,2056 +4039,2084 @@@ def test_deepseek_v4_models_in_cost_mapwith 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",+ # --- bare model names ---+ for key, expected_input, expected_output, expected_cache in [+ ("deepseek-v4-flash", 4.4e-07, 1.32e-06, 1.4e-08),+ ("deepseek-v4-pro", 1.32e-06, 3.96e-06, 4.4e-08),]: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 is not None, f"{key} missing from model_prices_and_context_window.json"+ assert info["litellm_provider"] == "deepseek"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+ assert info["input_cost_per_token"] == expected_input+ assert info["output_cost_per_token"] == expected_output+ assert info["cache_read_input_token_cost"] == expected_cache+ assert info["max_input_tokens"] == 1_000_000+ assert info["supports_function_calling"] is True+ assert info["supports_tool_choice"] is True- # minimax-m2p1: short-form and long-form- for key in [- "fireworks_ai/minimax-m2p1",- "fireworks_ai/accounts/fireworks/models/minimax-m2p1",+ # --- provider-prefixed names ---+ for key, expected_input, expected_output, expected_cache in [+ ("deepseek/deepseek-v4-flash", 4.4e-07, 1.32e-06, 1.4e-08),+ ("deepseek/deepseek-v4-pro", 1.32e-06, 3.96e-06, 4.4e-08),]: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 is not None, f"{key} missing from model_prices_and_context_window.json"+ assert info["litellm_provider"] == "deepseek"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"""-- def test_get_valid_models_with_cli_pattern(self):- """Test get_valid_models with litellm_proxy provider and CLI token pattern"""-- # Mock the HTTP request that get_valid_models makes to the proxy- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {- "data": [- {"id": "gpt-3.5-turbo", "object": "model"},- {"id": "gpt-4", "object": "model"},- {"id": "litellm_proxy/gemini/gemini-2.5-flash", "object": "model"},- {"id": "claude-3-sonnet", "object": "model"},- ]- }-- 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,- custom_llm_provider="litellm_proxy",- api_key="sk-test-cli-key-123",- api_base="http://localhost:4000/",- )-- # Verify the function returns a list of model names- assert isinstance(result, list)- assert len(result) == 4- # All models get prefixed with "litellm_proxy/" by the get_models method- assert "litellm_proxy/gpt-3.5-turbo" in result- assert "litellm_proxy/gpt-4" in result- # Note: This model already had the prefix, so it gets double-prefixed- assert "litellm_proxy/litellm_proxy/gemini/gemini-2.5-flash" in result- assert "litellm_proxy/claude-3-sonnet" in result-- # Verify the HTTP request was made with correct parameters- mock_get.assert_called_once()- _, call_kwargs = mock_get.call_args-- # Check that the request was made to the correct endpoint- assert call_kwargs["url"].startswith("http://localhost:4000/")- assert call_kwargs["url"].endswith("/v1/models")-- # Check that the API key was included in headers- assert "headers" in call_kwargs- headers = call_kwargs["headers"]- assert headers.get("Authorization") == "Bearer sk-test-cli-key-123"-+ assert info["input_cost_per_token"] == expected_input+ assert info["output_cost_per_token"] == expected_output+ assert info["cache_read_input_token_cost"] == expected_cache+ assert info["supports_function_calling"] is True+ assert info["supports_tool_choice"] is True- class TestIsCachedMessage:- """Test is_cached_message function for context caching detection.- Fixes GitHub issue #17821 - TypeError when content is string instead of list.+ def test_deepseek_v4_models_in_backup_cost_map():"""+ Test that deepseek-v4-flash and deepseek-v4-pro entries are correctly+ configured in litellm/model_prices_and_context_window_backup.json.+ """+ import json+ from pathlib import Path- def test_string_content_returns_false(self):- """String content should return False without crashing."""- message = {"role": "user", "content": "Hello world"}- assert is_cached_message(message) is False-- def test_none_content_returns_false(self):- """None content should return False."""- message = {"role": "user", "content": None}- assert is_cached_message(message) is False-- def test_missing_content_returns_false(self):- """Message without content key should return False."""- message = {"role": "user"}- assert is_cached_message(message) is False-- def test_list_content_without_cache_control_returns_false(self):- """List content without cache_control should return False."""- message = {"role": "user", "content": [{"type": "text", "text": "Hello"}]}- assert is_cached_message(message) is False-- def test_list_content_with_cache_control_returns_true(self):- """List content with cache_control ephemeral should return True."""- message = {- "role": "user",- "content": [- {- "type": "text",- "text": "Hello",- "cache_control": {"type": "ephemeral"},- }- ],- }- assert is_cached_message(message) is True-- def test_list_with_non_dict_items_skips_them(self):- """List content with non-dict items should skip them gracefully."""- message = {- "role": "user",- "content": ["string_item", 123, {"type": "text", "text": "Hello"}],- }- assert is_cached_message(message) is False-- def test_list_with_mixed_items_finds_cached(self):- """Mixed content list should find cached item."""- message = {- "role": "user",- "content": [- "string_item",- {"type": "image", "url": "..."},- {- "type": "text",- "text": "cached",- "cache_control": {"type": "ephemeral"},- },- ],- }- assert is_cached_message(message) is True-- def test_wrong_cache_control_type_returns_false(self):- """Non-ephemeral cache_control type should return False."""- message = {- "role": "user",- "content": [- {- "type": "text",- "text": "Hello",- "cache_control": {"type": "permanent"},- }- ],- }- assert is_cached_message(message) is False-- def test_empty_list_content_returns_false(self):- """Empty list content should return False."""- message = {"role": "user", "content": []}- assert is_cached_message(message) is False-- def test_message_level_cache_control_returns_true(self):- """Message with string content and message-level cache_control should return True.+ 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)- This is the format injected by the cache_control_injection_points hook- when the message content is a string (common for system messages).- Fixes GitHub issue #18519 - Gemini models ignoring cache_control_injection_points.- """- message = {- "role": "system",- "content": "You are a helpful assistant.",- "cache_control": {"type": "ephemeral"},- }- assert is_cached_message(message) is True+ # --- bare model names ---+ for key, expected_input, expected_output, expected_cache in [+ ("deepseek-v4-flash", 4.4e-07, 1.32e-06, 1.4e-08),+ ("deepseek-v4-pro", 1.32e-06, 3.96e-06, 4.4e-08),+ ]:+ info = model_cost.get(key)+ assert info is not None, f"{key} missing from backup JSON"+ assert info["litellm_provider"] == "deepseek"+ assert info["mode"] == "chat"+ assert info["input_cost_per_token"] == expected_input+ assert info["output_cost_per_token"] == expected_output+ assert info["cache_read_input_token_cost"] == expected_cache+ assert info["max_input_tokens"] == 1_000_000- def test_message_level_cache_control_wrong_type_returns_false(self):- """Message-level cache_control with non-ephemeral type should return False."""- message = {- "role": "system",- "content": "You are a helpful assistant.",- "cache_control": {"type": "permanent"},- }- assert is_cached_message(message) is False+ # --- provider-prefixed names ---+ for key, expected_input, expected_output, expected_cache in [+ ("deepseek/deepseek-v4-flash", 4.4e-07, 1.32e-06, 1.4e-08),+ ("deepseek/deepseek-v4-pro", 1.32e-06, 3.96e-06, 4.4e-08),+ ]:+ info = model_cost.get(key)+ assert info is not None, f"{key} missing from backup JSON"+ assert info["litellm_provider"] == "deepseek"+ assert info["mode"] == "chat"+ assert info["input_cost_per_token"] == expected_input+ assert info["output_cost_per_token"] == expected_output+ assert info["cache_read_input_token_cost"] == expected_cache- def test_message_level_cache_control_non_dict_returns_false(self):- """Message-level cache_control that's not a dict should return False."""- message = {- "role": "system",- "content": "You are a helpful assistant.",- "cache_control": "ephemeral",- }- assert is_cached_message(message) is False+ _FIREWORKS_MODELS = [+ (+ "accounts/fireworks/models/glm-5p2",+ 1.4e-06,+ 4.4e-06,+ 1.4e-07,+ 1048576,+ 131072,+ False,+ True,+ ),+ (+ "accounts/fireworks/models/glm-5p1",+ 1.4e-06,+ 4.4e-06,+ 2.6e-07,+ 202800,+ 131072,+ False,+ True,+ ),+ (+ "accounts/fireworks/routers/glm-5p1-fast",+ 2.8e-06,+ 8.8e-06,+ 5.2e-07,+ 202800,+ 131072,+ False,+ True,+ ),+ (+ "accounts/fireworks/models/qwen3p7-plus",+ 4e-07,+ 1.6e-06,+ 8e-08,+ 262144,+ 65536,+ True,+ True,+ ),+ (+ "accounts/fireworks/models/minimax-m3",+ 3e-07,+ 1.2e-06,+ 6e-08,+ 512000,+ 512000,+ True,+ True,+ ),+ (+ "accounts/fireworks/models/minimax-m2p7",+ 3e-07,+ 1.2e-06,+ 6e-08,+ 196608,+ 196608,+ False,+ True,+ ),+ (+ "accounts/fireworks/models/kimi-k2p7-code",+ 9.5e-07,+ 4e-06,+ 1.9e-07,+ 262144,+ 32768,+ True,+ True,+ ),+ (+ "accounts/fireworks/routers/kimi-k2p7-code-fast",+ 1.9e-06,+ 8e-06,+ 3.8e-07,+ 262144,+ 32768,+ True,+ True,+ ),+ (+ "accounts/fireworks/models/kimi-k2p6",+ 9.5e-07,+ 4e-06,+ 1.6e-07,+ 262144,+ 32768,+ True,+ True,+ ),+ (+ "accounts/fireworks/routers/kimi-k2p6-fast",+ 2e-06,+ 8e-06,+ 3e-07,+ 262144,+ 32768,+ True,+ True,+ ),+ (+ "accounts/fireworks/models/gpt-oss-120b",+ 1.5e-07,+ 6e-07,+ 1.5e-08,+ 131072,+ 32768,+ False,+ True,+ ),+ (+ "accounts/fireworks/models/gpt-oss-20b",+ 7e-08,+ 3e-07,+ 3.5e-08,+ 131072,+ 32768,+ False,+ True,+ ),+ (+ "accounts/fireworks/models/deepseek-v4-pro",+ 1.74e-06,+ 3.48e-06,+ 1.45e-07,+ 1048576,+ 384000,+ False,+ True,+ ),+ (+ "accounts/fireworks/models/deepseek-v4-flash",+ 1.4e-07,+ 2.8e-07,+ 2.8e-08,+ 1048576,+ 384000,+ False,+ True,+ ),+ ]++ _FIREWORKS_SHORT_FORMS = [+ "glm-5p2",+ "glm-5p1",+ "qwen3p7-plus",+ "minimax-m3",+ "minimax-m2p7",+ "kimi-k2p7-code",+ "kimi-k2p6",+ "gpt-oss-120b",+ "gpt-oss-20b",+ "deepseek-v4-pro",+ "deepseek-v4-flash",+ ]- @pytest.mark.asyncio- class TestProxyLoggingBudgetAlerts:- """Test budget_alerts method in ProxyLogging class."""+ _FIREWORKS_ROUTER_SHORT_FORMS = [+ "glm-5p1-fast",+ "kimi-k2p6-fast",+ "kimi-k2p7-code-fast",+ ]- async def test_budget_alerts_when_alerting_is_none(self):- """Test that budget_alerts returns early when alerting is None."""- from litellm.caching.caching import DualCache- from litellm.proxy.utils import ProxyLogging- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = None- proxy_logging.slack_alerting_instance = AsyncMock()- proxy_logging.email_logging_instance = AsyncMock()+ def _assert_fireworks_entry(+ model_cost,+ model_path,+ expected_input,+ expected_output,+ expected_cache,+ expected_max_input,+ expected_max_output,+ expected_vision,+ expected_reasoning,+ ):+ info = model_cost.get(f"fireworks_ai/{model_path}")+ assert info is not None, f"fireworks_ai/{model_path} missing from model cost map"+ assert info["litellm_provider"] == "fireworks_ai"+ assert info["mode"] == "chat"+ assert info["input_cost_per_token"] == expected_input+ assert info["output_cost_per_token"] == expected_output+ assert info["cache_read_input_token_cost"] == expected_cache+ 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+ assert info["supports_response_schema"] is True+ assert info["supports_vision"] is expected_vision- user_info = MagicMock()- # Should return without calling any alerting instances- await proxy_logging.budget_alerts(type="user_budget", user_info=user_info)+ def test_fireworks_models_in_cost_map():+ import json+ from pathlib import Path- # Verify no calls were made- proxy_logging.slack_alerting_instance.budget_alerts.assert_not_called()- proxy_logging.email_logging_instance.budget_alerts.assert_not_called()+ json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json"+ with open(json_path) as f:+ model_cost = json.load(f)- async def test_budget_alerts_with_slack_only(self):- """Test that budget_alerts calls slack_alerting_instance when slack is in alerting."""- from litellm.caching.caching import DualCache- from litellm.proxy.utils import ProxyLogging+ for entry in _FIREWORKS_MODELS:+ _assert_fireworks_entry(model_cost, *entry)- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = ["slack"]- proxy_logging.slack_alerting_instance = AsyncMock()+ 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}"- user_info = MagicMock()+ 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}"- await proxy_logging.budget_alerts(type="token_budget", user_info=user_info)- proxy_logging.slack_alerting_instance.budget_alerts.assert_called_once_with(- type="token_budget", user_info=user_info- )+ def test_fireworks_models_in_backup_cost_map():+ import json+ from pathlib import Path- async def test_budget_alerts_with_email_only(self):- """Test that budget_alerts calls email_logging_instance when email is in alerting."""- from litellm.caching.caching import DualCache- from litellm.proxy.utils import ProxyLogging+ 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)- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = ["email"]- proxy_logging.email_logging_instance = AsyncMock()+ for entry in _FIREWORKS_MODELS:+ _assert_fireworks_entry(model_cost, *entry)- user_info = MagicMock()+ 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}"- await proxy_logging.budget_alerts(type="team_budget", user_info=user_info)+ 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}"- proxy_logging.email_logging_instance.budget_alerts.assert_called_once_with(- type="team_budget", user_info=user_info- )- async def test_budget_alerts_with_email_when_instance_is_none(self):- """Test that budget_alerts does not call email_logging_instance when it is None."""- from litellm.caching.caching import DualCache- from litellm.proxy.utils import ProxyLogging+ 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``."""- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = ["email"]- proxy_logging.email_logging_instance = None+ TOOLS = [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "parameters": {+ "type": "object",+ "properties": {"city": {"type": "string"}},+ },+ },+ }+ ]- user_info = MagicMock()+ def test_base_model_label_keeps_tools_with_drop_params(self):+ from litellm.utils import get_optional_params- # Should not raise an error- await proxy_logging.budget_alerts(- type="organization_budget", user_info=user_info+ result = get_optional_params(+ model="eu.anthropic.claude-haiku-4-5-20251001-v1:0",+ custom_llm_provider="bedrock",+ base_model="claude-haiku-4-5",+ tools=self.TOOLS,+ tool_choice="auto",+ drop_params=True,)- 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."""- from litellm.caching.caching import DualCache- from litellm.proxy.utils import ProxyLogging+ assert "tools" in result+ assert "tool_choice" in result- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = ["slack", "email"]- proxy_logging.slack_alerting_instance = AsyncMock()- proxy_logging.email_logging_instance = AsyncMock()+ def test_base_model_label_alone_drops_tools(self):+ """Without the real model id the label resolves to no tool support, so passing+ the label as ``model`` is exactly what dropped tools before the fix."""+ from litellm.utils import get_optional_params- user_info = MagicMock()+ result = get_optional_params(+ model="claude-haiku-4-5",+ custom_llm_provider="bedrock",+ tools=self.TOOLS,+ tool_choice="auto",+ drop_params=True,+ )- await proxy_logging.budget_alerts(type="proxy_budget", user_info=user_info)+ assert "tools" not in result- proxy_logging.slack_alerting_instance.budget_alerts.assert_called_once_with(- type="proxy_budget", user_info=user_info- )- proxy_logging.email_logging_instance.budget_alerts.assert_called_once_with(- type="proxy_budget", user_info=user_info- )- @pytest.mark.parametrize(- "alert_type",- [- "token_budget",- "user_budget",- "soft_budget",- "team_budget",- "organization_budget",- "proxy_budget",- "projected_limit_exceeded",- ],+ def test_aws_bedrock_project_id_excluded_from_bedrock_optional_params():+ """`aws_bedrock_project_id` is sent as a bedrock-mantle request header, so it+ must never reach optional_params (and from there the request body), while+ other aws_* params keep flowing for boto3 auth."""+ from litellm.utils import get_optional_params++ result = get_optional_params(+ model="mantle/anthropic.claude-mythos-preview",+ custom_llm_provider="bedrock",+ max_tokens=10,+ aws_bedrock_project_id="proj_abc123def456",+ aws_region_name="us-east-1",)- async def test_budget_alerts_with_all_alert_types(self, alert_type):- """Test that budget_alerts works with all supported alert types."""- from litellm.caching.caching import DualCache- from litellm.proxy.utils import ProxyLogging- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = ["slack", "email"]- proxy_logging.slack_alerting_instance = AsyncMock()- proxy_logging.email_logging_instance = AsyncMock()+ assert "aws_bedrock_project_id" not in result+ assert result["aws_region_name"] == "us-east-1"- user_info = MagicMock()- await proxy_logging.budget_alerts(type=alert_type, user_info=user_info)+ class TestGetOptionalParamsTencent:+ """Tests that tencent provider uses TencentChatConfig for parameter mapping."""- 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- )+ def test_tencent_supports_thinking_param(self):+ """Verify get_optional_params for tencent accepts the 'thinking' param.- async def test_budget_alerts_soft_budget_with_alert_emails_bypasses_alerting_none(- self,- ):+ `thinking` must be nested in extra_body: tencent routes through the+ OpenAI SDK's chat.completions.create(), which rejects unknown kwargs."""- Test that soft_budget alerts with alert_emails bypass the alerting=None check- and send emails even when alerting is None.+ from unittest.mock import patch- This tests the new logic that allows team-specific soft budget email alerts- via metadata.soft_budget_alerting_emails to work even when global alerting is disabled.- """- from litellm.caching.caching import DualCache- from litellm.proxy._types import CallInfo, Litellm_EntityType- from litellm.proxy.utils import ProxyLogging+ from litellm.utils import get_optional_params- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = None # Global alerting is disabled- proxy_logging.slack_alerting_instance = AsyncMock()- proxy_logging.email_logging_instance = AsyncMock()+ with patch(+ "litellm.llms.tencent.chat.transformation.supports_reasoning",+ return_value=True,+ ):+ result = get_optional_params(+ model="tencent/deepseek-v4-pro",+ custom_llm_provider="tencent",+ thinking={"type": "enabled"},+ )+ assert "thinking" not in result+ assert result["extra_body"]["thinking"] == {"type": "enabled"}- # Create CallInfo with alert_emails set (simulating team metadata extraction)- user_info = CallInfo(- token="test-token",- spend=100.0,- soft_budget=50.0,- user_id="test-user",- team_id="test-team",- team_alias="test-team-alias",- event_group=Litellm_EntityType.TEAM,- alert_emails=["[email protected]", "[email protected]"],- )+ def test_tencent_supports_reasoning_effort(self):+ """Verify get_optional_params for tencent converts reasoning_effort to thinking."""+ from unittest.mock import patch- # Should send email even though alerting is None (because of alert_emails)- await proxy_logging.budget_alerts(type="soft_budget", user_info=user_info)+ from litellm.utils import get_optional_params- # Verify slack was NOT called (alerting is None)- proxy_logging.slack_alerting_instance.budget_alerts.assert_not_called()+ with patch(+ "litellm.llms.tencent.chat.transformation.supports_reasoning",+ return_value=True,+ ):+ result = get_optional_params(+ model="tencent/deepseek-v4-pro",+ custom_llm_provider="tencent",+ reasoning_effort="medium",+ )+ assert "thinking" not in result+ assert result["extra_body"]["thinking"] == {"type": "enabled"}- # Verify email WAS called (bypasses alerting=None check)- proxy_logging.email_logging_instance.budget_alerts.assert_called_once_with(- type="soft_budget", user_info=user_info+ def test_tencent_supported_params_includes_thinking_and_reasoning_effort(self):+ """Verify get_supported_openai_params for tencent includes custom params."""+ from unittest.mock import patch++ from litellm.litellm_core_utils.get_supported_openai_params import (+ get_supported_openai_params,)- async def test_budget_alerts_soft_budget_without_alert_emails_respects_alerting_none(- self,- ):- """- Test that soft_budget alerts WITHOUT alert_emails still respect alerting=None- and do not send emails when alerting is None.- """- from litellm.caching.caching import DualCache- from litellm.proxy._types import CallInfo, Litellm_EntityType- from litellm.proxy.utils import ProxyLogging+ with patch(+ "litellm.llms.tencent.chat.transformation.supports_reasoning",+ return_value=True,+ ):+ params = get_supported_openai_params(+ model="tencent/deepseek-v4-pro",+ custom_llm_provider="tencent",+ )+ assert "thinking" in params+ assert "reasoning_effort" in params- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = None- proxy_logging.slack_alerting_instance = AsyncMock()- proxy_logging.email_logging_instance = AsyncMock()+ def test_tencent_messages_config_routing(self):+ """Verify ProviderConfigManager routes tencent to TencentAnthropicMessagesConfig."""+ import litellm+ from litellm.llms.tencent.messages.transformation import (+ TencentAnthropicMessagesConfig,+ )- # Create CallInfo WITHOUT alert_emails- user_info = CallInfo(- token="test-token",- spend=100.0,- soft_budget=50.0,- user_id="test-user",- team_id="test-team",- team_alias="test-team-alias",- event_group=Litellm_EntityType.TEAM,- alert_emails=None, # No alert emails+ config = ProviderConfigManager.get_provider_anthropic_messages_config(+ model="deepseek-v4-pro",+ provider=litellm.LlmProviders.TENCENT,)+ assert isinstance(config, TencentAnthropicMessagesConfig)+ assert config.custom_llm_provider == "tencent"- # Should NOT send email (alerting is None and no alert_emails)- await proxy_logging.budget_alerts(type="soft_budget", user_info=user_info)- # Verify no calls were made- proxy_logging.slack_alerting_instance.budget_alerts.assert_not_called()- proxy_logging.email_logging_instance.budget_alerts.assert_not_called()+ class TestValidateEnvironmentTencent:+ """Tests that validate_environment resolves TENCENT_API_KEY for the tencent provider."""- async def test_budget_alerts_soft_budget_with_empty_alert_emails_respects_alerting_none(- self,- ):- """- Test that soft_budget alerts with empty alert_emails list still respect alerting=None.- """- from litellm.caching.caching import DualCache- from litellm.proxy._types import CallInfo, Litellm_EntityType- from litellm.proxy.utils import ProxyLogging+ def test_reports_key_present(self):+ with patch.dict(os.environ, {"TENCENT_API_KEY": "sk-tencent"}):+ result = litellm.validate_environment(model="tencent/deepseek-v4-pro")- proxy_logging = ProxyLogging(user_api_key_cache=DualCache())- proxy_logging.alerting = None- proxy_logging.slack_alerting_instance = AsyncMock()- proxy_logging.email_logging_instance = AsyncMock()+ assert result["keys_in_environment"] is True+ assert result["missing_keys"] == []- # Create CallInfo with empty alert_emails list- user_info = CallInfo(- token="test-token",- spend=100.0,- soft_budget=50.0,- user_id="test-user",- team_id="test-team",- team_alias="test-team-alias",- event_group=Litellm_EntityType.TEAM,- alert_emails=[], # Empty list+ def test_reports_key_missing(self):+ with patch.dict(os.environ, {}, clear=True):+ result = litellm.validate_environment(model="tencent/deepseek-v4-pro")++ assert result["keys_in_environment"] is False+ assert "TENCENT_API_KEY" in result["missing_keys"]+++ class TestVertexEmbeddingEncodingFormat:+ """vertex_ai/gemini embeddings must accept encoding_format="float" — it's+ the OpenAI SDK default and float lists are exactly what the vertex API+ returns. Other values keep the unsupported-param behavior (drop with+ drop_params, raise otherwise). Issue #33173."""++ def test_encoding_format_float_is_accepted_and_dropped(self):+ optional_params = litellm.utils.get_optional_params_embeddings(+ model="gemini-embedding-001",+ encoding_format="float",+ custom_llm_provider="vertex_ai",)+ assert "encoding_format" not in optional_params- # Should NOT send email (alert_emails is empty)- await proxy_logging.budget_alerts(type="soft_budget", user_info=user_info)+ def test_encoding_format_float_accepted_for_gemini_provider(self):+ optional_params = litellm.utils.get_optional_params_embeddings(+ model="gemini-embedding-001",+ encoding_format="float",+ custom_llm_provider="gemini",+ )+ 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:+ litellm.utils.get_optional_params_embeddings(+ model="gemini-embedding-001",+ encoding_format="base64",+ custom_llm_provider="vertex_ai",+ )+ assert "encoding_format" in str(excinfo.value)- # Verify no calls were made- proxy_logging.slack_alerting_instance.budget_alerts.assert_not_called()- proxy_logging.email_logging_instance.budget_alerts.assert_not_called()+ def test_encoding_format_base64_dropped_with_drop_params(self):+ optional_params = litellm.utils.get_optional_params_embeddings(+ model="gemini-embedding-001",+ encoding_format="base64",+ custom_llm_provider="vertex_ai",+ drop_params=True,+ )+ assert "encoding_format" not in optional_params+ def test_dimensions_still_mapped(self):+ optional_params = litellm.utils.get_optional_params_embeddings(+ model="gemini-embedding-001",+ encoding_format="float",+ dimensions=256,+ custom_llm_provider="vertex_ai",+ )+ assert optional_params.get("outputDimensionality") == 256- def test_azure_ai_claude_provider_config():- """Test that Azure AI Claude models return AzureAnthropicConfig for proper tool transformation."""- from litellm import AzureAIStudioConfig, AzureAnthropicConfig- from litellm.utils import ProviderConfigManager- # Claude models should return AzureAnthropicConfig- config = ProviderConfigManager.get_provider_chat_config(- model="claude-sonnet-4-5",- provider=LlmProviders.AZURE_AI,- )- assert isinstance(config, AzureAnthropicConfig)+ class TestBedrockCohereEmbeddingDispatch:+ """All bedrock cohere.embed models must route to BedrockCohereEmbeddingConfig,+ not just multilingual-v3/v4: english-v3 was falling into the unmapped+ else-branch and rejecting encoding_format. Issue #38659."""- # Test case-insensitive matching- config = ProviderConfigManager.get_provider_chat_config(- model="Claude-Opus-4",- provider=LlmProviders.AZURE_AI,+ @pytest.mark.parametrize(+ "model",+ [+ "cohere.embed-english-v3",+ "cohere.embed-multilingual-v3",+ "cohere.embed-v4:0",+ ],)- assert isinstance(config, AzureAnthropicConfig)+ def test_cohere_embed_models_accept_encoding_format(self, model):+ optional_params = litellm.utils.get_optional_params_embeddings(+ model=model,+ encoding_format="float",+ custom_llm_provider="bedrock",+ )+ assert optional_params.get("embedding_types") == ["float"]- # Non-Claude models should return AzureAIStudioConfig- config = ProviderConfigManager.get_provider_chat_config(- model="mistral-large",- provider=LlmProviders.AZURE_AI,+ @pytest.mark.parametrize(+ "model",+ [+ "cohere.embed-english-v3",+ "cohere.embed-multilingual-v3",+ "cohere.embed-v4:0",+ ],)- assert isinstance(config, AzureAIStudioConfig)+ def test_cohere_embed_models_map_base64_to_float(self, model):+ optional_params = litellm.utils.get_optional_params_embeddings(+ model=model,+ encoding_format="base64",+ custom_llm_provider="bedrock",+ )+ assert optional_params.get("embedding_types") == ["float"]+ def test_cohere_embed_english_v3_maps_dimensions(self):+ optional_params = litellm.utils.get_optional_params_embeddings(+ model="cohere.embed-english-v3",+ encoding_format="float",+ dimensions=512,+ custom_llm_provider="bedrock",+ )+ assert optional_params.get("output_dimension") == 512- # Tests for thinking blocks helper functions- # Related to issue: https://github.com/BerriAI/litellm/issues/18926+ @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."+ )- def test_any_assistant_message_has_thinking_blocks_with_thinking():- """Test that function returns True when any assistant message has thinking_blocks."""- from litellm.utils import any_assistant_message_has_thinking_blocks- messages = [- {"role": "user", "content": "Hello"},- {- "role": "assistant",- "thinking_blocks": [{"type": "thinking", "thinking": "Let me think..."}],- "tool_calls": [{"id": "123", "function": {"name": "test"}}],- },- {"role": "tool", "tool_call_id": "123", "content": "result"},- {- "role": "assistant",- "tool_calls": [{"id": "456", "function": {"name": "test2"}}],- # No thinking_blocks here - Claude sometimes doesn't include them- },- ]+ PROMPT_CACHE_MESSAGES = [{"role": "user", "content": "the quick brown fox jumps over the lazy dog " * 155}]- assert any_assistant_message_has_thinking_blocks(messages) is True+ @pytest.mark.parametrize(+ "model, expected_min_tokens",+ [+ ("claude-opus-4-6", 4096),+ ("claude-opus-4-7", 2048),+ ("claude-opus-4-8", 1024),+ ("claude-fable-5", 512),+ ],+ )+ def test_get_prompt_cache_min_tokens_resolves_per_model(+ model: str, expected_min_tokens: int, local_model_cost_map: None+ ) -> None:+ """The smallest cacheable prefix is a per-model property, read from the cost map's+ prompt_cache_min_tokens. Anthropic's minimum spans 512..4096 across models and moves in both+ directions across releases, so a single global constant is wrong for every model but one."""+ assert get_prompt_cache_min_tokens(model=model) == expected_min_tokens- def test_any_assistant_message_has_thinking_blocks_without_thinking():- """Test that function returns False when no assistant message has thinking_blocks."""- from litellm.utils import any_assistant_message_has_thinking_blocks- messages = [- {"role": "user", "content": "Hello"},- {- "role": "assistant",- "tool_calls": [{"id": "123", "function": {"name": "test"}}],- },- {"role": "tool", "tool_call_id": "123", "content": "result"},- ]+ def test_get_prompt_cache_min_tokens_uniform_for_fable_5_across_platforms(local_model_cost_map: None) -> None:+ """Anthropic removed the Amazon Bedrock override for Claude Fable 5, so its 512-token minimum+ now applies on every platform. The Bedrock entries carried the old 1024 and the re-export+ entries carried nothing, so the router judged 512-1023-token prefixes uncacheable and skipped+ prompt-cache-affinity routing for prompts the provider demonstrably caches (issue #35011)."""+ wrong: Final = {+ model: get_prompt_cache_min_tokens(model=model)+ for model, info in litellm.model_cost.items()+ if "fable-5" in model+ and info.get("supports_prompt_caching")+ and get_prompt_cache_min_tokens(model=model) != 512+ }+ assert not wrong, f"every Claude Fable 5 entry must carry prompt_cache_min_tokens 512: {wrong}"+++ ANTHROPIC_REEXPORT_CACHE_MIN: Final = {+ "azure_ai/claude-fable-5": 512,+ "azure_ai/claude-haiku-4-5": 4096,+ "azure_ai/claude-opus-4-1": 1024,+ "azure_ai/claude-opus-4-5": 4096,+ "azure_ai/claude-opus-4-6": 4096,+ "azure_ai/claude-opus-4-7": 2048,+ "azure_ai/claude-opus-4-8": 1024,+ "azure_ai/claude-sonnet-4-5": 1024,+ "azure_ai/claude-sonnet-4-6": 1024,+ "azure_ai/claude-sonnet-5": 1024,+ "databricks/databricks-claude-haiku-4-5": 4096,+ "databricks/databricks-claude-opus-4": 1024,+ "databricks/databricks-claude-opus-4-1": 1024,+ "databricks/databricks-claude-opus-4-5": 4096,+ "databricks/databricks-claude-opus-4-6": 4096,+ "databricks/databricks-claude-sonnet-4": 1024,+ "databricks/databricks-claude-sonnet-4-5": 1024,+ "databricks/databricks-claude-sonnet-4-6": 1024,+ "openrouter/anthropic/claude-haiku-4.5": 4096,+ "openrouter/anthropic/claude-opus-4": 1024,+ "openrouter/anthropic/claude-opus-4.1": 1024,+ "openrouter/anthropic/claude-opus-4.5": 4096,+ "openrouter/anthropic/claude-opus-4.6": 4096,+ "openrouter/anthropic/claude-opus-4.7": 2048,+ "openrouter/anthropic/claude-sonnet-4": 1024,+ "openrouter/anthropic/claude-sonnet-4.5": 1024,+ "openrouter/anthropic/claude-sonnet-4.6": 1024,+ "replicate/anthropic/claude-4-sonnet": 1024,+ "replicate/anthropic/claude-4.5-haiku": 4096,+ "replicate/anthropic/claude-4.5-sonnet": 1024,+ "snowflake/claude-4-opus": 1024,+ "snowflake/claude-4-sonnet": 1024,+ "snowflake/claude-haiku-4-5": 4096,+ "snowflake/claude-sonnet-4-5": 1024,+ "snowflake/claude-sonnet-4-6": 1024,+ "vercel_ai_gateway/anthropic/claude-haiku-4.5": 4096,+ "vercel_ai_gateway/anthropic/claude-opus-4": 1024,+ "vercel_ai_gateway/anthropic/claude-opus-4.1": 1024,+ "vercel_ai_gateway/anthropic/claude-opus-4.5": 4096,+ "vercel_ai_gateway/anthropic/claude-opus-4.6": 4096,+ "vercel_ai_gateway/anthropic/claude-sonnet-4": 1024,+ "vercel_ai_gateway/anthropic/claude-sonnet-4.5": 1024,+ "vertex_ai/claude-fable-5": 512,+ "vertex_ai/claude-fable-5@default": 512,+ }- assert any_assistant_message_has_thinking_blocks(messages) is False+ def test_anthropic_reexport_entries_carry_explicit_prompt_cache_min_tokens(local_model_cost_map: None) -> None:+ """Regression for issue #35011: these re-export entries carried no prompt_cache_min_tokens, so+ they silently inherited the 1024 default. That skipped cache-affinity routing for Fable 5's+ 512-1023-token prefixes and reported 1024-4095-token prompts as cacheable on the 2048/4096+ models. The entry must be explicit so a default change can never re-break them, which is why+ this asserts the cost-map value itself and not just the resolver's answer."""+ wrong: Final = {+ model: (litellm.model_cost[model].get("prompt_cache_min_tokens"), get_prompt_cache_min_tokens(model=model))+ for model, expected in ANTHROPIC_REEXPORT_CACHE_MIN.items()+ if litellm.model_cost[model].get("prompt_cache_min_tokens") != expected+ or get_prompt_cache_min_tokens(model=model) != expected+ }+ assert not wrong, f"(cost-map value, resolved value) diverge from Anthropic's published minimums: {wrong}"+++ def test_anthropic_reexport_cache_minimums_present_in_root_cost_map() -> None:+ """The root map ships to the CDN independently of the bundled backup, so both must carry the+ minimum or proxies reading one of them regress to the 1024 default."""+ root_map_path: Final = os.path.join(os.path.dirname(__file__), "..", "..", "model_prices_and_context_window.json")+ with open(root_map_path) as f:+ root_map: Final = json.load(f)+ wrong: Final = {+ model: root_map[model].get("prompt_cache_min_tokens")+ for model, expected in ANTHROPIC_REEXPORT_CACHE_MIN.items()+ if root_map[model].get("prompt_cache_min_tokens") != expected+ }+ fable_5_wrong: Final = {+ model: info.get("prompt_cache_min_tokens")+ for model, info in root_map.items()+ if "fable-5" in model and info.get("supports_prompt_caching") and info.get("prompt_cache_min_tokens") != 512+ }+ assert not wrong and not fable_5_wrong, f"root cost map diverges: {wrong | fable_5_wrong}"+++ GEMINI_4096_CACHE_MIN_MODELS: Final = tuple(+ prefix + base+ for base in (+ "gemini-3.5-flash",+ "gemini-3.6-flash",+ "gemini-3.7-flash",+ "gemini-3.8-flash",+ "gemini-3.1-pro-preview",+ "gemini-3.1-pro-preview-customtools",+ )+ for prefix in ("", "gemini/", "vertex_ai/")+ )- def test_any_assistant_message_has_thinking_blocks_empty_list():- """Test that function returns False when thinking_blocks is an empty list."""- from litellm.utils import any_assistant_message_has_thinking_blocks- messages = [- {"role": "user", "content": "Hello"},- {- "role": "assistant",- "thinking_blocks": [], # Empty list- "tool_calls": [{"id": "123", "function": {"name": "test"}}],- },- ]+ def test_gemini_3_flash_and_31_pro_preview_resolve_4096_cache_minimum(local_model_cost_map: None) -> None:+ """Regression for the cost map missing prompt_cache_min_tokens on these models: Google rejects+ explicit caching below 4,096 tokens for them (https://ai.google.dev/gemini-api/docs/caching), so+ the 1024 default sent cachedContents creates Vertex answered with a hard 400."""+ wrong: Final = {+ model: get_prompt_cache_min_tokens(model=model)+ for model in GEMINI_4096_CACHE_MIN_MODELS+ if get_prompt_cache_min_tokens(model=model) != 4096+ }+ assert not wrong, f"prompt_cache_min_tokens must be 4096: {wrong}"+++ def test_gemini_4096_cache_minimum_present_in_root_cost_map() -> None:+ """The root map ships to the CDN independently of the bundled backup, so both must carry the+ minimum or proxies reading one of them regress to the 1024 default."""+ root_map_path: Final = os.path.join(os.path.dirname(__file__), "..", "..", "model_prices_and_context_window.json")+ with open(root_map_path) as f:+ root_map: Final = json.load(f)+ wrong: Final = {+ model: root_map[model].get("prompt_cache_min_tokens")+ for model in GEMINI_4096_CACHE_MIN_MODELS+ if root_map[model].get("prompt_cache_min_tokens") != 4096+ }+ assert not wrong, f"prompt_cache_min_tokens must be 4096: {wrong}"- assert any_assistant_message_has_thinking_blocks(messages) is False+ def test_get_prompt_cache_min_tokens_unmapped_model_falls_back_to_default(local_model_cost_map: None) -> None:+ """get_model_info raises for a model it has no entry for. The resolver must swallow that and+ fall back to the default, otherwise the raise reaches callers that would read it as+ "not cacheable" -- turning an unknown model into a silently uncacheable one."""+ assert get_prompt_cache_min_tokens(model="totally-unknown-model-xyz") == 1024- def test_last_assistant_with_tool_calls_has_no_thinking_blocks_issue_18926():- """- Test the scenario from issue #18926 where:- - First assistant message HAS thinking_blocks- - Second assistant message has NO thinking_blocks- The old logic would drop thinking because the LAST tool_call message- has no thinking_blocks, but this breaks because the first message- still has thinking blocks in the conversation.- """- from litellm.utils import (- any_assistant_message_has_thinking_blocks,- last_assistant_with_tool_calls_has_no_thinking_blocks,+ def test_is_prompt_caching_valid_prompt_uses_per_model_minimum(local_model_cost_map: None) -> None:+ """Regression: a prompt between two models' minimums is cacheable on one and not the other.+ A 1403-token prompt clears claude-opus-4-8's 1024 minimum but not claude-opus-4-6's 4096, so+ the flat-1024 check reported claude-opus-4-6 as cacheable and the cache write was rejected+ upstream. Both assertions must live together: is_prompt_caching_valid_prompt returns False on+ any internal error, so the True case is what proves the False case isn't a swallowed exception."""+ token_count = litellm.token_counter(+ model="claude-opus-4-6", messages=PROMPT_CACHE_MESSAGES, use_default_image_token_count=True+ )+ assert 1024 <= token_count < 4096, (+ f"prompt drifted to {token_count} tokens; it must sit between claude-opus-4-8's 1024 minimum "+ "and claude-opus-4-6's 4096 minimum for this test to distinguish them")- messages = [- {"role": "user", "content": "Build a feature"},- {- "role": "assistant",- "thinking_blocks": [- {"type": "thinking", "thinking": "Let me analyze the requirements..."}- ],- "tool_calls": [- {- "id": "toolu_1",- "function": {"name": "file_editor", "arguments": "{}"},- }- ],- },- {- "role": "tool",- "tool_call_id": "toolu_1",- "content": "File contents here...",- },- {- "role": "assistant",- # NO thinking_blocks - Claude sometimes doesn't include them- "content": [{"type": "text", "text": "Let me explore more..."}],- "tool_calls": [- {- "id": "toolu_2",- "function": {"name": "file_editor", "arguments": "{}"},- }- ],- },- ]+ assert is_prompt_caching_valid_prompt(model="claude-opus-4-6", messages=PROMPT_CACHE_MESSAGES) is False+ assert is_prompt_caching_valid_prompt(model="claude-opus-4-8", messages=PROMPT_CACHE_MESSAGES) is True+++ def test_is_prompt_caching_valid_prompt_explicit_min_token_count_overrides_model(local_model_cost_map: None) -> None:+ """An explicit min_token_count wins over the model-resolved value in both directions. Callers+ holding only a model-group alias resolve the threshold themselves and pass it, because an alias+ resolves to nothing here and would silently fall back to the default."""+ assert (+ is_prompt_caching_valid_prompt(model="claude-opus-4-6", messages=PROMPT_CACHE_MESSAGES, min_token_count=512)+ is True+ )+ assert (+ is_prompt_caching_valid_prompt(model="claude-opus-4-8", messages=PROMPT_CACHE_MESSAGES, min_token_count=8192)+ is False+ )- # Last assistant with tool_calls has no thinking_blocks- assert last_assistant_with_tool_calls_has_no_thinking_blocks(messages) is True- # But ANY assistant message has thinking_blocks- assert any_assistant_message_has_thinking_blocks(messages) is True+ def test_custom_logger_guards_ignore_subclass_instances(monkeypatch: pytest.MonkeyPatch) -> None:+ """Regression LIT-4392: the success/failure existence guards used isinstance, so a user+ subclass of a built-in logger already promoted into the callback lists made the guard+ report the built-in itself as registered and the configured logger was silently skipped.+ The exact-class assertions must hold alongside the subclass assertions: the guards still+ have to dedup a second instance of the same class, only a subclass must stop matching."""+ from litellm.integrations.custom_logger import CustomLogger+ from litellm.utils import (+ _custom_logger_class_exists_in_failure_callbacks,+ _custom_logger_class_exists_in_success_callbacks,+ )- # So we should NOT drop thinking - the combination tells us thinking is in use- # The fix uses both checks: only drop if last has none AND no message has any- should_drop_thinking = last_assistant_with_tool_calls_has_no_thinking_blocks(- messages- ) and not any_assistant_message_has_thinking_blocks(messages)- assert should_drop_thinking is False+ class BuiltinLogger(CustomLogger):+ pass+ class UserSubclassLogger(BuiltinLogger):+ pass- class TestAdditionalDropParamsForNonOpenAIProviders:- """- Test additional_drop_params functionality for non-OpenAI providers.+ builtin_instance = BuiltinLogger()- Fixes https://github.com/BerriAI/litellm/issues/19225+ monkeypatch.setattr(litellm, "success_callback", [UserSubclassLogger()])+ monkeypatch.setattr(litellm, "failure_callback", [UserSubclassLogger()])+ monkeypatch.setattr(litellm, "_async_success_callback", [])+ monkeypatch.setattr(litellm, "_async_failure_callback", [])+ assert _custom_logger_class_exists_in_success_callbacks(builtin_instance) is False+ assert _custom_logger_class_exists_in_failure_callbacks(builtin_instance) is False- The bug was that additional_drop_params only filtered params for OpenAI/Azure- providers, but not for other providers like Bedrock. This caused OpenAI-specific- params like prompt_cache_key to be passed to Bedrock, resulting in errors.- """+ monkeypatch.setattr(litellm, "success_callback", [BuiltinLogger()])+ monkeypatch.setattr(litellm, "failure_callback", [BuiltinLogger()])+ assert _custom_logger_class_exists_in_success_callbacks(builtin_instance) is True+ assert _custom_logger_class_exists_in_failure_callbacks(builtin_instance) is True- def test_additional_drop_params_filters_for_bedrock(self):- """- Test that additional_drop_params correctly filters params for Bedrock provider.- Before the fix, prompt_cache_key would be passed through to Bedrock even when- specified in additional_drop_params, causing:- 'BedrockException - {"message":"The model returned the following errors:- prompt_cache_key: Extra inputs are not permitted"}'- """- from litellm.utils import add_provider_specific_params_to_optional_params+ @pytest.mark.asyncio+ async def test_s3_v2_success_callback_registers_alongside_user_subclass(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression LIT-4392: with a user S3Logger subclass registered via litellm_settings.callbacks+ and success_callback ["s3_v2"], the built-in s3_v2 logger was never added and S3 logs were+ silently dropped while requests kept returning 200."""+ from litellm.integrations.s3_v2 import S3Logger+ from litellm.utils import _add_custom_logger_callback_to_specific_event++ class UserS3Logger(S3Logger):+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ pass- optional_params = {}- passed_params = {- "prompt_cache_key": "test_key_123",- "temperature": 0.7,- "model": "bedrock/anthropic.claude-v2",- }- openai_params = ["temperature", "max_tokens", "top_p", "model"]+ user_logger = UserS3Logger()+ monkeypatch.setattr(litellm, "success_callback", [user_logger, "s3_v2"])+ monkeypatch.setattr(litellm, "_async_success_callback", [user_logger])+ monkeypatch.setattr(litellm, "failure_callback", [])+ monkeypatch.setattr(litellm, "_async_failure_callback", [])- result = add_provider_specific_params_to_optional_params(- optional_params=optional_params,- passed_params=passed_params,- custom_llm_provider="bedrock",- openai_params=openai_params,- additional_drop_params=["prompt_cache_key"],- )+ _add_custom_logger_callback_to_specific_event("s3_v2", "success")- # prompt_cache_key should be filtered out- assert "prompt_cache_key" not in result- # temperature should still be there (it's in openai_params, not filtered)- # Note: temperature is in openai_params so it won't be added by this function- # The function only adds params NOT in openai_params+ assert any(type(cb) is S3Logger for cb in litellm.success_callback)+ assert any(type(cb) is S3Logger for cb in litellm._async_success_callback)+ assert "s3_v2" not in litellm.success_callback+ assert user_logger in litellm.success_callback- def test_additional_drop_params_filters_multiple_params_for_non_openai(self):- """Test filtering multiple params for non-OpenAI providers."""- from litellm.utils import add_provider_specific_params_to_optional_params- optional_params = {}- passed_params = {- "prompt_cache_key": "test_key",- "some_openai_only_param": "value1",- "another_openai_param": "value2",- "keep_this_param": "keep_me",- }- openai_params = ["temperature", "max_tokens"]+ @pytest.mark.asyncio+ async def test_builtin_string_callback_registers_when_subclass_already_active(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression LIT-4392, litellm.callbacks path: the inline dedup in function_setup also+ matched subclass instances, so a built-in name in litellm.callbacks was dropped whenever a+ user subclass was already promoted into _async_success_callback."""+ from litellm.integrations.s3_v2 import S3Logger- result = add_provider_specific_params_to_optional_params(- optional_params=optional_params,- passed_params=passed_params,- custom_llm_provider="anthropic",- openai_params=openai_params,- additional_drop_params=["prompt_cache_key", "some_openai_only_param"],- )+ class UserS3Logger(S3Logger):+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ pass- # Filtered params should not be present- assert "prompt_cache_key" not in result- assert "some_openai_only_param" not in result- # Non-filtered params should be present- assert result.get("another_openai_param") == "value2"- assert result.get("keep_this_param") == "keep_me"+ user_logger = UserS3Logger()+ monkeypatch.setattr(litellm, "callbacks", ["s3_v2"])+ monkeypatch.setattr(litellm, "input_callback", [])+ monkeypatch.setattr(litellm, "success_callback", [user_logger])+ monkeypatch.setattr(litellm, "failure_callback", [])+ monkeypatch.setattr(litellm, "_async_success_callback", [user_logger])+ monkeypatch.setattr(litellm, "_async_failure_callback", [])++ await litellm.acompletion(+ model="gpt-5.6",+ messages=[{"role": "user", "content": "hi"}],+ mock_response="ok",+ )- def test_additional_drop_params_none_keeps_all_params(self):- """Test that when additional_drop_params is None, all params are kept."""- from litellm.utils import add_provider_specific_params_to_optional_params+ assert any(type(cb) is S3Logger for cb in litellm._async_success_callback)- optional_params = {}- passed_params = {- "prompt_cache_key": "test_key",- "custom_param": "value",- }- openai_params = ["temperature"]- result = add_provider_specific_params_to_optional_params(- optional_params=optional_params,- passed_params=passed_params,- custom_llm_provider="bedrock",- openai_params=openai_params,- additional_drop_params=None,- )+ def test_reapply_runtime_registrations_replays_register_model_overrides(monkeypatch):+ """+ register_model is the documented way to override pricing for a model. A+ price-data reload swaps litellm.model_cost for a freshly fetched catalog,+ so without replaying those registrations the override is silently lost and+ the model reverts to upstream pricing.+ """+ from litellm import utils as litellm_utils+ from litellm.utils import (+ _invalidate_model_cost_lowercase_map,+ reapply_runtime_model_cost_registrations,+ )- # All params should be present when additional_drop_params is None- assert result.get("prompt_cache_key") == "test_key"- assert result.get("custom_param") == "value"+ monkeypatch.setattr(+ litellm_utils,+ "_runtime_registered_model_cost",+ dict(litellm_utils._runtime_registered_model_cost),+ )+ # Only the recorded half is under test here; the live-router rebuild is covered+ # in test_router_model_cost_isolation.py. Routers built by earlier tests in this+ # process stay in the weak set until they are collected, so leaving the callback+ # installed would make this depend on when that happens.+ monkeypatch.setattr(litellm_utils._LiveDeploymentReplay, "callback", None)- def test_additional_drop_params_empty_list_keeps_all_params(self):- """Test that when additional_drop_params is empty list, all params are kept."""- from litellm.utils import add_provider_specific_params_to_optional_params+ saved_model_cost = litellm.model_cost+ try:+ litellm.register_model(+ model_cost={+ "openai/gpt-4o": {+ "litellm_provider": "openai",+ "mode": "chat",+ "input_cost_per_token": 0.000123,+ }+ }+ )- optional_params = {}- passed_params = {- "prompt_cache_key": "test_key",- "custom_param": "value",+ litellm.model_cost = {+ "openai/gpt-4o": {+ "litellm_provider": "openai",+ "mode": "chat",+ "input_cost_per_token": 0.000999,+ "max_input_tokens": 4242,+ }}- openai_params = ["temperature"]-- result = add_provider_specific_params_to_optional_params(- optional_params=optional_params,- passed_params=passed_params,- custom_llm_provider="bedrock",- openai_params=openai_params,- additional_drop_params=[],- )+ _invalidate_model_cost_lowercase_map()+ reapply_runtime_model_cost_registrations()- # All params should be present when additional_drop_params is empty- assert result.get("prompt_cache_key") == "test_key"- assert result.get("custom_param") == "value"+ assert litellm.model_cost["openai/gpt-4o"]["input_cost_per_token"] == 0.000123+ assert litellm.model_cost["openai/gpt-4o"]["max_input_tokens"] == 4242+ finally:+ litellm.model_cost = saved_model_cost+ _invalidate_model_cost_lowercase_map()- class TestDropParamsWithPromptCacheKey:+ def test_reapply_runtime_registrations_drops_request_scoped_registrations(monkeypatch):"""- Test that drop_params: true correctly drops prompt_cache_key for non-OpenAI providers.+ Per-request custom pricing describes one call, so it must not be re-asserted+ over every future catalog. Replaying it would let a one-off price outlive+ the catalog generation it was applied to and silently beat fresh upstream+ pricing forever, while a durable override registered alongside it survives.+ """+ from litellm import utils as litellm_utils+ from litellm.utils import (+ _invalidate_model_cost_lowercase_map,+ reapply_runtime_model_cost_registrations,+ )- Fixes https://github.com/BerriAI/litellm/issues/19225+ monkeypatch.setattr(+ litellm_utils,+ "_runtime_registered_model_cost",+ dict(litellm_utils._runtime_registered_model_cost),+ )- prompt_cache_key is an OpenAI-specific parameter that should be automatically- dropped when using providers like Bedrock that don't support it.- """+ saved_model_cost = litellm.model_cost+ try:+ litellm.register_model(+ model_cost={"openai/gpt-4o": {"litellm_provider": "openai", "input_cost_per_token": 0.000111}},+ persist_across_reloads=True,+ )+ litellm.register_model(+ model_cost={"openai/gpt-4o-mini": {"litellm_provider": "openai", "input_cost_per_token": 0.000222}},+ persist_across_reloads=False,+ )- def test_prompt_cache_key_in_default_params(self):- """Verify prompt_cache_key is now in DEFAULT_CHAT_COMPLETION_PARAM_VALUES."""- from litellm.constants import DEFAULT_CHAT_COMPLETION_PARAM_VALUES+ litellm.model_cost = {+ "openai/gpt-4o": {"litellm_provider": "openai", "input_cost_per_token": 0.000999},+ "openai/gpt-4o-mini": {"litellm_provider": "openai", "input_cost_per_token": 0.000888},+ }+ _invalidate_model_cost_lowercase_map()+ reapply_runtime_model_cost_registrations()- assert "prompt_cache_key" in DEFAULT_CHAT_COMPLETION_PARAM_VALUES- assert "prompt_cache_retention" in DEFAULT_CHAT_COMPLETION_PARAM_VALUES+ assert litellm.model_cost["openai/gpt-4o"]["input_cost_per_token"] == 0.000111+ assert litellm.model_cost["openai/gpt-4o-mini"]["input_cost_per_token"] == 0.000888+ finally:+ litellm.model_cost = saved_model_cost+ _invalidate_model_cost_lowercase_map()- def test_drop_params_removes_prompt_cache_key_for_bedrock(self):- """- Test that get_optional_params with drop_params=True removes prompt_cache_key- for Bedrock provider since it's not in Bedrock's supported params.- """- from litellm.utils import get_optional_params- # Call get_optional_params for Bedrock with prompt_cache_key- # drop_params=True should remove it since Bedrock doesn't support it- result = get_optional_params(- model="anthropic.claude-3-sonnet-20240229-v1:0",- custom_llm_provider="bedrock",- prompt_cache_key="test_cache_key",- temperature=0.7,- drop_params=True,- )+ class _JsonCapture(logging.Handler):+ def __init__(self):+ super().__init__()+ self.formatter = JsonFormatter()+ self.records: list[dict] = []+ self.addFilter(CorrelationContextFilter())- # prompt_cache_key should be dropped for Bedrock- assert "prompt_cache_key" not in result- # temperature should remain (it's supported by Bedrock)- assert result.get("temperature") == 0.7+ def emit(self, record):+ self.records.append(json.loads(self.formatter.format(record)))- class TestGetOptionalParamsDeepSeek:- """Tests that deepseek provider uses DeepSeekChatConfig for parameter mapping."""+ def _make_capture_logger(name: str) -> tuple[logging.Logger, _JsonCapture]:+ lg = logging.getLogger(name)+ cap = _JsonCapture()+ lg.addHandler(cap)+ lg.setLevel(logging.DEBUG)+ return lg, cap- def test_deepseek_supports_thinking_param(self):- """- Verify that get_optional_params for deepseek accepts the 'thinking' param,- which is only supported by DeepSeekChatConfig, not OpenAIConfig.- """- from litellm.utils import get_optional_params- result = get_optional_params(- model="deepseek-reasoner",- custom_llm_provider="deepseek",- thinking={"type": "enabled"},+ @pytest.mark.asyncio+ async def test_wrapper_async_restores_originating_task_context_after_success(monkeypatch):+ """A successful acompletion() dispatches async_success_handler via+ asyncio.create_task + the global logging worker - a different Task than the+ one running acompletion() itself (this test's own task). That handler's own+ restore only fixes up the detached child task it runs in; wrapper_async's own+ finally block (in litellm/utils.py) must separately restore the *originating*+ task's trace_id/session_id, since nothing else does.+ """+ monkeypatch.setattr(litellm, "request_correlation_in_logs", True)+ trace_id_var.set("outer-trace-wrapper-test")+ session_id_var.set("outer-session-wrapper-test")+ try:+ await litellm.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ mock_response="Hello there!",+ litellm_session_id="mock-call-session",+ num_retries=0,)- assert result.get("thinking") == {"type": "enabled"}+ assert trace_id_var.get() == "outer-trace-wrapper-test"+ assert session_id_var.get() == "outer-session-wrapper-test"+ finally:+ trace_id_var.set("")+ session_id_var.set("")- def test_deepseek_supports_reasoning_effort_param(self):- """- Verify that get_optional_params for deepseek accepts 'reasoning_effort',- which is only supported by DeepSeekChatConfig, not OpenAIConfig.- """- from litellm.utils import get_optional_params- result = get_optional_params(- model="deepseek-reasoner",- custom_llm_provider="deepseek",- reasoning_effort="high",- )- assert result.get("thinking") == {"type": "enabled"}+ def test_function_setup_failure_after_logging_construction_restores_context(monkeypatch):+ """If function_setup() constructs Logging() (which already mutated+ trace_id_var/session_id_var in __init__) but then raises before returning,+ the caller's wrapper() never gets a logging_obj reference to restore from.+ function_setup()'s own except block must restore the correlation context+ itself in that case, or it leaks into every subsequent log line in this+ thread/task until something unrelated happens to reset it."""+ from litellm.litellm_core_utils.litellm_logging import Logging- def test_deepseek_thinking_strips_budget_tokens(self):- """- DeepSeekChatConfig strips budget_tokens from thinking param.- This would not happen with OpenAIConfig.- """- from litellm.utils import get_optional_params+ monkeypatch.setattr(litellm, "request_correlation_in_logs", True)- result = get_optional_params(- model="deepseek-reasoner",- custom_llm_provider="deepseek",- thinking={"type": "enabled", "budget_tokens": 5000},- )- assert "budget_tokens" not in result.get("thinking", {})- assert result.get("thinking") == {"type": "enabled"}+ def _boom(self, *args, **kwargs):+ raise RuntimeError("simulated failure after Logging() construction")+ monkeypatch.setattr(Logging, "update_environment_variables", _boom)- class TestIsStreamingRequest:- def test_stream_true_in_kwargs(self):- assert (- _is_streaming_request(kwargs={"stream": True}, call_type="acompletion")- is True- )+ trace_id_var.set("pre-setup-failure-trace")+ session_id_var.set("pre-setup-failure-session")+ try:+ with pytest.raises(RuntimeError, match="simulated failure"):+ litellm.completion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ mock_response="Hello there!",+ litellm_session_id="doomed-call-session",+ num_retries=0,+ )+ assert trace_id_var.get() == "pre-setup-failure-trace"+ assert session_id_var.get() == "pre-setup-failure-session"+ finally:+ trace_id_var.set("")+ session_id_var.set("")- def test_stream_false_in_kwargs(self):- 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_function_setup_failure_log_line_shows_outer_not_doomed_ids(monkeypatch):+ """The 'Error in function_setup' diagnostic log line itself must be stamped+ with the outer/pre-call correlation ids, not the doomed call's own ids -+ restoring context must happen *before* logging the exception, not after,+ since the failed call never produces a usable logging object for anything+ else to be attributed to."""+ from litellm.litellm_core_utils.litellm_logging import Logging- def test_generate_content_stream_string(self):- assert (- _is_streaming_request(- kwargs={}, call_type=CallTypes.generate_content_stream.value+ monkeypatch.setattr(litellm, "request_correlation_in_logs", True)++ def _boom(self, *args, **kwargs):+ raise RuntimeError("simulated failure after Logging() construction")++ monkeypatch.setattr(Logging, "update_environment_variables", _boom)++ lg, cap = _make_capture_logger("test.function_setup_failure_log_order")+ # verbose_logger is a distinct, module-level logger from our throwaway one -+ # temporarily attach the same capture handler so we see its own emitted record.+ verbose_logger.addHandler(cap)+ try:+ trace_id_var.set("outer-trace")+ session_id_var.set("outer-session")+ with pytest.raises(RuntimeError, match="simulated failure"):+ litellm.completion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ mock_response="Hello there!",+ litellm_session_id="doomed-call-session",+ num_retries=0,)- is True- )+ setup_failure_records = [r for r in cap.records if "Error in function_setup" in r.get("message", "")]+ assert len(setup_failure_records) == 1+ record = setup_failure_records[0]+ assert record.get("session_id") == "outer-session"+ assert record.get("trace_id") == "outer-trace"+ finally:+ verbose_logger.removeHandler(cap)+ trace_id_var.set("")+ session_id_var.set("")+++ WEBSEARCH_INTERNAL_CONTROL_FIELDS = (+ "_websearch_interception_emit_native_blocks",+ "_websearch_interception_converted_stream",+ )+++ def test_websearch_interception_control_fields_never_reach_the_provider():+ """The web-search interception hooks stamp these onto kwargs to carry state+ across the agentic loop. Anything the param builder does not recognize is+ swept into the provider request, and a provider that validates its body+ rejects the whole call: Bedrock Converse answers+ `_websearch_interception_emit_native_blocks: Extra inputs are not permitted`+ with a 400, so enabling interception breaks every request it touches.++ Their code-interpreter counterparts are already registered; these were not.+ """+ kwargs = {+ "a_real_provider_specific_param": 1,+ **{field: True for field in WEBSEARCH_INTERNAL_CONTROL_FIELDS},+ }- def test_agenerate_content_stream_string(self):- assert (- _is_streaming_request(- kwargs={}, call_type=CallTypes.agenerate_content_stream.value- )- is True- )+ non_default = get_non_default_completion_params(kwargs)- def test_generate_content_stream_enum(self):- assert (- _is_streaming_request(- kwargs={}, call_type=CallTypes.generate_content_stream- )- is True- )+ assert non_default == {"a_real_provider_specific_param": 1}, (+ "web-search interception control fields leaked into the provider params: "+ f"{sorted(set(non_default) - {'a_real_provider_specific_param'})}"+ )+ assert set(WEBSEARCH_INTERNAL_CONTROL_FIELDS) <= set(all_litellm_params)- def test_agenerate_content_stream_enum(self):- assert (- _is_streaming_request(- kwargs={}, call_type=CallTypes.agenerate_content_stream- )- is True- )- def test_non_streaming_call_type_string(self):- assert _is_streaming_request(kwargs={}, call_type="acompletion") is False+ def test_bedrock_batch_params_never_reach_the_provider():+ """A Bedrock managed-batch deployment carries aws_batch_role_arn / s3_* /+ bedrock_tags in its litellm_params, and the same deployment also serves chat.+ Anything the param builder does not recognize is swept into extra_body, so+ Bedrock rejects the whole call: `aws_batch_role_arn: Extra inputs are not+ permitted` (Anthropic models) or `extraneous key [aws_batch_role_arn] is not+ permitted` (Nova/Llama/Titan), turning every non-batch request to that+ deployment into a 400.- def test_non_streaming_call_type_enum(self):- assert (- _is_streaming_request(kwargs={}, call_type=CallTypes.acompletion) is False- )+ The batch path is unaffected by registering them, because GenericLiteLLMParams+ is extra="allow" and preserves them into litellm_params for the batch and files+ transformations that read them.+ """+ configured = {+ field: ([{"key": "team", "value": "configured-value"}] if field == "bedrock_tags" else "configured-value")+ for field in bedrock_batch_litellm_params+ }+ kwargs = {"a_real_provider_specific_param": 1, **configured}- def test_stream_true_overrides_non_streaming_call_type(self):- assert (- _is_streaming_request(- kwargs={"stream": True}, call_type=CallTypes.acompletion- )- is True- )+ non_default = get_non_default_completion_params(dict(kwargs))+ assert non_default == {"a_real_provider_specific_param": 1}, (+ "bedrock batch params leaked into the provider params: "+ f"{sorted(set(non_default) - {'a_real_provider_specific_param'})}"+ )+ assert set(bedrock_batch_litellm_params) <= set(all_litellm_params)- class TestCallbackAsyncSyncSeparation:- """Test that LoggingCallbackManager auto-routes async callbacks to async lists."""+ batch_params = dict(GenericLiteLLMParams(**kwargs))+ assert all(batch_params.get(field) == configured[field] for field in bedrock_batch_litellm_params), (+ "registering these must not strip them from the batch path: "+ f"{sorted(f for f in bedrock_batch_litellm_params if batch_params.get(f) != configured[f])}"+ )- def setup_method(self):- """Reset callback lists before each test."""- litellm.input_callback = []- litellm.success_callback = []- litellm.failure_callback = []- litellm._async_input_callback = []- litellm._async_success_callback = []- litellm._async_failure_callback = []+ normalized = CredentialLiteLLMParams.model_validate(+ GenericLiteLLMParams(**kwargs).model_dump(exclude_none=True)+ ).model_dump(exclude_none=True)+ assert all(normalized.get(field) == configured[field] for field in bedrock_batch_litellm_params), (+ "credential normalization dropped batch params before the transformation: "+ f"{sorted(f for f in bedrock_batch_litellm_params if normalized.get(f) != configured[f])}"+ )- def test_async_success_callback_routed_to_async_list(self):- async def my_async_cb(*args, **kwargs):- pass- litellm.logging_callback_manager.add_litellm_success_callback(my_async_cb)- assert my_async_cb in litellm._async_success_callback- assert my_async_cb not in litellm.success_callback+ def test_client_side_timeout_marker_never_reaches_the_provider():+ """The proxy stamps kwargs["client_side_timeout"] = True whenever a request carries+ a caller-supplied timeout (body timeout / request_timeout / stream_timeout or the+ x-litellm-timeout headers) so the router can skip cooldowns on the resulting 408s.+ The marker is only meaningful to the router, so it must be filtered out of the+ provider params: swept into extra_body / additionalModelRequestFields it turns every+ timed-out request into a provider 400 (`client_side_timeout: Extra inputs are not+ permitted`)."""+ kwargs = {"a_real_provider_specific_param": 1, "client_side_timeout": True}- def test_sync_success_callback_stays_in_sync_list(self):- def my_sync_cb(*args, **kwargs):- pass+ non_default = get_non_default_completion_params(kwargs)- litellm.logging_callback_manager.add_litellm_success_callback(my_sync_cb)- assert my_sync_cb in litellm.success_callback- assert my_sync_cb not in litellm._async_success_callback+ assert non_default == {"a_real_provider_specific_param": 1}, (+ "client_side_timeout leaked into the provider params: "+ f"{sorted(set(non_default) - {'a_real_provider_specific_param'})}"+ )- def test_string_callback_stays_in_sync_list(self):- litellm.logging_callback_manager.add_litellm_success_callback("langfuse")- assert "langfuse" in litellm.success_callback- assert "langfuse" not in litellm._async_success_callback- def test_async_failure_callback_routed_to_async_list(self):- async def my_async_cb(*args, **kwargs):- pass+ class _RecordingDeploymentFailureLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.calls: list[tuple[dict, Exception, CallTypes | None, int | None]] = []- litellm.logging_callback_manager.add_litellm_failure_callback(my_async_cb)- assert my_async_cb in litellm._async_failure_callback- assert my_async_cb not in litellm.failure_callback+ async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type, fallback_depth=None):+ self.calls.append((request_data, exception, call_type, fallback_depth))- def test_sync_failure_callback_stays_in_sync_list(self):- def my_sync_cb(*args, **kwargs):- pass- litellm.logging_callback_manager.add_litellm_failure_callback(my_sync_cb)- assert my_sync_cb in litellm.failure_callback- assert my_sync_cb not in litellm._async_failure_callback+ @pytest.mark.asyncio+ async def test_async_post_call_failure_deployment_hook_calls_custom_logger_callbacks(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """The dispatcher must call the CustomLogger hook with an equivalent exception (not+ necessarily the same object - see test_..._snapshots_exception_so_callback_mutations_..._+ below) and the call_type resolved to its CallTypes enum member."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])++ exc = ValueError("deployment failed")+ await async_post_call_failure_deployment_hook(+ request_data={"model": "gpt-4o-mini"}, exception=exc, call_type="acompletion"+ )- def test_dynamodb_routed_to_async_success(self):- litellm.logging_callback_manager.add_litellm_success_callback("dynamodb")- assert "dynamodb" in litellm._async_success_callback- assert "dynamodb" not in litellm.success_callback+ assert len(recorder.calls) == 1+ request_data, received_exc, call_type, fallback_depth = recorder.calls[0]+ assert request_data == {"model": "gpt-4o-mini"}+ assert isinstance(received_exc, ValueError)+ assert str(received_exc) == str(exc)+ assert call_type == CallTypes.acompletion+ assert fallback_depth is None- def test_openmeter_routed_to_async_success(self):- litellm.logging_callback_manager.add_litellm_success_callback("openmeter")- assert "openmeter" in litellm._async_success_callback- assert "openmeter" not in litellm.success_callback- def test_async_input_callback_routed_to_async_list(self):- async def my_async_cb(*args, **kwargs):- pass+ @pytest.mark.asyncio+ async def test_async_post_call_failure_deployment_hook_falls_back_to_none_call_type(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """An unrecognized call_type string must resolve to None rather than raising."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])- litellm.logging_callback_manager.add_litellm_input_callback(my_async_cb)- assert my_async_cb in litellm._async_input_callback- assert my_async_cb not in litellm.input_callback+ await async_post_call_failure_deployment_hook(+ request_data={}, exception=ValueError("x"), call_type="not_a_real_call_type"+ )- def test_sync_input_callback_stays_in_sync_list(self):- def my_sync_cb(*args, **kwargs):- pass+ assert recorder.calls[0][2] is None- litellm.logging_callback_manager.add_litellm_input_callback(my_sync_cb)- assert my_sync_cb in litellm.input_callback- assert my_sync_cb not in litellm._async_input_callback+ @pytest.mark.asyncio+ async def test_async_post_call_failure_deployment_hook_passes_through_fallback_depth(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """fallback_depth on request_data (set by Router on each fallback hop) must reach the+ callback unchanged, so a subscriber can tell which fallback hop this failure is from."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])- class TestMetadataNoneHandling:- """- Test that metadata=None in kwargs doesn't cause TypeError.+ await async_post_call_failure_deployment_hook(+ request_data={"fallback_depth": 2}, exception=ValueError("x"), call_type="acompletion"+ )- When metadata key exists with value None (e.g., from Azure OpenAI streaming),- dict.get("metadata", {}) returns None (key exists, so default is ignored).- The fix uses (kwargs.get("metadata") or {}) which handles both missing key- and explicit None value.+ assert recorder.calls[0][3] == 2- Related: #20871- """- def test_metadata_none_get_previous_models(self):- """kwargs.get("metadata") or {} should return {} when metadata is None."""- kwargs = {"metadata": None}- previous_models = (kwargs.get("metadata") or {}).get("previous_models", None)- assert previous_models is None+ @pytest.mark.asyncio+ async def test_async_post_call_failure_deployment_hook_fallback_depth_defaults_to_none(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """fallback_depth must be None, not raise or pass through garbage, when request_data has+ no fallback_depth at all (first attempt, or a bare SDK call with no Router) or a+ non-int value there."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])++ await async_post_call_failure_deployment_hook(request_data={}, exception=ValueError("x"), call_type="acompletion")+ await async_post_call_failure_deployment_hook(+ request_data={"fallback_depth": "not-an-int"}, exception=ValueError("y"), call_type="acompletion"+ )- def test_metadata_none_model_group_check(self):- """'model_group' in (kwargs.get("metadata") or {}) should not raise TypeError."""- kwargs = {"metadata": None}- _is_litellm_router_call = "model_group" in (kwargs.get("metadata") or {})- assert _is_litellm_router_call is False+ assert recorder.calls[0][3] is None+ assert recorder.calls[1][3] is None- def test_metadata_missing_key(self):- """Should work when metadata key is completely absent."""- kwargs = {}- previous_models = (kwargs.get("metadata") or {}).get("previous_models", None)- assert previous_models is None- def test_metadata_present_with_values(self):- """Should work when metadata has actual values."""- kwargs = {"metadata": {"previous_models": ["model1"], "model_group": "test"}}- previous_models = (kwargs.get("metadata") or {}).get("previous_models", None)- assert previous_models == ["model1"]- _is_litellm_router_call = "model_group" in (kwargs.get("metadata") or {})- assert _is_litellm_router_call is True+ @pytest.mark.asyncio+ async def test_async_post_call_failure_deployment_hook_swallows_callback_errors(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """A callback that raises inside the hook must not propagate out of the dispatcher."""- def test_metadata_none_causes_error_with_old_pattern(self):- """Demonstrate the bug: dict.get('metadata', {}) returns None when key exists with None value."""- kwargs = {"metadata": None}- # Old pattern: kwargs.get("metadata", {}) returns None because key exists- result = kwargs.get("metadata", {})- assert result is None # This is the root cause of the bug+ class ExplodingLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.called = False- # Attempting to use .get() on None raises AttributeError or TypeError- with pytest.raises((TypeError, AttributeError)):- kwargs.get("metadata", {}).get("previous_models", 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")- # Attempting 'in' on None raises TypeError- with pytest.raises(TypeError):- "model_group" in kwargs.get("metadata", {})+ exploding_logger = ExplodingLogger()+ monkeypatch.setattr(litellm, "callbacks", [exploding_logger])- def test_litellm_params_metadata_none(self):- """litellm_params.get("metadata") or {} should handle None value."""- litellm_params = {"metadata": None}- metadata = litellm_params.get("metadata") or {}- assert metadata == {}+ await async_post_call_failure_deployment_hook(request_data={}, exception=ValueError("x"), call_type="acompletion")+ assert exploding_logger.called- class TestValidateAndFixThinkingParam:- """Tests for validate_and_fix_thinking_param."""- def test_none_returns_none(self):- from litellm.utils import validate_and_fix_thinking_param+ @pytest.mark.asyncio+ async def test_async_post_call_failure_deployment_hook_skips_non_custom_logger_callbacks(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Callable (function-based) callbacks are not CustomLogger instances and must be skipped."""+ called: list[bool] = []- assert validate_and_fix_thinking_param(thinking=None) is None+ async def fn_callback(*args: object, **kwargs: object) -> None:+ called.append(True)- def test_already_snake_case(self):- from litellm.utils import validate_and_fix_thinking_param+ monkeypatch.setattr(litellm, "callbacks", [fn_callback])- thinking = {"type": "enabled", "budget_tokens": 32000}- result = validate_and_fix_thinking_param(thinking=thinking)- assert result == {"type": "enabled", "budget_tokens": 32000}+ await async_post_call_failure_deployment_hook(request_data={}, exception=ValueError("x"), call_type="acompletion")- def test_camel_case_normalized(self):- from litellm.utils import validate_and_fix_thinking_param+ assert called == []- thinking = {"type": "enabled", "budgetTokens": 32000}- result = validate_and_fix_thinking_param(thinking=thinking)- assert result == {"type": "enabled", "budget_tokens": 32000}- assert "budgetTokens" not in result- def test_both_keys_snake_case_wins(self):- from litellm.utils import validate_and_fix_thinking_param+ @pytest.mark.asyncio+ async def test_wrapper_async_fires_post_call_failure_deployment_hook_once_per_failed_attempt(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: a failed deployment call must reach async_post_call_failure_deployment_hook+ exactly once, sourced from wrapper_async's own except block rather than the dedup-gated+ async_log_failure_event path, which would miss retries/fallback chain attempts 2+."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])++ with pytest.raises(litellm.AuthenticationError):+ await 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"),+ )- thinking = {"type": "enabled", "budget_tokens": 10000, "budgetTokens": 50000}- result = validate_and_fix_thinking_param(thinking=thinking)- assert result == {"type": "enabled", "budget_tokens": 10000}- assert "budgetTokens" not in result+ assert len(recorder.calls) == 1+ _, received_exc, call_type, fallback_depth = recorder.calls[0]+ assert isinstance(received_exc, litellm.AuthenticationError)+ assert call_type == CallTypes.acompletion+ assert fallback_depth is None- def test_original_dict_not_mutated(self):- from litellm.utils import validate_and_fix_thinking_param- thinking = {"type": "enabled", "budgetTokens": 32000}- validate_and_fix_thinking_param(thinking=thinking)- assert "budgetTokens" in thinking- assert "budget_tokens" not in thinking+ @pytest.mark.asyncio+ async def test_wrapper_async_raises_original_exception_even_if_hook_callback_errors(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """A broken async_post_call_failure_deployment_hook override must never shadow the real+ 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):+ raise RuntimeError("hook exploded")- def test_deepseek_v4_models_in_cost_map():- """- Test that deepseek-v4-flash and deepseek-v4-pro entries are correctly- configured in model_prices_and_context_window.json.+ monkeypatch.setattr(litellm, "callbacks", [ExplodingLogger()])- Prices sourced from https://api-docs.deepseek.com/quick_start/pricing:- - deepseek-v4-flash: $0.14/M input, $0.28/M output- - deepseek-v4-pro: $0.435/M input, $0.87/M output (75% discounted active price)+ with pytest.raises(litellm.AuthenticationError, match="bad key"):+ await 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"),+ )- Closes https://github.com/BerriAI/litellm/issues/26709- """- 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)+ @pytest.mark.asyncio+ async def test_router_fallback_chain_reports_increasing_fallback_depth(monkeypatch: pytest.MonkeyPatch) -> None:+ """Regression: a real Router fallback chain must report fallback_depth=None on the+ first, pre-fallback attempt and fallback_depth=1 on the first fallback hop - the+ concrete scenario async_post_call_failure_deployment_hook exists to make visible."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])++ router = litellm.Router(+ model_list=[+ {"model_name": "bad-group", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "bad-a"}},+ {"model_name": "good-group", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "bad-b"}},+ ],+ num_retries=0,+ fallbacks=[{"bad-group": ["good-group"]}],+ )- # --- bare model names ---- for key, expected_input, expected_output, expected_cache in [- ("deepseek-v4-flash", 1.4e-07, 2.8e-07, 2.8e-09),- ("deepseek-v4-pro", 4.35e-07, 8.7e-07, 3.625e-09),- ]:- info = model_cost.get(key)- assert info is not None, f"{key} missing from model_prices_and_context_window.json"- assert info["litellm_provider"] == "deepseek"- assert info["mode"] == "chat"- assert info["input_cost_per_token"] == expected_input- assert info["output_cost_per_token"] == expected_output- assert info["cache_read_input_token_cost"] == expected_cache- assert info["max_input_tokens"] == 1_000_000- assert info["supports_function_calling"] is True- assert info["supports_tool_choice"] is True+ with pytest.raises(litellm.AuthenticationError):+ await router.acompletion(+ model="bad-group",+ messages=[{"role": "user", "content": "hi"}],+ mock_response=litellm.AuthenticationError(message="bad key", llm_provider="openai", model="gpt-4o-mini"),+ )- # --- provider-prefixed names ---- for key, expected_input, expected_output, expected_cache in [- ("deepseek/deepseek-v4-flash", 1.4e-07, 2.8e-07, 2.8e-09),- ("deepseek/deepseek-v4-pro", 4.35e-07, 8.7e-07, 3.625e-09),- ]:- info = model_cost.get(key)- assert info is not None, f"{key} missing from model_prices_and_context_window.json"- assert info["litellm_provider"] == "deepseek"- assert info["mode"] == "chat"- assert info["input_cost_per_token"] == expected_input- assert info["output_cost_per_token"] == expected_output- assert info["cache_read_input_token_cost"] == expected_cache- assert info["supports_function_calling"] is True- assert info["supports_tool_choice"] is True+ assert len(recorder.calls) == 2+ assert recorder.calls[0][3] is None+ assert recorder.calls[1][3] == 1- def test_deepseek_v4_models_in_backup_cost_map():- """- Test that deepseek-v4-flash and deepseek-v4-pro entries are correctly- configured in litellm/model_prices_and_context_window_backup.json.- """- import json- from pathlib import Path+ @pytest.mark.asyncio+ async def test_router_multi_hop_fallback_chain_reports_depth_per_hop(monkeypatch: pytest.MonkeyPatch) -> None:+ """Regression: fallback_depth must keep incrementing across more than one fallback+ hop (group-a -> group-b -> group-c, all failing), not just report 1 for every+ fallback attempt regardless of how deep the chain has gone."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])++ router = litellm.Router(+ model_list=[+ {"model_name": "group-a", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "bad-a"}},+ {"model_name": "group-b", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "bad-b"}},+ {"model_name": "group-c", "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "bad-c"}},+ ],+ num_retries=0,+ fallbacks=[{"group-a": ["group-b", "group-c"]}],+ )++ with pytest.raises(litellm.AuthenticationError):+ await router.acompletion(+ model="group-a",+ messages=[{"role": "user", "content": "hi"}],+ mock_response=litellm.AuthenticationError(message="bad key", llm_provider="openai", model="gpt-4o-mini"),+ )++ assert len(recorder.calls) == 3+ assert [call[3] for call in recorder.calls] == [None, 1, 2]+++ @pytest.mark.asyncio+ async def test_wrapper_async_fires_post_call_failure_deployment_hook_on_internal_calls(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: a failed attempt made while is_internal_call is set (e.g. an emulated+ file-search step) must still reach async_post_call_failure_deployment_hook, matching+ async_pre_call_deployment_hook, which already fires unconditionally for such calls."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])++ token = is_internal_call.set(True)+ try:+ with pytest.raises(litellm.AuthenticationError):+ await 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"+ ),+ )+ finally:+ is_internal_call.reset(token)- 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)+ assert len(recorder.calls) == 1+ assert isinstance(recorder.calls[0][1], litellm.AuthenticationError)- # --- bare model names ---- for key, expected_input, expected_output, expected_cache in [- ("deepseek-v4-flash", 1.4e-07, 2.8e-07, 2.8e-09),- ("deepseek-v4-pro", 4.35e-07, 8.7e-07, 3.625e-09),- ]:- info = model_cost.get(key)- assert info is not None, f"{key} missing from backup JSON"- assert info["litellm_provider"] == "deepseek"- assert info["mode"] == "chat"- assert info["input_cost_per_token"] == expected_input- assert info["output_cost_per_token"] == expected_output- assert info["cache_read_input_token_cost"] == expected_cache- assert info["max_input_tokens"] == 1_000_000- # --- provider-prefixed names ---- for key, expected_input, expected_output, expected_cache in [- ("deepseek/deepseek-v4-flash", 1.4e-07, 2.8e-07, 2.8e-09),- ("deepseek/deepseek-v4-pro", 4.35e-07, 8.7e-07, 3.625e-09),- ]:- info = model_cost.get(key)- assert info is not None, f"{key} missing from backup JSON"- assert info["litellm_provider"] == "deepseek"- assert info["mode"] == "chat"- assert info["input_cost_per_token"] == expected_input- assert info["output_cost_per_token"] == expected_output- assert info["cache_read_input_token_cost"] == expected_cache+ @pytest.mark.asyncio+ async def test_wrapper_async_does_not_fire_failure_hook_for_pre_call_budget_error(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: a BudgetExceededError raised before any deployment call is attempted+ (the [OPTIONAL] CHECK BUDGET gate) is not a deployment attempt failure and must not+ reach async_post_call_failure_deployment_hook."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])+ monkeypatch.setattr(litellm, "max_budget", 0.0001)+ monkeypatch.setattr(litellm, "_current_cost", 100.0)++ with pytest.raises(litellm.BudgetExceededError):+ await litellm.acompletion(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hi"}],+ mock_response="should never be reached",+ )+ assert recorder.calls == []- _FIREWORKS_MODELS = [- (- "accounts/fireworks/models/glm-5p2",- 1.4e-06,- 4.4e-06,- 2.6e-07,- 1048576,- 131072,- False,- True,- ),- (- "accounts/fireworks/models/glm-5p1",- 1.4e-06,- 4.4e-06,- 2.6e-07,- 202800,- 131072,- False,- True,- ),- (- "accounts/fireworks/routers/glm-5p1-fast",- 2.8e-06,- 8.8e-06,- 5.2e-07,- 202800,- 131072,- False,- True,- ),- (- "accounts/fireworks/models/qwen3p7-plus",- 4e-07,- 1.6e-06,- 8e-08,- 262144,- 65536,- True,- True,- ),- (- "accounts/fireworks/models/minimax-m3",- 3e-07,- 1.2e-06,- 6e-08,- 512000,- 512000,- True,- True,- ),- (- "accounts/fireworks/models/minimax-m2p7",- 3e-07,- 1.2e-06,- 6e-08,- 196608,- 196608,- False,- True,- ),- (- "accounts/fireworks/models/kimi-k2p7-code",- 9.5e-07,- 4e-06,- 1.9e-07,- 262144,- 262144,- True,- True,- ),- (- "accounts/fireworks/routers/kimi-k2p7-code-fast",- 1.9e-06,- 8e-06,- 3.8e-07,- 262144,- 262144,- True,- True,- ),- (- "accounts/fireworks/models/kimi-k2p6",- 9.5e-07,- 4e-06,- 1.6e-07,- 262144,- 262144,- True,- True,- ),- (- "accounts/fireworks/routers/kimi-k2p6-fast",- 2e-06,- 8e-06,- 3e-07,- 262144,- 262144,- True,- True,- ),- (- "accounts/fireworks/models/gpt-oss-120b",- 1.5e-07,- 6e-07,- 1.5e-08,- 131072,- 32768,- False,- True,- ),- (- "accounts/fireworks/models/gpt-oss-20b",- 7e-08,- 3e-07,- 3.5e-08,- 131072,- 32768,- False,- True,- ),- (- "accounts/fireworks/models/deepseek-v4-pro",- 1.74e-06,- 3.48e-06,- 1.45e-07,- 1048576,- 384000,- False,- True,- ),- (- "accounts/fireworks/models/deepseek-v4-flash",- 1.4e-07,- 2.8e-07,- 2.8e-08,- 1048576,- 384000,- False,- True,- ),- ]- _FIREWORKS_SHORT_FORMS = [- "glm-5p2",- "glm-5p1",- "qwen3p7-plus",- "minimax-m3",- "minimax-m2p7",- "kimi-k2p7-code",- "kimi-k2p6",- "gpt-oss-120b",- "gpt-oss-20b",- "deepseek-v4-pro",- "deepseek-v4-flash",- ]+ @pytest.mark.asyncio+ async def test_wrapper_async_does_not_fire_failure_hook_for_post_success_error(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: an error raised after the deployment call already succeeded (e.g. inside+ async_post_call_success_deployment_hook or post_call_processing) is not a deployment+ attempt failure and must not reach async_post_call_failure_deployment_hook."""- _FIREWORKS_ROUTER_SHORT_FORMS = [- "glm-5p1-fast",- "kimi-k2p6-fast",- "kimi-k2p7-code-fast",- ]+ class ExplodingSuccessLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.failure_calls: list[Exception] = []+ async def async_post_call_success_deployment_hook(self, request_data, response, call_type):+ raise RuntimeError("boom in success hook, model call itself succeeded")- def _assert_fireworks_entry(- model_cost,- model_path,- expected_input,- expected_output,- expected_cache,- expected_max_input,- expected_max_output,- expected_vision,- expected_reasoning,- ):- info = model_cost.get(f"fireworks_ai/{model_path}")- assert info is not None, f"fireworks_ai/{model_path} missing from model cost map"- assert info["litellm_provider"] == "fireworks_ai"- assert info["mode"] == "chat"- assert info["input_cost_per_token"] == expected_input- assert info["output_cost_per_token"] == expected_output- assert info["cache_read_input_token_cost"] == expected_cache- 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- assert info["supports_response_schema"] is True- assert info["supports_vision"] is expected_vision+ 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()+ monkeypatch.setattr(litellm, "callbacks", [exploding_logger])- def test_fireworks_models_in_cost_map():- import json- from pathlib import Path+ with pytest.raises(RuntimeError, match="boom in success hook"):+ await litellm.acompletion(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "hi"}],+ mock_response="this call succeeds",+ )- json_path = Path(__file__).parents[2] / "model_prices_and_context_window.json"- with open(json_path) as f:- model_cost = json.load(f)+ assert exploding_logger.failure_calls == []- 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}"+ @pytest.mark.asyncio+ async def test_wrapper_async_calls_hook_override_missing_fallback_depth_param(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: an override written before fallback_depth existed (this PR's own earlier+ proof-of-fix example used exactly this 3-arg signature) must still fire, not raise a+ TypeError on the fallback_depth keyword that gets swallowed at debug level."""++ class ThreeArgLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.calls: list[tuple[dict, Exception, CallTypes | None]] = []++ async def async_post_call_failure_deployment_hook(self, request_data, exception, call_type):+ self.calls.append((request_data, exception, call_type))++ three_arg_logger = ThreeArgLogger()+ monkeypatch.setattr(litellm, "callbacks", [three_arg_logger])++ with pytest.raises(litellm.AuthenticationError):+ await 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"),+ )- 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 len(three_arg_logger.calls) == 1+ assert isinstance(three_arg_logger.calls[0][1], litellm.AuthenticationError)- def test_fireworks_models_in_backup_cost_map():- import json- from pathlib import Path+ @pytest.mark.asyncio+ async def test_wrapper_async_failure_hook_exception_mutation_does_not_change_raised_exception(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: a callback setting an attribute on the exception it receives (e.g.+ status_code, as a real caller would read to determine the HTTP response) must not+ change what the actual caller ends up with - the hook must not have write access to+ 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):+ exception.status_code = 429++ monkeypatch.setattr(litellm, "callbacks", [StatusCodeMutatingLogger()])++ with pytest.raises(litellm.AuthenticationError) as exc_info:+ await 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"),+ )- 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)+ assert exc_info.value.status_code == 401- 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}"+ @pytest.mark.asyncio+ async def test_async_post_call_failure_deployment_hook_omits_attempted_targets_from_request_data(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: attempted_targets is the router's own live fallback-walk bookkeeping,+ shared by reference across every hop of a single request - unlike the rest of+ request_data, it is not this attempt's own isolated copy. A callback calling .record()+ on it would make the router skip a deployment it hasn't actually tried, so the+ dispatcher must never hand it to a callback."""+ recorder = _RecordingDeploymentFailureLogger()+ monkeypatch.setattr(litellm, "callbacks", [recorder])++ sentinel_targets = object()+ await async_post_call_failure_deployment_hook(+ request_data={"model": "gpt-4o-mini", "attempted_targets": sentinel_targets},+ exception=ValueError("x"),+ call_type="acompletion",+ )- 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 recorder.calls[0][0].get("attempted_targets") is None- 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``."""+ @pytest.mark.asyncio+ async def test_router_fallback_not_skipped_when_failure_hook_callback_touches_attempted_targets(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: even a callback that tries to record a target on whatever it's handed as+ attempted_targets must not affect the live Router fallback walk - the healthy fallback+ deployment must still be reachable, not silently skipped as already-attempted.++ attempted_targets is only present in kwargs starting from the second hop onward (the+ first deployment's own failure predates the router's own fallback bookkeeping), so this+ needs a 3-deployment chain: mid-group's failure is where the callback sees+ attempted_targets and can prematurely mark good-group as tried. Uses per-deployment+ mock_timeout/mock_response, not a request-level mock_response, which Router carries+ 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):+ attempted = request_data.get("attempted_targets")+ if attempted is not None:+ attempted.record("good-group")++ monkeypatch.setattr(litellm, "callbacks", [RecordingAttemptLogger()])++ def _mock_timeout_deployment(model_name: str) -> dict:+ return {+ "model_name": model_name,+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "fake",+ "mock_timeout": True,+ "timeout": 0.001,+ "num_retries": 0,+ },+ }- TOOLS = [- {- "type": "function",- "function": {- "name": "get_weather",- "parameters": {- "type": "object",- "properties": {"city": {"type": "string"}},+ router = litellm.Router(+ model_list=[+ _mock_timeout_deployment("bad-group"),+ _mock_timeout_deployment("mid-group"),+ {+ "model_name": "good-group",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": "fake",+ "mock_response": "fallback worked",+ "num_retries": 0,},},- }- ]+ ],+ num_retries=0,+ fallbacks=[{"bad-group": ["mid-group", "good-group"]}],+ )- def test_base_model_label_keeps_tools_with_drop_params(self):- from litellm.utils import get_optional_params+ response = await router.acompletion(+ model="bad-group",+ messages=[{"role": "user", "content": "hi"}],+ )- result = get_optional_params(- model="eu.anthropic.claude-haiku-4-5-20251001-v1:0",- custom_llm_provider="bedrock",- base_model="claude-haiku-4-5",- tools=self.TOOLS,- tool_choice="auto",- drop_params=True,+ assert response.choices[0].message.content == "fallback worked"+++ @pytest.mark.asyncio+ async def test_wrapper_async_preserves_original_exception_when_hook_await_is_cancelled(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: if the caller's own timeout (e.g. asyncio.wait_for) fires while the+ failure hook is still being awaited, the real deployment exception must still reach+ the caller - not get replaced by CancelledError/TimeoutError from the hook's own+ await getting cancelled."""++ class SlowLogger(CustomLogger):+ 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()])++ with pytest.raises(litellm.AuthenticationError):+ await asyncio.wait_for(+ 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"),+ ),+ timeout=0.2,)- assert "tools" in result- assert "tool_choice" in result- def test_base_model_label_alone_drops_tools(self):- """Without the real model id the label resolves to no tool support, so passing- the label as ``model`` is exactly what dropped tools before the fix."""- from litellm.utils import get_optional_params+ @pytest.mark.asyncio+ async def test_wrapper_async_failure_hook_latency_does_not_inflate_reported_duration(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: a slow failure-hook callback must not inflate the duration reported to+ async_log_failure_event - that's real observability data (e.g. latency dashboards),+ and the hook's own runtime is not part of how long the deployment call itself took."""+ reported_durations: list[float] = []- result = get_optional_params(- model="claude-haiku-4-5",- custom_llm_provider="bedrock",- tools=self.TOOLS,- tool_choice="auto",- drop_params=True,+ class SlowLoggerWithDurationCapture(CustomLogger):+ 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):+ reported_durations.append((end_time - start_time).total_seconds())++ monkeypatch.setattr(litellm, "callbacks", [SlowLoggerWithDurationCapture()])++ with pytest.raises(litellm.AuthenticationError):+ await 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"),)+ await asyncio.sleep(0.1)- assert "tools" not in result+ assert len(reported_durations) == 1+ assert reported_durations[0] < 0.5- def test_aws_bedrock_project_id_excluded_from_bedrock_optional_params():- """`aws_bedrock_project_id` is sent as a bedrock-mantle request header, so it- must never reach optional_params (and from there the request body), while- other aws_* params keep flowing for boto3 auth."""- from litellm.utils import get_optional_params+ @pytest.mark.asyncio+ async def test_wrapper_async_failure_hook_exception_snapshot_preserves_traceback(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression: the exception snapshot handed to failure-hook callbacks (see+ test_..._exception_mutation_does_not_change_raised_exception above) must still carry+ __traceback__/__cause__/__context__, not just __dict__/args - a callback formatting or+ inspecting the failure chain needs the real traceback, not an empty one."""+ received: list[Exception] = []++ class TracebackCapturingLogger(CustomLogger):+ 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()])++ with pytest.raises(litellm.AuthenticationError):+ await 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"),+ )- result = get_optional_params(- model="mantle/anthropic.claude-mythos-preview",- custom_llm_provider="bedrock",- max_tokens=10,- aws_bedrock_project_id="proj_abc123def456",- aws_region_name="us-east-1",- )+ assert len(received) == 1+ assert received[0].__traceback__ is not None- assert "aws_bedrock_project_id" not in result- assert result["aws_region_name"] == "us-east-1"+ def test_snapshot_exception_for_hook_preserves_suppress_context_flag() -> None:+ """Regression: setting __cause__ has a documented CPython side effect of implicitly+ forcing __suppress_context__ to True, even when the real exception's own+ __suppress_context__ is False (the common case: no `raise ... from`, just an+ exception raised while handling another one, which chains __context__ but does not+ 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")+ except ValueError:+ raise RuntimeError("outer error") # no `from` clause: implicit chaining, not suppressed+ with pytest.raises(RuntimeError) as exc_info:+ _raise_chained_without_from()- class TestGetOptionalParamsTencent:- """Tests that tencent provider uses TencentChatConfig for parameter mapping."""+ e = exc_info.value+ assert e.__suppress_context__ is False # sanity check on the real exception itself+ snapshot = _snapshot_exception_for_hook(e)+ assert snapshot.__suppress_context__ is False+ assert snapshot.__context__ is e.__context__- def test_tencent_supports_thinking_param(self):- """Verify get_optional_params for tencent accepts the 'thinking' param."""- from unittest.mock import patch- from litellm.utils import get_optional_params+ class TestDefaultReasoningEffortHydration:+ """`get_model_info` is the public shape every other capability key is readable through, so+ the declared default has to survive hydration too, not only the raw-map fallback the+ request-path gate happens to reach it by.+ """- with patch(- "litellm.llms.tencent.chat.transformation.supports_reasoning",- return_value=True,- ):- result = get_optional_params(- model="tencent/deepseek-v4-pro",- custom_llm_provider="tencent",- thinking={"type": "enabled"},- )- assert result.get("thinking") == {"type": "enabled"}+ @pytest.mark.parametrize(+ "model, provider",+ [("gpt-5.1", "openai"), ("gpt-5.4", "openai"), ("azure/gpt-5.1", "azure")],+ )+ def test_the_declared_default_survives_model_info_hydration(self, local_model_cost_map, model, provider):+ from litellm.utils import _get_model_info_helper- def test_tencent_supports_reasoning_effort(self):- """Verify get_optional_params for tencent converts reasoning_effort to thinking."""- from unittest.mock import patch+ model_info = dict(_get_model_info_helper(model=model, custom_llm_provider=provider))+ assert model_info["default_reasoning_effort"] == "none"- from litellm.utils import get_optional_params+ def test_a_model_that_declares_nothing_hydrates_to_none(self, local_model_cost_map):+ """Absent means "the map does not say", which the gate reads as reasoning being active."""+ from litellm.utils import _get_model_info_helper- with patch(- "litellm.llms.tencent.chat.transformation.supports_reasoning",- return_value=True,- ):- result = get_optional_params(- model="tencent/deepseek-v4-pro",- custom_llm_provider="tencent",- reasoning_effort="medium",- )- assert result.get("thinking") == {"type": "enabled"}+ model_info = dict(_get_model_info_helper(model="gpt-5.6-terra", custom_llm_provider="openai"))+ assert model_info.get("default_reasoning_effort") is None- def test_tencent_supported_params_includes_thinking_and_reasoning_effort(self):- """Verify get_supported_openai_params for tencent includes custom params."""- from unittest.mock import patch- from litellm.litellm_core_utils.get_supported_openai_params import (- get_supported_openai_params,- )+ class TestHuggingFaceConfigFetch:+ """The Hugging Face config.json fetch runs on background logging threads during cost+ calculation, so an unbounded request can hang a whole test job; the timeout is the fix."""- with patch(- "litellm.llms.tencent.chat.transformation.supports_reasoning",- return_value=True,- ):- params = get_supported_openai_params(- model="tencent/deepseek-v4-pro",- custom_llm_provider="tencent",+ @pytest.fixture+ def hf_config_route(self):+ with respx.mock(assert_all_called=True) as respx_mock:+ yield respx_mock.get(url__regex=r"https://huggingface\.co/.*/config\.json").respond(+ json={"max_position_embeddings": 512})- assert "thinking" in params- assert "reasoning_effort" in params- def test_tencent_messages_config_routing(self):- """Verify ProviderConfigManager routes tencent to TencentAnthropicMessagesConfig."""- import litellm- from litellm.llms.tencent.messages.transformation import (- TencentAnthropicMessagesConfig,- )- from litellm.utils import ProviderConfigManager+ def test_get_max_tokens_reads_hf_config_with_a_bounded_timeout(self, hf_config_route):+ from litellm.constants import HF_CONFIG_FETCH_TIMEOUT_SECONDS+ from litellm.utils import get_max_tokens- config = ProviderConfigManager.get_provider_anthropic_messages_config(- model="deepseek-v4-pro",- provider=litellm.LlmProviders.TENCENT,- )- assert isinstance(config, TencentAnthropicMessagesConfig)- assert config.custom_llm_provider == "tencent"+ assert get_max_tokens("huggingface/some-org/some-model") == 512+ request_timeout = hf_config_route.calls.last.request.extensions["timeout"]+ assert request_timeout["read"] == HF_CONFIG_FETCH_TIMEOUT_SECONDS+ def test_get_max_position_embeddings_reads_hf_config_with_a_bounded_timeout(self, hf_config_route):+ from litellm.constants import HF_CONFIG_FETCH_TIMEOUT_SECONDS+ from litellm.utils import _get_max_position_embeddings- class TestValidateEnvironmentTencent:- """Tests that validate_environment resolves TENCENT_API_KEY for the tencent provider."""+ assert _get_max_position_embeddings("some-org/some-model") == 512+ request_timeout = hf_config_route.calls.last.request.extensions["timeout"]+ assert request_timeout["read"] == HF_CONFIG_FETCH_TIMEOUT_SECONDS- def test_reports_key_present(self):- with patch.dict(os.environ, {"TENCENT_API_KEY": "sk-tencent"}):- result = litellm.validate_environment(model="tencent/deepseek-v4-pro")- assert result["keys_in_environment"] is True- assert result["missing_keys"] == []+ @pytest.mark.asyncio+ async def test_success_deployment_hook_chains_past_callback_returning_response(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression (LIT-5863): the dispatcher must run every callback, chaining each non-None+ result into the next call, instead of returning at the first callback answering non-None.+ A guardrail answering with the unmodified response used to starve every callback after it."""+ from litellm.types.utils import ModelResponse++ original = ModelResponse()+ replacement = ModelResponse()++ class PassthroughLogger(CustomLogger):+ async def async_post_call_success_deployment_hook(self, request_data, response, call_type):+ return response++ class ReplacingLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.seen: list = []++ async def async_post_call_success_deployment_hook(self, request_data, response, call_type):+ self.seen.append(response)+ return replacement++ class ObservingLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.seen: list = []++ async def async_post_call_success_deployment_hook(self, request_data, response, call_type):+ self.seen.append(response)+ return None++ replacer = ReplacingLogger()+ observer = ObservingLogger()+ monkeypatch.setattr(litellm, "callbacks", [PassthroughLogger(), replacer, observer])++ result = await async_post_call_success_deployment_hook(+ request_data={}, response=original, call_type=CallTypes.acompletion+ )- def test_reports_key_missing(self):- with patch.dict(os.environ, {}, clear=True):- result = litellm.validate_environment(model="tencent/deepseek-v4-pro")+ assert replacer.seen == [original]+ assert observer.seen == [replacement]+ assert result is replacement- assert result["keys_in_environment"] is False- assert "TENCENT_API_KEY" in result["missing_keys"]+ @pytest.mark.asyncio+ async def test_registered_guardrail_does_not_starve_vector_store_search_results(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Regression (LIT-5863): with any guardrail registered ahead of the lazily-appended+ VectorStorePreCallHook, /v1/chat/completions responses lost+ provider_specific_fields["search_results"] because the guardrail answered the unmodified+ response and the dispatcher stopped there."""+ from types import SimpleNamespace++ from litellm.integrations.custom_guardrail import CustomGuardrail+ from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import (+ VectorStorePreCallHook,+ )+ from litellm.types.utils import ModelResponse+ 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"}}])- @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",- "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",- ],- )- 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."+ monkeypatch.setattr(+ litellm,+ "callbacks",+ [CustomGuardrail(guardrail_name="dummy-guardrail"), VectorStorePreCallHook()],)- assert litellm.supports_reasoning(model) is False, (- f"{model} incorrectly classified as reasoning-capable. "- "Add 'supports_reasoning: false' to its model_cost entry."++ result = await async_post_call_success_deployment_hook(+ request_data={"litellm_logging_obj": logging_obj},+ response=response,+ call_type=CallTypes.acompletion,)+ provider_fields = result.choices[0].message.provider_specific_fields+ assert provider_fields is not None+ assert provider_fields["search_results"] == search_results- PROMPT_CACHE_MESSAGES = [{"role": "user", "content": "the quick brown fox jumps over the lazy dog " * 155}]+ class TestIsVisionExplicitlyDisabled:+ """github_copilot and chatgpt run an OAuth device flow inside get_llm_provider; the+ explicit-disable lookup must adopt the declared prefix instead of resolving it, exactly+ as _supports_factory does, or a capability check on a copilot deployment blocks routing+ on a device-code prompt."""- @pytest.mark.parametrize(- "model, expected_min_tokens",- [- ("claude-opus-4-6", 4096),- ("claude-opus-4-7", 2048),- ("claude-opus-4-8", 1024),- ("claude-fable-5", 512),- ],- )- def test_get_prompt_cache_min_tokens_resolves_per_model(- model: str, expected_min_tokens: int, local_model_cost_map: None- ) -> None:- """The smallest cacheable prefix is a per-model property, read from the cost map's- prompt_cache_min_tokens. Anthropic's minimum spans 512..4096 across models and moves in both- directions across releases, so a single global constant is wrong for every model but one."""- assert get_prompt_cache_min_tokens(model=model) == expected_min_tokens+ @pytest.mark.parametrize("model", ["github_copilot/gpt-4o", "chatgpt/gpt-5"])+ def test_never_resolves_an_authenticating_prefix(self, model, monkeypatch):+ from litellm.utils import is_vision_explicitly_disabled+ lookups: list = []- def test_get_prompt_cache_min_tokens_differs_per_platform_for_same_model(local_model_cost_map: None) -> None:- """The same model can carry a different minimum per platform, so the threshold must come from- the platform's own cost-map entry rather than being derived from the model family name."""- assert get_prompt_cache_min_tokens(model="claude-fable-5") == 512- assert get_prompt_cache_min_tokens(model="anthropic.claude-fable-5") == 1024- assert get_prompt_cache_min_tokens(model="claude-fable-5") != get_prompt_cache_min_tokens(- model="anthropic.claude-fable-5"- )+ def _record(*args, **kwargs):+ lookups.append((args, kwargs))+ raise RuntimeError("provider resolution must not run for an authenticating provider")+ monkeypatch.setattr(litellm, "get_llm_provider", _record)- def test_get_prompt_cache_min_tokens_unmapped_model_falls_back_to_default(local_model_cost_map: None) -> None:- """get_model_info raises for a model it has no entry for. The resolver must swallow that and- fall back to the default, otherwise the raise reaches callers that would read it as- "not cacheable" -- turning an unknown model into a silently uncacheable one."""- assert get_prompt_cache_min_tokens(model="totally-unknown-model-xyz") == 1024+ assert is_vision_explicitly_disabled(model) is False+ assert lookups == []+ def test_explicit_false_detected_and_absent_reads_enabled(self):+ from litellm.utils import is_vision_explicitly_disabled- def test_is_prompt_caching_valid_prompt_uses_per_model_minimum(local_model_cost_map: None) -> None:- """Regression: a prompt between two models' minimums is cacheable on one and not the other.- A 1403-token prompt clears claude-opus-4-8's 1024 minimum but not claude-opus-4-6's 4096, so- the flat-1024 check reported claude-opus-4-6 as cacheable and the cache write was rejected- upstream. Both assertions must live together: is_prompt_caching_valid_prompt returns False on- any internal error, so the True case is what proves the False case isn't a swallowed exception."""- token_count = litellm.token_counter(- model="claude-opus-4-6", messages=PROMPT_CACHE_MESSAGES, use_default_image_token_count=True- )- assert 1024 <= token_count < 4096, (- f"prompt drifted to {token_count} tokens; it must sit between claude-opus-4-8's 1024 minimum "- "and claude-opus-4-6's 4096 minimum for this test to distinguish them"- )+ 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+++ class TestVerboseRequestLineRedaction:+ """`litellm.set_verbose = True` echoes the caller's kwargs back as a `litellm.completion(...)`+ line on stdout, so a credential kwarg lands in whatever collects stdout: a terminal, a+ container log drain, a CI job log. Credential-named kwargs must not survive that echo,+ at any nesting depth, while ordinary params still must, or the line stops telling the+ developer what they called."""++ FAKE_API_KEY: Final = "sk-fake-lit6823-0000000000000000"++ def _verbose_request_line(self, capsys, monkeypatch, **kwargs) -> str:+ monkeypatch.setattr(litellm, "set_verbose", True)+ monkeypatch.setattr("litellm._logging.set_verbose", True)+ capsys.readouterr()+ litellm.completion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hello"}],+ mock_response="hi",+ **kwargs,+ )+ captured: Final = capsys.readouterr()+ return "\n".join(line for line in (captured.out + captured.err).splitlines() if "litellm.completion(" in line)++ def test_api_key_never_reaches_the_request_line(self, capsys, monkeypatch):+ printed: Final = self._verbose_request_line(capsys, monkeypatch, api_key=self.FAKE_API_KEY)++ assert "litellm.completion(" in printed+ assert self.FAKE_API_KEY not in printed+ assert "api_key='REDACTED'" in printed++ def test_credential_headers_never_reach_the_request_line(self, capsys, monkeypatch):+ printed: Final = self._verbose_request_line(+ capsys,+ monkeypatch,+ api_key=self.FAKE_API_KEY,+ extra_headers={"Authorization": "Bearer fake-lit6823-header", "x-request-id": "abc123"},+ )- assert is_prompt_caching_valid_prompt(model="claude-opus-4-6", messages=PROMPT_CACHE_MESSAGES) is False- assert is_prompt_caching_valid_prompt(model="claude-opus-4-8", messages=PROMPT_CACHE_MESSAGES) is True+ assert "fake-lit6823-header" not in printed+ assert "'Authorization': 'REDACTED'" in printed+ assert "'x-request-id': 'abc123'" in printed+ def test_credentials_nested_in_a_list_never_reach_the_request_line(self, capsys, monkeypatch):+ printed: Final = self._verbose_request_line(+ capsys,+ monkeypatch,+ api_key=self.FAKE_API_KEY,+ extra_body={"providers": [{"name": "openai", "api_key": "sk-fake-lit6823-nested"}]},+ )- def test_is_prompt_caching_valid_prompt_explicit_min_token_count_overrides_model(local_model_cost_map: None) -> None:- """An explicit min_token_count wins over the model-resolved value in both directions. Callers- holding only a model-group alias resolve the threshold themselves and pass it, because an alias- resolves to nothing here and would silently fall back to the default."""- assert (- is_prompt_caching_valid_prompt(model="claude-opus-4-6", messages=PROMPT_CACHE_MESSAGES, min_token_count=512)- is True- )- assert (- is_prompt_caching_valid_prompt(model="claude-opus-4-8", messages=PROMPT_CACHE_MESSAGES, min_token_count=8192)- is False- )+ assert "sk-fake-lit6823-nested" not in printed+ assert "'name': 'openai'" in printed++ def test_ordinary_params_still_printed(self, capsys, monkeypatch):+ printed: Final = self._verbose_request_line(+ capsys, monkeypatch, api_key=self.FAKE_API_KEY, max_tokens=17, temperature=0.25+ )++ assert "model='gpt-3.5-turbo'" in printed+ assert "max_tokens=17" in printed+ assert "temperature=0.25" in printed+++ class TestFinalOptionalParamsLineRedaction:+ """A verbose run echoes the fully built optional params too, and `extra_body` carries whatever the+ caller nested inside it straight onto that line, so a credential tucked in there lands in a terminal+ or a log drain in plaintext. It has to be redacted on both surfaces `print_verbose` writes to, and the+ line has to keep printing on both, because `litellm.set_verbose` and the DEBUG logger are independent+ switches and neither implies the other."""++ FAKE_NESTED_KEY: Final = "sk-fake-lit6835-nested-0000000000"++ def _complete(self, **kwargs) -> None:+ litellm.completion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hello"}],+ mock_response="hi",+ **kwargs,+ )++ def _printed_line(self, capsys) -> str:+ captured: Final = capsys.readouterr()+ return "\n".join(+ line for line in (captured.out + captured.err).splitlines() if "Final returned optional params" in line+ )++ def test_nested_credential_is_redacted_when_only_set_verbose_is_on(self, capsys, caplog, monkeypatch):+ monkeypatch.setattr(litellm, "set_verbose", True)+ with caplog.at_level(logging.WARNING, logger=verbose_logger.name):+ capsys.readouterr()+ self._complete(extra_body={"providers": [{"name": "openai", "api_key": self.FAKE_NESTED_KEY}]})+ printed: Final = self._printed_line(capsys)++ assert printed+ assert self.FAKE_NESTED_KEY not in printed+ assert "'api_key': 'REDACTED'" in printed+ assert "'name': 'openai'" in printed++ def test_line_still_reaches_the_logger_when_only_the_debug_logger_is_on(self, capsys, caplog, monkeypatch):+ monkeypatch.setattr(litellm, "set_verbose", False)+ with caplog.at_level(logging.DEBUG, logger=verbose_logger.name):+ self._complete(extra_body={"providers": [{"name": "openai", "api_key": self.FAKE_NESTED_KEY}]})+ logged: Final = "\n".join(+ record.getMessage()+ for record in caplog.records+ if "Final returned optional params" in record.getMessage()+ )++ assert logged+ assert self.FAKE_NESTED_KEY not in logged+ assert "'name': 'openai'" in logged++ def test_nothing_is_emitted_when_neither_verbose_switch_is_on(self, capsys, caplog, monkeypatch):+ monkeypatch.setattr(litellm, "set_verbose", False)+ with caplog.at_level(logging.WARNING, logger=verbose_logger.name):+ capsys.readouterr()+ self._complete(extra_body={"providers": [{"name": "openai", "api_key": self.FAKE_NESTED_KEY}]})+ captured: Final = capsys.readouterr()++ assert "Final returned optional params" not in captured.out + captured.err+ assert self.FAKE_NESTED_KEY not in captured.out + captured.err++ def test_ordinary_optional_params_still_reach_the_line(self, capsys, caplog, monkeypatch):+ monkeypatch.setattr(litellm, "set_verbose", True)+ with caplog.at_level(logging.WARNING, logger=verbose_logger.name):+ capsys.readouterr()+ self._complete(max_tokens=17, temperature=0.25)+ printed: Final = self._printed_line(capsys)++ assert "'max_tokens': 17" in printed+ assert "'temperature': 0.25" in printed+++class TestDropParamsStringCoercion:+ @pytest.mark.parametrize("drop_params", ["true", "True", True])+ def test_truthy_drop_params_drops_unsupported_temperature(self, drop_params, monkeypatch):+ from litellm.utils import get_optional_params++ monkeypatch.setattr(litellm, "drop_params", False)+ result = get_optional_params(+ model="gpt-5-nano",+ custom_llm_provider="openai",+ temperature=0.1,+ drop_params=drop_params,+ )+ assert "temperature" not in result++ @pytest.mark.parametrize("drop_params", ["false", False, None])+ def test_falsy_drop_params_still_raises(self, drop_params, monkeypatch):+ from litellm.utils import get_optional_params++ monkeypatch.setattr(litellm, "drop_params", False)+ with pytest.raises(litellm.UnsupportedParamsError):+ get_optional_params(+ model="gpt-5-nano",+ custom_llm_provider="openai",+ temperature=0.1,+ drop_params=drop_params,+ )diff --cc ui/litellm-dashboard/src/lib/http/schema.d.tsindex 62103e4f742,6fb08445aff..f7552bfb397--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@@ -25667,10 -29396,10 +29396,12 @@@ export interface componentsdefault_api_key_rpm_limit?: number | null;/** Default Api Key Tpm Limit */default_api_key_tpm_limit?: number | null;+ /** Drop Params */+ drop_params?: boolean | null;/** Gcs Bucket Name */gcs_bucket_name?: string | null;+ /** Google Maps Grounding Cost Per Query */+ google_maps_grounding_cost_per_query?: number | null;/** Input Cost Per Audio Per Second */input_cost_per_audio_per_second?: number | null;/** Input Cost Per Audio Per Second Above 128K Tokens */@@@ -33505,10 -39567,10 +39569,12 @@@default_api_key_rpm_limit?: number | null;/** Default Api Key Tpm Limit */default_api_key_tpm_limit?: number | null;+ /** Drop Params */+ drop_params?: boolean | null;/** Gcs Bucket Name */gcs_bucket_name?: string | null;+ /** Google Maps Grounding Cost Per Query */+ google_maps_grounding_cost_per_query?: number | null;/** Input Cost Per Audio Per Second */input_cost_per_audio_per_second?: number | null;/** Input Cost Per Audio Per Second Above 128K Tokens */