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
[Enhancement] Add support for Mistral model file handling and update documentation
jinskjoyd8a33e137d0b
diff --git a/docs/my-website/docs/completion/document_understanding.md b/docs/my-website/docs/completion/document_understanding.mdindex b831a7b9da2..172e0792801 100644--- a/docs/my-website/docs/completion/document_understanding.md+++ b/docs/my-website/docs/completion/document_understanding.md@@ -10,6 +10,7 @@ Works for:- Bedrock Models- Anthropic API Models- OpenAI API Models+- Mistral (Only using file ID of already uploaded file, similar to OpenAI file_id input)## Quick Start@@ -279,6 +280,71 @@ curl -X POST 'http://0.0.0.0:4000/chat/completions' \</Tabs>+## Mistral Example++Here is a sample payload for using the Mistral model for document understanding:+++<Tabs>+<TabItem value="sdk" label="SDK">++```python+from litellm.utils import completion++# pdf file_id received from files endpoint+file_id = "fa778e5e-46ec-4562-8418-36623fe25a71"++# model+model = "mistral/mistral-large-latest"++file_content = [+ {"type": "text", "text": "What's this file about?"},+ {+ "type": "file",+ "file": {+ "file_id": file_id,+ }+ },+]++response = completion(+ model=model,+ messages=[{"role": "user", "content": file_content}],+)+assert response is not None+```++</TabItem>+<TabItem value="proxy" label="PROXY">++```bash+curl -X POST 'http://0.0.0.0:4000/chat/completions' \+-H 'Content-Type: application/json' \+-H 'Authorization: Bearer sk-1234' \+-d '{+ "model": "mistral/mistral-large-latest",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "What is the content of the file?"+ },+ {+ "type": "file",+ "file": {+ "file_id": "fa778e5e-46ec-4562-8418-36623fe25a71"+ }+ }+ ]+ }+ ]+}+```+</TabItem>+</Tabs>+## Checking if a model supports pdf input<Tabs>diff --git a/litellm/llms/mistral/chat/transformation.py b/litellm/llms/mistral/chat/transformation.pyindex b38a4982471..af4ded0983b 100644--- a/litellm/llms/mistral/chat/transformation.py+++ b/litellm/llms/mistral/chat/transformation.py@@ -218,18 +218,20 @@ class MistralConfig(OpenAIGPTConfig):- if image passed in, then just return as is (user-intended)- if `name` is passed, then drop it for mistral API: https://github.com/BerriAI/litellm/issues/6696- Motivation: mistral api doesn't support content as a list+ Motivation: mistral api doesn't support content as a list.+ The above statement is not valid now. Need to plan to remove all the #1,2,3+ Mistral API supports content as a list."""- ## 1. If 'image_url' in content, then return as is+ ## 1. If 'image_url' or 'file' in content, then transform with base class and mistral-specific handlingfor m in messages:_content_block = m.get("content")if _content_block and isinstance(_content_block, list):- for c in _content_block:- if c.get("type") == "image_url":- if is_async:- return super()._transform_messages(messages, model, True)- else:- return super()._transform_messages(messages, model, False)+ if any(c.get("type") in ["image_url", "file"] for c in _content_block):+ if is_async:+ return self._transform_messages_async(messages, model)+ else:+ messages = self._transform_messages_sync(messages, model)+ return messages## 2. If content is list, then convert to stringmessages = handle_messages_with_content_list_to_str_conversion(messages)@@ -247,6 +249,51 @@ class MistralConfig(OpenAIGPTConfig):else:return super()._transform_messages(new_messages, model, False)+ async def _transform_messages_async(self,+ messages: List[AllMessageValues], model: str+ ) -> List[AllMessageValues]:+ """+ Handle modification of messages for Mistral API in an async context.+ """+ # Call parent async method to handle basic transformations+ # and then apply Mistral-specific handling for files+ messages = await super()._transform_messages(messages, model, True)+ messages = self._handle_message_with_file(messages)+ return messages++ def _transform_messages_sync(self,+ messages: List[AllMessageValues], model: str+ ) -> List[AllMessageValues]:+ """ Handle modification of messages for Mistral API in a sync context.+ """+ # Call parent sync method to handle basic transformations+ # and then apply Mistral-specific handling for files+ # This is the sync version of the async method above+ messages = super()._transform_messages(messages, model, False)+ messages = self._handle_message_with_file(messages)+ return messages++ def _handle_message_with_file(+ self,+ messages: List[AllMessageValues]) -> List[AllMessageValues]:+ """+ Mistral API supports only 'file_id' in message content with type 'file'.+ """+ for m in messages:+ _content_block = m.get("content")+ if _content_block and isinstance(_content_block, list):+ if any(c.get("type") == "file" for c in _content_block):+ # If file content is present, we get file_id from 'file' attribute of content block+ # then replace 'file' with 'file_id' and assign the value of 'file_id' attribute to it.+ file_contents = [c for c in _content_block if c.get("type") == "file"]+ for file_content in file_contents:+ file_id = file_content.get("file", {}).get("file_id")+ if file_id:+ # Replace 'file' with 'file_id'+ file_content["file_id"] = file_id # type: ignore+ file_content.pop("file", None)+ return messages+def _add_reasoning_system_prompt_if_needed(self, messages: List[AllMessageValues], optional_params: dict) -> List[AllMessageValues]:diff --git a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.pyindex 3e4d3ddb304..b02a6a1ceaa 100644--- a/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py+++ b/tests/test_litellm/llms/mistral/test_mistral_chat_transformation.py@@ -1,9 +1,12 @@import osimport sys+from typing import List, castfrom unittest.mock import MagicMock, patchimport pytest+from litellm.types.llms.openai import AllMessageValues+sys.path.insert(0, os.path.abspath("../..")) # Adds the parent directory to the system path@@ -476,4 +479,76 @@ class TestMistralEmptyContentHandling:# Only first choice should be converted to Noneassert 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+ assert result["choices"][1]["message"]["content"] is None++class TestMistralFileHandling:+ """Test suite for Mistral file handling functionality."""++ def test_handle_file_message_with_file_id(self):+ """Test that file messages with file_id are handled correctly."""+ mistral_config = MistralConfig()+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Please review this file."},+ {"type": "file", "file": {"file_id": "file-12345"}}+ ]+ }+ ]+ casted_message = cast(list[AllMessageValues], messages)+ result = mistral_config._handle_message_with_file(casted_message)+ assert len(result) == 1+ assert result[0]["role"] == "user"+ # Check that content is transformed correctly+ assert isinstance(result[0]["content"], list)+ assert len(result[0]["content"]) == 2+ # Check that file type is preserved+ assert result[0]["content"][1]["type"] == "file"+ # Check that file_id is modified to match Mistral's expected format+ assert result[0]["content"][1]["file_id"] == "file-12345" # type: ignore++ def test_handle_file_message_without_file_id(self):+ """Test that file messages without file_id are ignored."""+ mistral_config = MistralConfig()+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Please review this file."}+ ]+ }+ ]+ casted_message = cast(list[AllMessageValues], messages)+ result = mistral_config._handle_message_with_file(casted_message)+ assert len(result) == 1+ assert result[0]["role"] == "user"+ assert isinstance(result[0]["content"], list)+ assert len(result[0]["content"]) == 1 # Only text part remains++ def test_handle_message_with_file_multiple_files(self):+ """Test that multiple file messages are handled correctly."""+ mistral_config = MistralConfig()+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Please review these files."},+ {"type": "file", "file": {"file_id": "file-12345"}},+ {"type": "file", "file": {"file_id": "file-67890"}}+ ]+ }+ ]+ casted_message = cast(list[AllMessageValues], messages)+ result = mistral_config._handle_message_with_file(casted_message)+ assert len(result) == 1+ assert result[0]["role"] == "user"+ # Check that content is transformed correctly+ assert isinstance(result[0]["content"], list)+ assert len(result[0]["content"]) == 3 # Text + 2 files+ # Check that file types are preserved+ assert result[0]["content"][1]["type"] == "file"+ assert result[0]["content"][2]["type"] == "file"+ # Check that file_ids are modified to match Mistral's expected format+ assert result[0]["content"][1]["file_id"] == "file-12345" # type: ignore+ assert result[0]["content"][2]["file_id"] == "file-67890" # type: ignore\ No newline at end of file