From 0847b459d1a3d52ddd7df65bafb3c7144106e809 Mon Sep 17 00:00:00 2001 From: Evan David <57571858+evandavid1@users.noreply.github.com> Date: Wed, 25 Sep 2024 08:11:25 -0700 Subject: [PATCH] Fix role mapping in GPTAssistantAgent for OpenAI API compatibility (#3555) Co-authored-by: Evan David Co-authored-by: Jack Gerrits --- .../agentchat/contrib/gpt_assistant_agent.py | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/autogen/agentchat/contrib/gpt_assistant_agent.py b/autogen/agentchat/contrib/gpt_assistant_agent.py index 0dcad27b16d5..244f5ed81894 100644 --- a/autogen/agentchat/contrib/gpt_assistant_agent.py +++ b/autogen/agentchat/contrib/gpt_assistant_agent.py @@ -209,10 +209,12 @@ def _invoke_assistant( for message in pending_messages: if message["content"].strip() == "": continue + # Convert message roles to 'user' or 'assistant', by calling _map_role_for_api, to comply with OpenAI API spec + api_role = self._map_role_for_api(message["role"]) self._openai_client.beta.threads.messages.create( thread_id=assistant_thread.id, content=message["content"], - role=message["role"], + role=api_role, ) # Create a new run to get responses from the assistant @@ -240,6 +242,28 @@ def _invoke_assistant( self._unread_index[sender] = len(self._oai_messages[sender]) + 1 return True, response + def _map_role_for_api(self, role: str) -> str: + """ + Maps internal message roles to the roles expected by the OpenAI Assistant API. + + Args: + role (str): The role from the internal message. + + Returns: + str: The mapped role suitable for the API. + """ + if role in ["function", "tool"]: + return "assistant" + elif role == "system": + return "system" + elif role == "user": + return "user" + elif role == "assistant": + return "assistant" + else: + # Default to 'assistant' for any other roles not recognized by the API + return "assistant" + def _get_run_response(self, thread, run): """ Waits for and processes the response of a run from the OpenAI assistant.