Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix role mapping in GPTAssistantAgent for OpenAI API compatibility #3555

Merged
merged 3 commits into from
Sep 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion autogen/agentchat/contrib/gpt_assistant_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
Loading