Skip to content

Commit 51d79bf

Browse files
committed
fix: support assistant role in message conversion
- The _Converter.items_to_messages method was incorrectly rejecting 'assistant' as a valid role in conversation messages, causing runtime errors when processing standard chat completion message formats. - This fix enables proper handling of complete conversation contexts that include both user and assistant messages.
1 parent c8f3cdd commit 51d79bf

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/agents/models/openai_chatcompletions.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,13 @@ def ensure_assistant_message() -> ChatCompletionAssistantMessageParam:
808808
"content": cls.extract_text_content(content),
809809
}
810810
result.append(msg_developer)
811+
elif role == "assistant":
812+
flush_assistant_message()
813+
msg_assistant: ChatCompletionAssistantMessageParam = {
814+
"role": "assistant",
815+
"content": cls.extract_text_content(content),
816+
}
817+
result.append(msg_assistant)
811818
else:
812819
raise UserError(f"Unexpected role in easy_input_message: {role}")
813820

tests/test_openai_chatcompletions_converter.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,3 +393,35 @@ def test_unknown_object_errors():
393393
with pytest.raises(UserError, match="Unhandled item type or structure"):
394394
# Purposely ignore the type error
395395
_Converter.items_to_messages([TestObject()]) # type: ignore
396+
397+
398+
def test_assistant_messages_in_history():
399+
"""
400+
Test that assistant messages are added to the history.
401+
"""
402+
messages = _Converter.items_to_messages(
403+
[
404+
{
405+
"role": "user",
406+
"content": "Hello",
407+
},
408+
{
409+
"role": "assistant",
410+
"content": "Hello?",
411+
},
412+
{
413+
"role": "user",
414+
"content": "What was my Name?",
415+
},
416+
]
417+
)
418+
419+
# OUTPUT is [{'role': 'user', 'content': 'Hello'}, {'role': 'assistant', 'content': 'Hello?'}, {'role': 'user', 'content': 'What was my Name?'}]
420+
assert messages == [{'role': 'user', 'content': 'Hello'}, {'role': 'assistant', 'content': 'Hello?'}, {'role': 'user', 'content': 'What was my Name?'}]
421+
assert len(messages) == 3
422+
assert messages[0]["role"] == "user"
423+
assert messages[0]["content"] == "Hello"
424+
assert messages[1]["role"] == "assistant"
425+
assert messages[1]["content"] == "Hello?"
426+
assert messages[2]["role"] == "user"
427+
assert messages[2]["content"] == "What was my Name?"

0 commit comments

Comments
 (0)