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 'main' into fix/bedrock-thinking-tool-call-2
Benedikt Óskarssonf09cae210702
diff --cc litellm/utils.pyindex e088b35037a,7c7591cdbab..9cb5b41aacb--- a/litellm/utils.py+++ b/litellm/utils.py@@@ -7417,15 -7462,184 +7469,184 @@@ def validate_chat_completion_tool_choicclass ProviderConfigManager:+ # Dictionary mapping for O(1) provider lookup+ # Stores tuples of (factory_function, needs_model_parameter)+ # This is initialized lazily on first access to avoid circular imports+ _PROVIDER_CONFIG_MAP: Optional[dict[LlmProviders, tuple[Callable, bool]]] = None++ @staticmethod+ def _build_provider_config_map() -> dict[LlmProviders, tuple[Callable, bool]]:+ """Build the provider-to-config mapping dictionary.-+++ Returns a dict mapping provider to (factory_function, needs_model_parameter).+ This avoids expensive inspect.signature() calls at runtime.+ """+ return {+ # Most common providers first for readability+ # Format: (factory_function, needs_model_parameter: bool)+ LlmProviders.OPENAI: (lambda: litellm.OpenAIGPTConfig(), False),+ LlmProviders.ANTHROPIC: (lambda: litellm.AnthropicConfig(), False),+ LlmProviders.AZURE: (lambda model: ProviderConfigManager._get_azure_config(model), True),+ LlmProviders.AZURE_AI: (lambda model: ProviderConfigManager._get_azure_ai_config(model), True),+ LlmProviders.VERTEX_AI: (lambda model: ProviderConfigManager._get_vertex_ai_config(model), True),+ LlmProviders.BEDROCK: (lambda model: ProviderConfigManager._get_bedrock_config(model), True),+ LlmProviders.COHERE: (lambda model: ProviderConfigManager._get_cohere_config(model), True),+ LlmProviders.COHERE_CHAT: (lambda model: ProviderConfigManager._get_cohere_config(model), True),+ # Simple provider mappings (no model parameter needed)+ LlmProviders.DEEPSEEK: (lambda: litellm.DeepSeekChatConfig(), False),+ LlmProviders.GROQ: (lambda: litellm.GroqChatConfig(), False),+ LlmProviders.BYTEZ: (lambda: litellm.BytezChatConfig(), False),+ LlmProviders.DATABRICKS: (lambda: litellm.DatabricksConfig(), False),+ LlmProviders.XAI: (lambda: litellm.XAIChatConfig(), False),+ LlmProviders.ZAI: (lambda: litellm.ZAIChatConfig(), False),+ LlmProviders.LAMBDA_AI: (lambda: litellm.LambdaAIChatConfig(), False),+ LlmProviders.LLAMA: (lambda: litellm.LlamaAPIConfig(), False),+ LlmProviders.TEXT_COMPLETION_OPENAI: (lambda: litellm.OpenAITextCompletionConfig(), False),+ LlmProviders.SNOWFLAKE: (lambda: litellm.SnowflakeConfig(), False),+ LlmProviders.CLARIFAI: (lambda: litellm.ClarifaiConfig(), False),+ LlmProviders.ANTHROPIC_TEXT: (lambda: litellm.AnthropicTextConfig(), False),+ LlmProviders.VERTEX_AI_BETA: (lambda: litellm.VertexGeminiConfig(), False),+ LlmProviders.CLOUDFLARE: (lambda: litellm.CloudflareChatConfig(), False),+ LlmProviders.SAGEMAKER_CHAT: (lambda: litellm.SagemakerChatConfig(), False),+ LlmProviders.SAGEMAKER: (lambda: litellm.SagemakerConfig(), False),+ LlmProviders.FIREWORKS_AI: (lambda: litellm.FireworksAIConfig(), False),+ LlmProviders.FRIENDLIAI: (lambda: litellm.FriendliaiChatConfig(), False),+ LlmProviders.WATSONX: (lambda: litellm.IBMWatsonXChatConfig(), False),+ LlmProviders.WATSONX_TEXT: (lambda: litellm.IBMWatsonXAIConfig(), False),+ LlmProviders.EMPOWER: (lambda: litellm.EmpowerChatConfig(), False),+ LlmProviders.MINIMAX: (lambda: litellm.MinimaxChatConfig(), False),+ LlmProviders.GITHUB: (lambda: litellm.GithubChatConfig(), False),+ LlmProviders.COMPACTIFAI: (lambda: litellm.CompactifAIChatConfig(), False),+ LlmProviders.GITHUB_COPILOT: (lambda: litellm.GithubCopilotConfig(), False),+ LlmProviders.GIGACHAT: (lambda: litellm.GigaChatConfig(), False),+ LlmProviders.RAGFLOW: (lambda: litellm.RAGFlowConfig(), False),+ LlmProviders.CUSTOM: (lambda: litellm.OpenAILikeChatConfig(), False),+ LlmProviders.CUSTOM_OPENAI: (lambda: litellm.OpenAILikeChatConfig(), False),+ LlmProviders.OPENAI_LIKE: (lambda: litellm.OpenAILikeChatConfig(), False),+ LlmProviders.AIOHTTP_OPENAI: (lambda: litellm.AiohttpOpenAIChatConfig(), False),+ LlmProviders.HOSTED_VLLM: (lambda: litellm.HostedVLLMChatConfig(), False),+ LlmProviders.LLAMAFILE: (lambda: litellm.LlamafileChatConfig(), False),+ LlmProviders.LM_STUDIO: (lambda: litellm.LMStudioChatConfig(), False),+ LlmProviders.GALADRIEL: (lambda: litellm.GaladrielChatConfig(), False),+ LlmProviders.REPLICATE: (lambda: litellm.ReplicateConfig(), False),+ LlmProviders.HUGGINGFACE: (lambda: litellm.HuggingFaceChatConfig(), False),+ LlmProviders.TOGETHER_AI: (lambda: litellm.TogetherAIConfig(), False),+ LlmProviders.OPENROUTER: (lambda: litellm.OpenrouterConfig(), False),+ LlmProviders.VERCEL_AI_GATEWAY: (lambda: litellm.VercelAIGatewayConfig(), False),+ LlmProviders.COMETAPI: (lambda: litellm.CometAPIConfig(), False),+ LlmProviders.DATAROBOT: (lambda: litellm.DataRobotConfig(), False),+ LlmProviders.GEMINI: (lambda: litellm.GoogleAIStudioGeminiConfig(), False),+ LlmProviders.AI21: (lambda: litellm.AI21ChatConfig(), False),+ LlmProviders.AI21_CHAT: (lambda: litellm.AI21ChatConfig(), False),+ LlmProviders.AZURE_TEXT: (lambda: litellm.AzureOpenAITextConfig(), False),+ LlmProviders.NLP_CLOUD: (lambda: litellm.NLPCloudConfig(), False),+ LlmProviders.OOBABOOGA: (lambda: litellm.OobaboogaConfig(), False),+ LlmProviders.OLLAMA_CHAT: (lambda: litellm.OllamaChatConfig(), False),+ LlmProviders.DEEPINFRA: (lambda: litellm.DeepInfraConfig(), False),+ LlmProviders.PERPLEXITY: (lambda: litellm.PerplexityChatConfig(), False),+ LlmProviders.MISTRAL: (lambda: litellm.MistralConfig(), False),+ LlmProviders.CODESTRAL: (lambda: litellm.MistralConfig(), False),+ LlmProviders.NVIDIA_NIM: (lambda: litellm.NvidiaNimConfig(), False),+ LlmProviders.CEREBRAS: (lambda: litellm.CerebrasConfig(), False),+ LlmProviders.BASETEN: (lambda: litellm.BasetenConfig(), False),+ LlmProviders.VOLCENGINE: (lambda: litellm.VolcEngineConfig(), False),+ LlmProviders.TEXT_COMPLETION_CODESTRAL: (lambda: litellm.CodestralTextCompletionConfig(), False),+ LlmProviders.SAMBANOVA: (lambda: litellm.SambanovaConfig(), False),+ LlmProviders.MARITALK: (lambda: litellm.MaritalkConfig(), False),+ LlmProviders.VLLM: (lambda: litellm.VLLMConfig(), False),+ LlmProviders.OLLAMA: (lambda: litellm.OllamaConfig(), False),+ LlmProviders.PREDIBASE: (lambda: litellm.PredibaseConfig(), False),+ LlmProviders.TRITON: (lambda: litellm.TritonConfig(), False),+ LlmProviders.PETALS: (lambda: litellm.PetalsConfig(), False),+ LlmProviders.SAP_GENERATIVE_AI_HUB: (lambda: litellm.GenAIHubOrchestrationConfig(), False),+ LlmProviders.FEATHERLESS_AI: (lambda: litellm.FeatherlessAIConfig(), False),+ LlmProviders.NOVITA: (lambda: litellm.NovitaConfig(), False),+ LlmProviders.NEBIUS: (lambda: litellm.NebiusConfig(), False),+ LlmProviders.WANDB: (lambda: litellm.WandbConfig(), False),+ LlmProviders.DASHSCOPE: (lambda: litellm.DashScopeChatConfig(), False),+ LlmProviders.MOONSHOT: (lambda: litellm.MoonshotChatConfig(), False),+ LlmProviders.DOCKER_MODEL_RUNNER: (lambda: litellm.DockerModelRunnerChatConfig(), False),+ LlmProviders.V0: (lambda: litellm.V0ChatConfig(), False),+ LlmProviders.MORPH: (lambda: litellm.MorphChatConfig(), False),+ LlmProviders.LITELLM_PROXY: (lambda: litellm.LiteLLMProxyChatConfig(), False),+ LlmProviders.GRADIENT_AI: (lambda: litellm.GradientAIConfig(), False),+ LlmProviders.NSCALE: (lambda: litellm.NscaleConfig(), False),+ LlmProviders.HEROKU: (lambda: litellm.HerokuChatConfig(), False),+ LlmProviders.OCI: (lambda: litellm.OCIChatConfig(), False),+ LlmProviders.HYPERBOLIC: (lambda: litellm.HyperbolicChatConfig(), False),+ LlmProviders.OVHCLOUD: (lambda: litellm.OVHCloudChatConfig(), False),+ LlmProviders.AMAZON_NOVA: (lambda: litellm.AmazonNovaChatConfig(), False),+ LlmProviders.LANGGRAPH: (lambda: ProviderConfigManager._get_langgraph_config(), False),+ }++ @staticmethod+ def _get_azure_config(model: str) -> BaseConfig:+ """Get Azure config based on model type."""+ if litellm.AzureOpenAIO1Config().is_o_series_model(model=model):+ return litellm.AzureOpenAIO1Config()+ if litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model(model=model):+ return litellm.AzureOpenAIGPT5Config()+ return litellm.AzureOpenAIConfig()++ @staticmethod+ def _get_azure_ai_config(model: str) -> BaseConfig:+ """Get Azure AI config based on model type."""+ if "claude" in model.lower():+ return litellm.AzureAnthropicConfig()+ return litellm.AzureAIStudioConfig()++ @staticmethod+ def _get_vertex_ai_config(model: str) -> BaseConfig:+ """Get Vertex AI config based on model type."""+ if "gemini" in model:+ return litellm.VertexGeminiConfig()+ elif "claude" in model:+ return litellm.VertexAIAnthropicConfig()+ elif "gpt-oss" in model:+ from litellm.llms.vertex_ai.vertex_ai_partner_models.gpt_oss.transformation import (+ VertexAIGPTOSSTransformation,+ )+ return VertexAIGPTOSSTransformation()+ elif model in litellm.vertex_mistral_models:+ if "codestral" in model:+ return litellm.CodestralTextCompletionConfig()+ return litellm.MistralConfig()+ elif model in litellm.vertex_ai_ai21_models:+ return litellm.VertexAIAi21Config()+ else:+ return litellm.VertexAILlama3Config()++ @staticmethod+ def _get_bedrock_config(model: str) -> BaseConfig:+ """Get Bedrock config based on model."""+ from litellm.llms.bedrock.common_utils import get_bedrock_chat_config+ return get_bedrock_chat_config(model=model)++ @staticmethod+ def _get_cohere_config(model: str) -> BaseConfig:+ """Get Cohere config based on route."""+ CohereModelInfo = getattr(sys.modules[__name__], 'CohereModelInfo')- route = CohereModelInfo.get_cohere_route(model)++ route = CohereModelInfo.get_cohere_route(model)+ if route == "v2":+ return litellm.CohereV2ChatConfig()+ return litellm.CohereChatConfig()++ @staticmethod+ def _get_langgraph_config() -> BaseConfig:+ """Get LangGraph config."""+ from litellm.llms.langgraph.chat.transformation import LangGraphConfig+ return LangGraphConfig()+@staticmethoddef get_provider_chat_config( # noqa: PLR0915model: str, provider: LlmProviders) -> Optional[BaseConfig]:"""Returns the provider config for a given provider.- """-+- # Check JSON providers FIRST+ Uses O(1) dictionary lookup for fast provider resolution.+ """+ # Check JSON providers FIRST (these override standard mappings)from litellm.llms.openai_like.dynamic_config import create_config_classfrom litellm.llms.openai_like.json_loader import JSONProviderRegistrydiff --cc tests/test_litellm/llms/bedrock/chat/test_converse_transformation.pyindex 473847c04fd,692866f8552..ee27775978e--- a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py+++ b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py@@@ -2736,132 -2736,74 +2736,204 @@@ def test_is_nova_lite_2_model()assert config._is_nova_lite_2_model("meta.llama3-70b-instruct-v1:0") is Falseassert config._is_nova_lite_2_model("mistral.mistral-7b-instruct-v0:2") is False++ def test_thinking_with_max_completion_tokens():+ """Test that thinking respects max_completion_tokens parameter."""+ config = AmazonConverseConfig()-+++ # Test case 1: max_completion_tokens is specified - should NOT set maxTokens automatically+ non_default_params_with_max_completion = {+ "thinking": {"type": "enabled", "budget_tokens": 5000},+ "max_completion_tokens": 10000,+ }+ optional_params = {}-+++ result = config.map_openai_params(+ non_default_params=non_default_params_with_max_completion,+ optional_params=optional_params,+ model="us.anthropic.claude-3-7-sonnet-20250219-v1:0",+ drop_params=False,+ )-+++ # Should have maxTokens set to max_completion_tokens value+ assert "maxTokens" in result+ assert result["maxTokens"] == 10000+ # Should have thinking config+ assert "thinking" in result+ assert result["thinking"]["type"] == "enabled"+ assert result["thinking"]["budget_tokens"] == 5000-+++ # Test case 2: max_tokens is specified - should NOT set maxTokens automatically+ non_default_params_with_max_tokens = {+ "thinking": {"type": "enabled", "budget_tokens": 5000},+ "max_tokens": 8000,+ }+ optional_params = {}-+++ result = config.map_openai_params(+ non_default_params=non_default_params_with_max_tokens,+ optional_params=optional_params,+ model="us.anthropic.claude-3-7-sonnet-20250219-v1:0",+ drop_params=False,+ )-+++ # Should have maxTokens set to max_tokens value+ assert "maxTokens" in result+ assert result["maxTokens"] == 8000+ # Should have thinking config+ assert "thinking" in result+ assert result["thinking"]["type"] == "enabled"+ assert result["thinking"]["budget_tokens"] == 5000-+++ # Test case 3: Neither max_tokens nor max_completion_tokens specified - should set maxTokens automatically+ from litellm.constants import DEFAULT_MAX_TOKENS-+++ non_default_params_without_max = {+ "thinking": {"type": "enabled", "budget_tokens": 5000},+ }+ optional_params = {}-+++ result = config.map_openai_params(+ non_default_params=non_default_params_without_max,+ optional_params=optional_params,+ model="us.anthropic.claude-3-7-sonnet-20250219-v1:0",+ drop_params=False,+ )-+++ # Should have maxTokens set to budget_tokens + DEFAULT_MAX_TOKENS+ assert "maxTokens" in result+ assert result["maxTokens"] == 5000 + DEFAULT_MAX_TOKENS+ # Should have thinking config+ assert "thinking" in result+ assert result["thinking"]["type"] == "enabled"+ assert result["thinking"]["budget_tokens"] == 5000+++def test_drop_thinking_param_when_thinking_blocks_missing():+ """+ Test that thinking param is dropped when modify_params=True and+ thinking_blocks are missing from assistant message with tool_calls.++ This prevents the Anthropic/Bedrock error:+ "Expected thinking or redacted_thinking, but found tool_use"++ Related issue: https://github.com/BerriAI/litellm/issues/14194+ """+ from litellm.utils import last_assistant_with_tool_calls_has_no_thinking_blocks++ # Save original modify_params setting+ original_modify_params = litellm.modify_params++ try:+ # Test case 1: thinking should be dropped when modify_params=True+ # and assistant message has tool_calls but no thinking_blocks+ litellm.modify_params = True++ messages_without_thinking_blocks = [+ {"role": "user", "content": "Search for weather"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_123",+ "type": "function",+ "function": {"name": "search", "arguments": "{}"},+ }+ ],+ # No thinking_blocks - simulates OpenAI-compatible client+ },+ {"role": "tool", "content": "Weather is sunny", "tool_call_id": "call_123"},+ ]++ optional_params = {"thinking": {"type": "enabled", "budget_tokens": 1000}}++ # Verify the condition is detected+ assert last_assistant_with_tool_calls_has_no_thinking_blocks(+ messages_without_thinking_blocks+ ), "Should detect missing thinking_blocks"++ # Simulate what _transform_request_helper does+ if (+ optional_params.get("thinking") is not None+ and messages_without_thinking_blocks is not None+ and last_assistant_with_tool_calls_has_no_thinking_blocks(+ messages_without_thinking_blocks+ )+ ):+ if litellm.modify_params:+ optional_params.pop("thinking", None)++ assert "thinking" not in optional_params, (+ "thinking param should be dropped when modify_params=True "+ "and thinking_blocks are missing"+ )++ # Test case 2: thinking should NOT be dropped when thinking_blocks are present+ messages_with_thinking_blocks = [+ {"role": "user", "content": "Search for weather"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_123",+ "type": "function",+ "function": {"name": "search", "arguments": "{}"},+ }+ ],+ "thinking_blocks": [+ {"type": "thinking", "thinking": "Let me search for weather..."}+ ],+ },+ {"role": "tool", "content": "Weather is sunny", "tool_call_id": "call_123"},+ ]++ optional_params_with_thinking = {+ "thinking": {"type": "enabled", "budget_tokens": 1000}+ }++ # Verify the condition is NOT detected when thinking_blocks are present+ assert not last_assistant_with_tool_calls_has_no_thinking_blocks(+ messages_with_thinking_blocks+ ), "Should NOT detect missing thinking_blocks when they are present"++ # Simulate what _transform_request_helper does+ if (+ optional_params_with_thinking.get("thinking") is not None+ and messages_with_thinking_blocks is not None+ and last_assistant_with_tool_calls_has_no_thinking_blocks(+ messages_with_thinking_blocks+ )+ ):+ if litellm.modify_params:+ optional_params_with_thinking.pop("thinking", None)++ assert "thinking" in optional_params_with_thinking, (+ "thinking param should NOT be dropped when thinking_blocks are present"+ )++ # Test case 3: thinking should NOT be dropped when modify_params=False+ litellm.modify_params = False++ optional_params_no_modify = {+ "thinking": {"type": "enabled", "budget_tokens": 1000}+ }++ # Simulate what _transform_request_helper does+ if (+ optional_params_no_modify.get("thinking") is not None+ and messages_without_thinking_blocks is not None+ and last_assistant_with_tool_calls_has_no_thinking_blocks(+ messages_without_thinking_blocks+ )+ ):+ if litellm.modify_params:+ optional_params_no_modify.pop("thinking", None)++ assert "thinking" in optional_params_no_modify, (+ "thinking param should NOT be dropped when modify_params=False"+ )++ finally:+ # Restore original modify_params setting+ litellm.modify_params = original_modify_params