From 421bc9376563ef1a6c05949083a555290161b8c7 Mon Sep 17 00:00:00 2001 From: Mir Adnan ALI Date: Fri, 24 Jan 2025 03:58:08 -0500 Subject: [PATCH 1/2] Ensure alternating roles for deepseek-reasoner --- aider/sendchat.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/aider/sendchat.py b/aider/sendchat.py index 2cf7086aa..5e75ff584 100644 --- a/aider/sendchat.py +++ b/aider/sendchat.py @@ -42,6 +42,38 @@ def sanity_check_messages(messages): return last_non_system_role == "user" +def ensure_alternating_roles(messages): + """ + Ensure messages alternate between 'assistant' and 'user' roles. + Inserts empty messages of the opposite role when consecutive messages of the same role are found. + + Args: + messages: List of message dictionaries with 'role' and 'content' keys. + + Returns: + List of messages with alternating roles. + """ + if not messages: + return messages + + fixed_messages = [] + prev_role = None + + for msg in messages: + current_role = msg['role'] + + # If the current role is the same as the previous, insert an empty message of the opposite role + if current_role == prev_role: + if current_role == 'user': + fixed_messages.append({'role': 'assistant', 'content': ''}) + else: + fixed_messages.append({'role': 'user', 'content': ''}) + + fixed_messages.append(msg) + prev_role = current_role + + return fixed_messages + def send_completion( model_name, messages, @@ -57,6 +89,9 @@ def send_completion( # # + if model_name == 'deepseek/deepseek-reasoner': + messages = ensure_alternating_roles(messages) + kwargs = dict( model=model_name, messages=messages, From 92f6d31f3322c0ea827bffce019c1cf9cf34afe3 Mon Sep 17 00:00:00 2001 From: Mir Adnan ALI Date: Fri, 24 Jan 2025 05:25:21 -0500 Subject: [PATCH 2/2] Updated patch to avoid KeyError on malformed dict --- aider/sendchat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aider/sendchat.py b/aider/sendchat.py index 5e75ff584..837b3b853 100644 --- a/aider/sendchat.py +++ b/aider/sendchat.py @@ -60,7 +60,7 @@ def ensure_alternating_roles(messages): prev_role = None for msg in messages: - current_role = msg['role'] + current_role = msg.get('role') # Get 'role', None if missing # If the current role is the same as the previous, insert an empty message of the opposite role if current_role == prev_role: