Skip to content

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]

fix: mistral transform_response handling for empty string content (#12202)

Nathan Brakec2dbc9c64b03
diff --git a/litellm/llms/mistral/mistral_chat_transformation.py b/litellm/llms/mistral/mistral_chat_transformation.py
index e281e055537..3bff50a8fdc 100644
--- a/litellm/llms/mistral/mistral_chat_transformation.py
+++ b/litellm/llms/mistral/mistral_chat_transformation.py
@@ -8,6 +8,8 @@ Docs - https://docs.mistral.ai/api/
from typing import Any, Coroutine, List, Literal, Optional, Tuple, Union, cast, overload
+import httpx
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.litellm_core_utils.prompt_templates.common_utils import (
handle_messages_with_content_list_to_str_conversion,
strip_none_values_from_message,
@@ -16,6 +18,8 @@ from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig
from litellm.secret_managers.main import get_secret_str
from litellm.types.llms.mistral import MistralToolCallMessage
from litellm.types.llms.openai import AllMessageValues
+from litellm.types.utils import ModelResponse
+from litellm.utils import convert_to_model_response_object
class MistralConfig(OpenAIGPTConfig):
@@ -92,7 +96,7 @@ class MistralConfig(OpenAIGPTConfig):
# Add reasoning support for magistral models
if "magistral" in model.lower():
supported_params.extend(["thinking", "reasoning_effort"])
-
+
return supported_params
def _map_tool_choice(self, tool_choice: str) -> str:
@@ -140,9 +144,7 @@ class MistralConfig(OpenAIGPTConfig):
for param, value in non_default_params.items():
if param == "max_tokens":
optional_params["max_tokens"] = value
- if (
- param == "max_completion_tokens"
- ): # max_completion_tokens should take priority
+ if param == "max_completion_tokens": # max_completion_tokens should take priority
optional_params["max_tokens"] = value
if param == "tools":
optional_params["tools"] = value
@@ -155,9 +157,7 @@ class MistralConfig(OpenAIGPTConfig):
if param == "stop":
optional_params["stop"] = value
if param == "tool_choice" and isinstance(value, str):
- optional_params["tool_choice"] = self._map_tool_choice(
- tool_choice=value
- )
+ optional_params["tool_choice"] = self._map_tool_choice(tool_choice=value)
if param == "seed":
optional_params["extra_body"] = {"random_seed": value}
if param == "response_format":
@@ -183,9 +183,7 @@ class MistralConfig(OpenAIGPTConfig):
) # type: ignore
# if api_base does not end with /v1 we add it
- if api_base is not None and not api_base.endswith(
- "/v1"
- ): # Mistral always needs a /v1 at the end
+ if api_base is not None and not api_base.endswith("/v1"): # Mistral always needs a /v1 at the end
api_base = api_base + "/v1"
dynamic_api_key = (
api_key
@@ -197,8 +195,7 @@ class MistralConfig(OpenAIGPTConfig):
@overload
def _transform_messages(
self, messages: List[AllMessageValues], model: str, is_async: Literal[True]
- ) -> Coroutine[Any, Any, List[AllMessageValues]]:
- ...
+ ) -> Coroutine[Any, Any, List[AllMessageValues]]: ...
@overload
def _transform_messages(
@@ -206,8 +203,7 @@ class MistralConfig(OpenAIGPTConfig):
messages: List[AllMessageValues],
model: str,
is_async: Literal[False] = False,
- ) -> List[AllMessageValues]:
- ...
+ ) -> List[AllMessageValues]: ...
def _transform_messages(
self, messages: List[AllMessageValues], model: str, is_async: bool = False
@@ -248,52 +244,44 @@ class MistralConfig(OpenAIGPTConfig):
return super()._transform_messages(new_messages, model, False)
def _add_reasoning_system_prompt_if_needed(
- self,
- messages: List[AllMessageValues],
- optional_params: dict
+ 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()
-
+
# Handle both string and list content, preserving original format
if isinstance(existing_content, str):
# String content - prepend reasoning prompt
new_content: Union[str, list] = f"{reasoning_prompt}\n\n{existing_content}"
elif isinstance(existing_content, list):
# List content - prepend reasoning prompt as text block
- new_content = [
- {"type": "text", "text": reasoning_prompt + "\n\n"}
- ] + existing_content
+ new_content = [{"type": "text", "text": reasoning_prompt + "\n\n"}] + existing_content
else:
# Fallback for any other type - convert to string
new_content = f"{reasoning_prompt}\n\n{str(existing_content)}"
-
- messages[i] = cast(AllMessageValues, {
- **msg,
- "content": new_content
- })
+
+ messages[i] = cast(AllMessageValues, {**msg, "content": new_content})
break
else:
# Add new system message with reasoning instructions
- reasoning_message: AllMessageValues = cast(AllMessageValues, {
- "role": "system",
- "content": self._get_mistral_reasoning_system_prompt()
- })
+ reasoning_message: AllMessageValues = cast(
+ 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
@@ -307,7 +295,7 @@ class MistralConfig(OpenAIGPTConfig):
Otherwise, we drop `name`
"""
_name = message.get("name") # type: ignore
-
+
if _name is not None:
# Remove name if not a tool message
if message["role"] != "tool":
@@ -336,6 +324,26 @@ class MistralConfig(OpenAIGPTConfig):
message["tool_calls"] = mistral_tool_calls # type: ignore
return message
+ @staticmethod
+ def _handle_empty_content_response(response_data: dict) -> dict:
+ """
+ Handle Mistral-specific behavior where empty string content should be converted to None.
+
+ Mistral API sometimes returns empty string content ('') instead of null,
+ which can cause issues with downstream processing.
+
+ Args:
+ response_data: The raw response data from Mistral API
+
+ Returns:
+ dict: The response data with empty string content converted to None
+ """
+ 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") == "":
+ choice["message"]["content"] = None
+ return response_data
+
def transform_request(
self,
model: str,
@@ -354,7 +362,7 @@ class MistralConfig(OpenAIGPTConfig):
# 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,
@@ -363,3 +371,40 @@ class MistralConfig(OpenAIGPTConfig):
litellm_params=litellm_params,
headers=headers,
)
+
+ def transform_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: ModelResponse,
+ logging_obj: LiteLLMLoggingObj,
+ request_data: dict,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ encoding: Any,
+ api_key: Optional[str] = None,
+ json_mode: Optional[bool] = None,
+ ) -> ModelResponse:
+ """
+ Transform the raw response from Mistral API.
+ Handles Mistral-specific behavior like converting empty string content to None.
+ """
+ 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
+ response_data = raw_response.json()
+ response_data = self._handle_empty_content_response(response_data)
+
+ final_response_obj = cast(
+ ModelResponse,
+ convert_to_model_response_object(
+ response_object=response_data,
+ model_response_object=model_response,
+ hidden_params={"headers": raw_response.headers},
+ _response_headers=dict(raw_response.headers),
+ ),
+ )
+
+ return final_response_obj
diff --git a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py
index be0e73d8506..6a61cef00a8 100644
--- a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py
+++ b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py
@@ -408,4 +408,72 @@ class TestMistralParallelToolCalls:
assert result.get("parallel_tool_calls") is True
assert len(result["messages"]) == 1
- assert result["messages"][0]["role"] == "user"
\ No newline at end of file
+ assert result["messages"][0]["role"] == "user"
+
+
+class TestMistralEmptyContentHandling:
+ """Test suite for Mistral empty content response handling functionality."""
+
+ def test_handle_empty_content_response_converts_empty_string_to_none(self):
+ """Test that empty string content is converted to None."""
+ response_data = {
+ "choices": [
+ {
+ "message": {
+ "content": "",
+ "role": "assistant"
+ },
+ "finish_reason": "stop"
+ }
+ ]
+ }
+
+ result = MistralConfig._handle_empty_content_response(response_data)
+
+ assert result["choices"][0]["message"]["content"] is None
+
+ def test_handle_empty_content_response_preserves_actual_content(self):
+ """Test that actual content is preserved unchanged."""
+ response_data = {
+ "choices": [
+ {
+ "message": {
+ "content": "Hello, how can I help you?",
+ "role": "assistant"
+ },
+ "finish_reason": "stop"
+ }
+ ]
+ }
+
+ result = MistralConfig._handle_empty_content_response(response_data)
+
+ assert result["choices"][0]["message"]["content"] == "Hello, how can I help you?"
+
+ def test_handle_empty_content_response_handles_multiple_choices(self):
+ """Test that only the first choice is processed for empty content."""
+ response_data = {
+ "choices": [
+ {
+ "message": {
+ "content": "",
+ "role": "assistant"
+ },
+ "finish_reason": "stop"
+ },
+ {
+ "message": {
+ "content": "",
+ "role": "assistant"
+ },
+ "finish_reason": "stop"
+ }
+ ]
+ }
+
+ result = MistralConfig._handle_empty_content_response(response_data)
+
+ # Only first choice should be converted to None
+ assert result["choices"][0]["message"]["content"] is None
+ # Second choice should remain as empty string
+ assert result["choices"][1]["message"]["content"] is None
\ No newline at end of file