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
[Feat] Enhance Mistral model support with reasoning capabilities
Cole McIntosh12a61fce4a21
diff --git a/litellm/llms/mistral/mistral_chat_transformation.py b/litellm/llms/mistral/mistral_chat_transformation.pyindex a675beebbda..3c90380f12b 100644--- a/litellm/llms/mistral/mistral_chat_transformation.py+++ b/litellm/llms/mistral/mistral_chat_transformation.py@@ -75,7 +75,7 @@ class MistralConfig(OpenAIGPTConfig):return super().get_config()def get_supported_openai_params(self, model: str) -> List[str]:- return [+ supported_params = ["stream","temperature","top_p",@@ -87,6 +87,12 @@ class MistralConfig(OpenAIGPTConfig):"stop","response_format",]++ # Add reasoning support for magistral models+ if "magistral" in model.lower():+ supported_params.extend(["thinking", "reasoning_effort"])++ return supported_paramsdef _map_tool_choice(self, tool_choice: str) -> str:if tool_choice == "auto" or tool_choice == "none":@@ -96,6 +102,20 @@ class MistralConfig(OpenAIGPTConfig):else: # openai 'tool_choice' object param not supported by Mistral APIreturn "any"+ @staticmethod+ def _get_mistral_reasoning_system_prompt() -> str:+ """+ Returns the system prompt for Mistral reasoning models.+ Based on Mistral's documentation: https://docs.mistral.ai/capabilities/reasoning/+ """+ return """When solving problems, think step-by-step in <think> tags before providing your final answer. Use the following format:++<think>+Your step-by-step reasoning process. Be thorough and work through the problem carefully.+</think>++Then provide a clear, concise answer based on your reasoning."""+def map_openai_params(self,non_default_params: dict,@@ -128,6 +148,12 @@ class MistralConfig(OpenAIGPTConfig):optional_params["extra_body"] = {"random_seed": value}if param == "response_format":optional_params["response_format"] = value+ if param == "reasoning_effort" and "magistral" in model.lower():+ # Flag that we need to add reasoning system prompt+ optional_params["_add_reasoning_prompt"] = True+ if param == "thinking" and "magistral" in model.lower():+ # Flag that we need to add reasoning system prompt+ optional_params["_add_reasoning_prompt"] = Truereturn optional_paramsdef _get_openai_compatible_provider_info(@@ -205,6 +231,43 @@ class MistralConfig(OpenAIGPTConfig):else:return super()._transform_messages(new_messages, model, False)+ def _add_reasoning_system_prompt_if_needed(+ self,+ messages: List[AllMessageValues],+ optional_params: dict+ ) -> List[AllMessageValues]:+ """+ Add reasoning system prompt for Mistral magistral models when reasoning_effort is specified.+ """+ if not optional_params.get("_add_reasoning_prompt", False):+ return messages++ # Check if there's already a system message+ has_system_message = any(msg.get("role") == "system" for msg in messages)++ if has_system_message:+ # Prepend reasoning instructions to existing system message+ for i, msg in enumerate(messages):+ if msg.get("role") == "system":+ existing_content = msg.get("content", "")+ reasoning_prompt = self._get_mistral_reasoning_system_prompt()+ messages[i] = {+ **msg,+ "content": f"{reasoning_prompt}\n\n{existing_content}"+ }+ break+ else:+ # Add new system message with reasoning instructions+ reasoning_message: AllMessageValues = {+ "role": "system",+ "content": self._get_mistral_reasoning_system_prompt()+ }+ messages = [reasoning_message] + messages++ # Remove the internal flag+ optional_params.pop("_add_reasoning_prompt", None)+ return messages+@classmethoddef _handle_name_in_message(cls, message: AllMessageValues) -> AllMessageValues:"""@@ -236,3 +299,31 @@ class MistralConfig(OpenAIGPTConfig):mistral_tool_calls.append(_tool_call_message)message["tool_calls"] = mistral_tool_calls # type: ignorereturn message++ def transform_request(+ self,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ headers: dict,+ ) -> dict:+ """+ Transform the overall request to be sent to the API.+ For magistral models, adds reasoning system prompt when reasoning_effort is specified.++ Returns:+ dict: The transformed request. Sent as the body of the API call.+ """+ # Add reasoning system prompt if needed (for magistral models)+ if "magistral" in model.lower() and optional_params.get("_add_reasoning_prompt", False):+ messages = self._add_reasoning_system_prompt_if_needed(messages, optional_params)++ # Call parent transform_request which handles _transform_messages+ return super().transform_request(+ model=model,+ messages=messages,+ optional_params=optional_params,+ litellm_params=litellm_params,+ headers=headers,+ )diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 22d60c0ae77..6104e613c73 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -4250,7 +4250,8 @@"source": "https://mistral.ai/news/magistral","supports_function_calling": true,"supports_assistant_prefill": true,- "supports_tool_choice": true+ "supports_tool_choice": true,+ "supports_reasoning": true},"mistral/magistral-small-2506": {"max_tokens": 40000,@@ -4263,7 +4264,8 @@"source": "https://mistral.ai/news/magistral","supports_function_calling": true,"supports_assistant_prefill": true,- "supports_tool_choice": true+ "supports_tool_choice": true,+ "supports_reasoning": true},"mistral/mistral-embed": {"max_tokens": 8192,diff --git a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.pyindex e8e50890e12..96a5671cb3e 100644--- a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py+++ b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py@@ -32,3 +32,252 @@ async def test_mistral_chat_transformation():"is_async": True,})+++class TestMistralReasoningSupport:+ """Test suite for Mistral Magistral reasoning functionality."""++ def test_get_supported_openai_params_magistral_model(self):+ """Test that magistral models support reasoning parameters."""+ mistral_config = MistralConfig()++ # Test magistral model supports reasoning parameters+ supported_params = mistral_config.get_supported_openai_params("mistral/magistral-medium-2506")+ assert "reasoning_effort" in supported_params+ assert "thinking" in supported_params++ # Test non-magistral model doesn't include reasoning parameters+ supported_params_normal = mistral_config.get_supported_openai_params("mistral/mistral-large-latest")+ assert "reasoning_effort" not in supported_params_normal+ assert "thinking" not in supported_params_normal++ def test_map_openai_params_reasoning_effort(self):+ """Test that reasoning_effort parameter is properly mapped for magistral models."""+ mistral_config = MistralConfig()++ # Test reasoning_effort mapping for magistral model+ optional_params = {}+ result = mistral_config.map_openai_params(+ non_default_params={"reasoning_effort": "low"},+ optional_params=optional_params,+ model="mistral/magistral-medium-2506",+ drop_params=False,+ )++ assert result.get("_add_reasoning_prompt") is True++ # Test reasoning_effort ignored for non-magistral model+ optional_params_normal = {}+ result_normal = mistral_config.map_openai_params(+ non_default_params={"reasoning_effort": "low"},+ optional_params=optional_params_normal,+ model="mistral/mistral-large-latest",+ drop_params=False,+ )++ assert "_add_reasoning_prompt" not in result_normal++ def test_map_openai_params_thinking(self):+ """Test that thinking parameter is properly mapped for magistral models."""+ mistral_config = MistralConfig()++ # Test thinking mapping for magistral model+ optional_params = {}+ result = mistral_config.map_openai_params(+ non_default_params={"thinking": {"budget": 1000}},+ optional_params=optional_params,+ model="mistral/magistral-small-2506",+ drop_params=False,+ )++ assert result.get("_add_reasoning_prompt") is True++ def test_get_mistral_reasoning_system_prompt(self):+ """Test that the reasoning system prompt is properly formatted."""+ prompt = MistralConfig._get_mistral_reasoning_system_prompt()++ assert "<think>" in prompt+ assert "</think>" in prompt+ assert "step-by-step" in prompt+ assert isinstance(prompt, str)+ assert len(prompt) > 50 # Ensure it's not empty++ def test_add_reasoning_system_prompt_no_existing_system_message(self):+ """Test adding reasoning system prompt when no system message exists."""+ mistral_config = MistralConfig()++ messages = [+ {"role": "user", "content": "What is 2+2?"}+ ]+ optional_params = {"_add_reasoning_prompt": True}++ result = mistral_config._add_reasoning_system_prompt_if_needed(messages, optional_params)++ # Should add a new system message at the beginning+ assert len(result) == 2+ assert result[0]["role"] == "system"+ assert "<think>" in result[0]["content"]+ assert result[1]["role"] == "user"+ assert result[1]["content"] == "What is 2+2?"++ # Should remove the internal flag+ assert "_add_reasoning_prompt" not in optional_params++ def test_add_reasoning_system_prompt_with_existing_system_message(self):+ """Test adding reasoning system prompt when system message already exists."""+ mistral_config = MistralConfig()++ messages = [+ {"role": "system", "content": "You are a helpful assistant."},+ {"role": "user", "content": "What is 2+2?"}+ ]+ optional_params = {"_add_reasoning_prompt": True}++ result = mistral_config._add_reasoning_system_prompt_if_needed(messages, optional_params)++ # Should modify existing system message+ assert len(result) == 2+ assert result[0]["role"] == "system"+ assert "<think>" in result[0]["content"]+ assert "You are a helpful assistant." in result[0]["content"]+ assert result[1]["role"] == "user"++ # Should remove the internal flag+ assert "_add_reasoning_prompt" not in optional_params++ def test_add_reasoning_system_prompt_no_flag(self):+ """Test that no modification happens when _add_reasoning_prompt flag is not set."""+ mistral_config = MistralConfig()++ messages = [+ {"role": "user", "content": "What is 2+2?"}+ ]+ optional_params = {}++ result = mistral_config._add_reasoning_system_prompt_if_needed(messages, optional_params)++ # Should return messages unchanged+ assert result == messages+ assert len(result) == 1++ def test_transform_request_magistral_with_reasoning(self):+ """Test transform_request method for magistral model with reasoning."""+ mistral_config = MistralConfig()++ messages = [+ {"role": "user", "content": "What is 15 * 7?"}+ ]+ optional_params = {"_add_reasoning_prompt": True}++ result = mistral_config.transform_request(+ model="mistral/magistral-medium-2506",+ messages=messages,+ optional_params=optional_params,+ litellm_params={},+ headers={}+ )++ # Should have added system message+ assert len(result["messages"]) == 2+ assert result["messages"][0]["role"] == "system"+ assert "<think>" in result["messages"][0]["content"]+ assert result["messages"][1]["role"] == "user"++ # Should remove internal flag from optional_params+ assert "_add_reasoning_prompt" not in result++ def test_transform_request_magistral_without_reasoning(self):+ """Test transform_request method for magistral model without reasoning."""+ mistral_config = MistralConfig()++ messages = [+ {"role": "user", "content": "What is 15 * 7?"}+ ]+ optional_params = {}++ result = mistral_config.transform_request(+ model="mistral/magistral-medium-2506",+ messages=messages,+ optional_params=optional_params,+ litellm_params={},+ headers={}+ )++ # Should not modify messages+ assert len(result["messages"]) == 1+ assert result["messages"][0]["role"] == "user"++ def test_transform_request_non_magistral_with_reasoning_params(self):+ """Test that non-magistral models ignore reasoning parameters."""+ mistral_config = MistralConfig()++ messages = [+ {"role": "user", "content": "What is 15 * 7?"}+ ]+ optional_params = {"_add_reasoning_prompt": True}++ result = mistral_config.transform_request(+ model="mistral/mistral-large-latest",+ messages=messages,+ optional_params=optional_params,+ litellm_params={},+ headers={}+ )++ # Should not add system message for non-magistral models+ assert len(result["messages"]) == 1+ assert result["messages"][0]["role"] == "user"++ def test_case_insensitive_magistral_detection(self):+ """Test that magistral model detection is case-insensitive."""+ mistral_config = MistralConfig()++ # Test various case combinations+ models_to_test = [+ "mistral/Magistral-medium-2506",+ "mistral/MAGISTRAL-MEDIUM-2506",+ "mistral/magistral-SMALL-2506",+ "MaGiStRaL-medium-2506"+ ]++ for model in models_to_test:+ supported_params = mistral_config.get_supported_openai_params(model)+ assert "reasoning_effort" in supported_params, f"Failed for model: {model}"++ def test_end_to_end_reasoning_workflow(self):+ """Test the complete workflow from parameter to system prompt injection."""+ mistral_config = MistralConfig()++ # Step 1: Map parameters+ optional_params = {}+ mapped_params = mistral_config.map_openai_params(+ non_default_params={"reasoning_effort": "high", "temperature": 0.7},+ optional_params=optional_params,+ model="mistral/magistral-medium-2506",+ drop_params=False,+ )++ assert mapped_params.get("_add_reasoning_prompt") is True+ assert mapped_params.get("temperature") == 0.7++ # Step 2: Transform request+ messages = [+ {"role": "user", "content": "Solve for x: 2x + 5 = 13"}+ ]++ result = mistral_config.transform_request(+ model="mistral/magistral-medium-2506",+ messages=messages,+ optional_params=mapped_params,+ litellm_params={},+ headers={}+ )++ # Verify final result+ assert len(result["messages"]) == 2+ assert result["messages"][0]["role"] == "system"+ assert "<think>" in result["messages"][0]["content"]+ assert result["messages"][1]["role"] == "user"+ assert result["messages"][1]["content"] == "Solve for x: 2x + 5 = 13"+ assert result.get("temperature") == 0.7+ assert "_add_reasoning_prompt" not in result