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
fix(mistral/chat/transformation.py): Support new mistral thinking block
Krrish Dholakia675d73fb9b80
diff --git a/litellm/llms/mistral/chat/transformation.py b/litellm/llms/mistral/chat/transformation.pyindex dda497dac86..385057bb45a 100644--- a/litellm/llms/mistral/chat/transformation.py+++ b/litellm/llms/mistral/chat/transformation.py@@ -28,7 +28,11 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import ()from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfigfrom litellm.secret_managers.main import get_secret_str-from litellm.types.llms.mistral import MistralToolCallMessage+from litellm.types.llms.mistral import (+ MistralTextBlock,+ MistralThinkingBlock,+ MistralToolCallMessage,+)from litellm.types.llms.openai import AllMessageValuesfrom litellm.types.utils import ModelResponsefrom litellm.utils import convert_to_model_response_object@@ -433,6 +437,58 @@ class MistralConfig(OpenAIGPTConfig):choice["message"]["content"] = Nonereturn response_data+ @staticmethod+ def _convert_thinking_block_to_reasoning_content(+ thinking_blocks: MistralThinkingBlock,+ ) -> str:+ """+ Convert Mistral thinking blocks to reasoning content.+ """+ return "\n".join(+ [block.get("text", "") for block in thinking_blocks["thinking"]]+ )++ @staticmethod+ def _handle_content_list_to_str_conversion(response_data: dict) -> dict:+ """+ Handle Mistral's content list format and extract thinking content.++ Map mistral's content list to string and extract thinking blocks:+ - Thinking block -> reasoning_content field+ - Text block -> content field+ """++ if response_data.get("choices") and len(response_data["choices"]) > 0:+ for choice in response_data["choices"]:+ if choice.get("message") and choice["message"].get("content"):+ content = choice["message"]["content"]++ # Only process if content is a list+ if isinstance(content, list):+ thinking_content = ""+ text_content = ""++ # Process each content block+ for block in content:+ if block.get("type") == "thinking":+ thinking_blocks = block.get("thinking", [])+ thinking_texts = []+ for thinking_block in thinking_blocks:+ if thinking_block.get("type") == "text":+ thinking_texts.append(+ thinking_block.get("text", "")+ )+ thinking_content = "\n".join(thinking_texts)+ elif block.get("type") == "text":+ text_content = block.get("text", "")++ # Set the extracted content+ choice["message"]["content"] = text_content+ if thinking_content:+ choice["message"]["reasoning_content"] = thinking_content++ return response_data+def transform_request(self,model: str,@@ -481,14 +537,16 @@ class MistralConfig(OpenAIGPTConfig):) -> ModelResponse:"""Transform the raw response from Mistral API.- Handles Mistral-specific behavior like converting empty string content to None.+ Handles Mistral-specific behavior like converting empty string content to None+ and extracting thinking content from content lists."""logging_obj.post_call(original_response=raw_response.text)logging_obj.model_call_details["response_headers"] = raw_response.headers- # Handle Mistral-specific empty string content conversion to None+ # Handle Mistral-specific response transformationsresponse_data = raw_response.json()response_data = self._handle_empty_content_response(response_data)+ response_data = self._handle_content_list_to_str_conversion(response_data)final_response_obj = cast(ModelResponse,diff --git a/litellm/types/llms/mistral.py b/litellm/types/llms/mistral.pyindex e9563a9ae3f..375120e5376 100644--- a/litellm/types/llms/mistral.py+++ b/litellm/types/llms/mistral.py@@ -10,3 +10,13 @@ class MistralToolCallMessage(TypedDict):id: Optional[str]type: Literal["function"]function: Optional[FunctionCall]+++class MistralTextBlock(TypedDict):+ type: Literal["text"]+ text: str+++class MistralThinkingBlock(TypedDict):+ type: Literal["thinking"]+ thinking: List[MistralTextBlock]diff --git a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.pyindex dd48bae3922..d1859c2c5ba 100644--- a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py+++ b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py@@ -9,6 +9,7 @@ sys.path.insert() # Adds the parent directory to the system pathfrom litellm.llms.mistral.chat.transformation import MistralConfig+from litellm.types.utils import ModelResponse@pytest.mark.asyncio@@ -424,6 +425,115 @@ class TestMistralParallelToolCalls:assert result["messages"][0]["role"] == "user"+class TestMistralThinkingContentHandling:+ """Test suite for Mistral thinking content response handling functionality."""++ def test_transform_response_with_thinking_content(self):+ """Test that Mistral responses with thinking content are correctly transformed."""+ import json+ from unittest.mock import Mock++ import litellm++ # Raw response from Mistral with thinking content+ raw_response_data = {+ "id": "12a18e1439f24f95b9812a016e0af235",+ "choices": [+ {+ "finish_reason": "stop",+ "index": 0,+ "logprobs": None,+ "message": {+ "content": [+ {+ "type": "thinking",+ "thinking": [+ {+ "type": "text",+ "text": "Well, the capital of France is a well-known fact. It's Paris. But just to be sure, I recall that Paris is indeed the capital city of France. I don't need to look it up because it's a common knowledge fact. But if I were unsure, I would double-check using a reliable source or a knowledge base. Since I'm confident about this, I can provide the answer directly.",+ }+ ],+ },+ {"type": "text", "text": "The capital of France is Paris."},+ ],+ "refusal": None,+ "role": "assistant",+ "annotations": None,+ "audio": None,+ "function_call": None,+ "tool_calls": None,+ },+ }+ ],+ "created": 1754654178,+ "model": "magistral-medium-2507",+ "object": "chat.completion",+ "service_tier": None,+ "system_fingerprint": None,+ "usage": {+ "completion_tokens": 93,+ "prompt_tokens": 11,+ "total_tokens": 104,+ "completion_tokens_details": None,+ "prompt_tokens_details": None,+ },+ }++ # Mock httpx response+ mock_response = Mock()+ mock_response.json.return_value = raw_response_data+ mock_response.headers = {}+ mock_response.text = json.dumps(raw_response_data)++ # Mock logging object with proper attributes+ mock_logging_obj = Mock()+ mock_logging_obj.model_call_details = {}++ # Test the transformation+ mistral_config = MistralConfig()+ model_response = litellm.ModelResponse()++ # Test transform_response method+ final_response = mistral_config.transform_response(+ model="mistral/magistral-medium-2507",+ raw_response=mock_response,+ model_response=model_response,+ logging_obj=mock_logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ optional_params={},+ litellm_params={},+ encoding=None,+ )++ # Verify the response structure+ assert final_response is not None+ assert len(final_response.choices) == 1+ choice = final_response.choices[0]++ # Verify message content+ message = choice.message+ assert message.role == "assistant"++ # The content should be processed - either as text or as thinking blocks+ # Content could be the text part or the full content list+ content_str = str(message.content) if message.content else ""++ # Verify the actual text content is preserved somewhere+ assert "The capital of France is Paris." in content_str or (+ hasattr(message, "thinking_blocks") and message.thinking_blocks+ )++ # Verify usage information+ assert final_response.usage.completion_tokens == 93+ assert final_response.usage.prompt_tokens == 11+ assert final_response.usage.total_tokens == 104++ # Verify model and metadata+ assert final_response.id == "12a18e1439f24f95b9812a016e0af235"+ assert final_response.created == 1754654178++class TestMistralEmptyContentHandling:"""Test suite for Mistral empty content response handling functionality."""