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 ensure_alternating_roles for correct order
Sameer Kankuteb9266bb3b9e6
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.pyindex a5d6bc936bb..8791c769af9 100644--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py@@ -269,35 +269,56 @@ def _insert_user_continue_message(2. Final assistant message3. Consecutive assistant messages- Only inserts messages between consecutive assistant messages,- ignoring all other role types.+ Skips tool messages and assistant messages with tool calls in the+ alternation check, matching strict templates like llama.cpp."""if not messages:return messages+ def _counts_for_alternation(message: AllMessageValues) -> bool:+ role = message.get("role")+ if role == "user":+ return True+ if role == "assistant":+ return not bool(message.get("tool_calls"))+ return False+result_messages = messages.copy() # Don't modify the input listcontinue_message = user_continue_message or DEFAULT_USER_CONTINUE_MESSAGE- # Handle first message if it's an assistant message- if result_messages[0]["role"] == "assistant":+ # Handle first counted message if it's an assistant message+ if (+ result_messages[0]["role"] == "assistant"+ and _counts_for_alternation(result_messages[0])+ ):result_messages.insert(0, continue_message)- # Handle consecutive assistant messages and final message- i = 1 # Start from second message since we handled first message+ # Handle consecutive assistant messages in the counted sequence+ i = 1while i < len(result_messages):curr_message = result_messages[i]- prev_message = result_messages[i - 1]-- # Only check for consecutive assistant messages- # Ignore all other role types- if curr_message["role"] == "assistant" and prev_message["role"] == "assistant":- result_messages.insert(i, continue_message)- i += 2 # Skip over the message we just inserted- else:+ if (+ curr_message["role"] == "assistant"+ and _counts_for_alternation(curr_message)+ ):+ j = i - 1+ while j >= 0:+ previous_message = result_messages[j]+ if _counts_for_alternation(previous_message):+ if previous_message["role"] == "assistant":+ result_messages.insert(i, continue_message)+ i += 2+ break+ j -= 1+ if i < len(result_messages):i += 1# Handle final message- if result_messages[-1]["role"] == "assistant" and ensure_alternating_roles:+ if (+ result_messages[-1]["role"] == "assistant"+ and _counts_for_alternation(result_messages[-1])+ and ensure_alternating_roles+ ):result_messages.append(continue_message)return result_messages@@ -310,6 +331,8 @@ def _insert_assistant_continue_message() -> List[AllMessageValues]:"""Add assistant continuation messages between consecutive user messages.+ Skips tool messages and assistant messages with tool calls in the+ alternation check, matching strict templates like llama.cpp.Args:messages: List of message dictionaries@@ -322,27 +345,73 @@ def _insert_assistant_continue_message(if not ensure_alternating_roles or len(messages) <= 1:return messages+ def _counts_for_alternation(message: AllMessageValues) -> bool:+ role = message.get("role")+ if role == "user":+ return True+ if role == "assistant":+ return not bool(message.get("tool_calls"))+ return False+# Create a new list to store modified messagesmodified_messages: List[AllMessageValues] = []for i, message in enumerate(messages):modified_messages.append(message)- # Check if we need to insert an assistant message- if (- i < len(messages) - 1 # Not the last message- and message.get("role") == "user" # Current is user- and messages[i + 1].get("role") == "user"- ): # Next is user- # Insert assistant message- continue_message = (- assistant_continue_message or DEFAULT_ASSISTANT_CONTINUE_MESSAGE- )- modified_messages.append(continue_message)+ if message.get("role") == "user" and _counts_for_alternation(message):+ next_counted_index = i + 1+ while next_counted_index < len(messages) and not _counts_for_alternation(+ messages[next_counted_index]+ ):+ next_counted_index += 1++ if (+ next_counted_index < len(messages)+ and messages[next_counted_index].get("role") == "user"+ ):+ continue_message = (+ assistant_continue_message or DEFAULT_ASSISTANT_CONTINUE_MESSAGE+ )+ modified_messages.append(continue_message)return modified_messages+def strip_tool_messages_for_alternating_roles(+ messages: List[AllMessageValues],+) -> List[AllMessageValues]:+ """+ Prepare history for strict user/assistant-only chat templates.++ - Drop tool/function role messages+ - Drop assistant tool-dispatch turns with no content+ - Keep assistant content turns but remove tool metadata fields+ """+ cleaned_messages: List[AllMessageValues] = []++ for message in messages:+ role = message.get("role")+ if role in ("tool", "function"):+ continue++ if role == "assistant":+ assistant_message = message.copy()+ assistant_message.pop("tool_calls", None)+ assistant_message.pop("function_call", None)+ assistant_message.pop("tool_call_id", None)++ if assistant_message.get("content") is None:+ continue++ cleaned_messages.append(assistant_message)+ continue++ cleaned_messages.append(message)++ return cleaned_messages++def get_completion_messages(messages: List[AllMessageValues],assistant_continue_message: Optional[ChatCompletionAssistantMessage],diff --git a/litellm/main.py b/litellm/main.pyindex 81319bc432f..cb5a92caf8d 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -166,6 +166,7 @@ from .litellm_core_utils.fallback_utils import (from .litellm_core_utils.prompt_templates.common_utils import (add_system_prompt_to_messages,get_completion_messages,+ strip_tool_messages_for_alternating_roles,update_messages_with_model_file_ids,)from .litellm_core_utils.prompt_templates.factory import (@@ -1298,6 +1299,9 @@ def completion( # type: ignore # noqa: PLR0915prompt_variables = cast(Optional[dict], kwargs.get("prompt_variables", None))litellm_system_prompt = kwargs.get("litellm_system_prompt", None)### COPY MESSAGES ### - related issue https://github.com/BerriAI/litellm/discussions/4489+ if ensure_alternating_roles:+ messages = strip_tool_messages_for_alternating_roles(messages=messages)+messages = get_completion_messages(messages=messages,ensure_alternating_roles=ensure_alternating_roles or False,diff --git a/tests/llm_translation/test_prompt_factory.py b/tests/llm_translation/test_prompt_factory.pyindex a6dcabe25ef..2eed9fa2129 100644--- a/tests/llm_translation/test_prompt_factory.py+++ b/tests/llm_translation/test_prompt_factory.py@@ -25,6 +25,7 @@ from litellm.litellm_core_utils.prompt_templates.factory import ()from litellm.litellm_core_utils.prompt_templates.common_utils import (get_completion_messages,+ strip_tool_messages_for_alternating_roles,)from litellm.llms.vertex_ai.gemini.transformation import (_gemini_convert_messages_with_history,@@ -775,6 +776,50 @@ def test_ensure_alternating_roles(assert messages == expected_messages+def test_ensure_alternating_roles_with_tool_calls():+ messages = [+ {"role": "user", "content": "What's the weather?"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_123",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"location": "NYC"}',+ },+ }+ ],+ },+ {"role": "tool", "tool_call_id": "call_123", "content": "72F, sunny"},+ {"role": "assistant", "content": "It's 72F and sunny in NYC."},+ {"role": "user", "content": "What about tomorrow?"},+ {"role": "user", "content": "And the day after?"},+ {"role": "user", "content": "What about next week?"},+ ]++ messages = strip_tool_messages_for_alternating_roles(messages)++ transformed_messages = get_completion_messages(+ messages=messages,+ assistant_continue_message=None,+ user_continue_message=None,+ ensure_alternating_roles=True,+ )++ assert transformed_messages == [+ {"role": "user", "content": "What's the weather?"},+ {"role": "assistant", "content": "It's 72F and sunny in NYC."},+ {"role": "user", "content": "What about tomorrow?"},+ {"role": "assistant", "content": "Please continue."},+ {"role": "user", "content": "And the day after?"},+ {"role": "assistant", "content": "Please continue."},+ {"role": "user", "content": "What about next week?"},+ ]++def test_alternating_roles_e2e():from litellm.llms.custom_httpx.http_handler import HTTPHandlerimport json