diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py index d67b659fe37..a9d91c41d5f 100644 --- a/litellm/litellm_core_utils/prompt_templates/common_utils.py +++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py @@ -87,7 +87,13 @@ def handle_messages_with_content_list_to_str_conversion( """ for message in messages: texts = convert_content_list_to_str(message=message) - if texts: + content = message.get("content") + is_text_only_list = ( + isinstance(content, list) + and bool(content) + and all(isinstance(part, dict) and part.get("type") == "text" for part in content) + ) + if texts or is_text_only_list: message["content"] = texts return messages diff --git a/tests/unit/llms/moonshot/test_moonshot_chat_transformation.py b/tests/unit/llms/moonshot/test_moonshot_chat_transformation.py index 4e7a2931cda..b29fcb3b732 100644 --- a/tests/unit/llms/moonshot/test_moonshot_chat_transformation.py +++ b/tests/unit/llms/moonshot/test_moonshot_chat_transformation.py @@ -7,7 +7,6 @@ Moonshot AI is an OpenAI-compatible provider with minor customizations. from unittest.mock import patch - import pytest import litellm @@ -433,6 +432,48 @@ class TestMoonshotConfig: assert isinstance(result["messages"][0]["content"], str) assert result["messages"][0]["content"] == "Hello, how are you?" + def test_transform_messages_flattens_empty_text_for_tool_call(self): + """Moonshot accepts an empty string, but rejects an empty text part.""" + config = MoonshotChatConfig() + messages = [ + { + "role": "assistant", + "content": [{"type": "text", "text": ""}], + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": {"name": "foo", "arguments": "{}"}, + } + ], + } + ] + + result = config.transform_request( + model="moonshot-v1-8k", + messages=messages, + optional_params={}, + litellm_params={}, + headers={}, + ) + + assert result["messages"][0]["content"] == "" + + def test_transform_messages_preserves_empty_content_list(self): + """An empty list has no text parts to flatten.""" + config = MoonshotChatConfig() + messages = [{"role": "assistant", "content": [], "tool_calls": []}] + + result = config.transform_request( + model="moonshot-v1-8k", + messages=messages, + optional_params={}, + litellm_params={}, + headers={}, + ) + + assert result["messages"][0]["content"] == [] + # ------------------------------------------------------------------ # # Tests for fill_reasoning_content # # ------------------------------------------------------------------ #