Skip to content

Commit

Permalink
Fix role mapping in GPTAssistantAgent for OpenAI API compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
Evan David committed Sep 29, 2024
1 parent cd64eb3 commit 40db5f4
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions autogen/agentchat/contrib/gpt_assistant_agent.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
# Copyright (c) 2023 - 2024, Owners of https://github.com/autogen-ai
#
# SPDX-License-Identifier: Apache-2.0
#
# Portions derived from https://github.com/microsoft/autogen are under the MIT License.
# SPDX-License-Identifier: MIT
import copy
import json
import logging
Expand Down Expand Up @@ -215,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
Expand Down Expand Up @@ -246,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.
Expand Down

0 comments on commit 40db5f4

Please sign in to comment.