Skip to content

Commit 6412c75

Browse files
authored
fix: Improve error handling in task creation (#294)
# Description This update improves the robustness of the `new_task` function by adding explicit error handling for invalid `Message` objects. Previously, `new_task` did not validate its input, which could lead to unexpected `TypeError` or `ValueError` exceptions when a malformed `Message` was passed. This change introduces checks to ensure that a `Message` has a valid `role` and a non-empty `parts` list before a `Task` is created. Additionally, this update includes corresponding unit tests to verify the new error handling and ensures that the correct exceptions are raised for invalid inputs.
1 parent e781ced commit 6412c75

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/a2a/utils/task.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,16 @@ def new_task(request: Message) -> Task:
1515
1616
Returns:
1717
A new `Task` object initialized with 'submitted' status and the input message in history.
18+
19+
Raises:
20+
TypeError: If the message role is None.
21+
ValueError: If the message parts are empty.
1822
"""
23+
if not request.role:
24+
raise TypeError('Message role cannot be None')
25+
if not request.parts:
26+
raise ValueError('Message parts cannot be empty')
27+
1928
return Task(
2029
status=TaskStatus(state=TaskState.submitted),
2130
id=(request.taskId if request.taskId else str(uuid.uuid4())),

tests/utils/test_task.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,25 @@ def test_completed_task_uses_provided_history(self):
113113
)
114114
self.assertEqual(task.history, history)
115115

116+
def test_new_task_invalid_message_empty_parts(self):
117+
with self.assertRaises(ValueError):
118+
new_task(
119+
Message(
120+
role=Role.user,
121+
parts=[],
122+
messageId=str(uuid.uuid4()),
123+
)
124+
)
125+
126+
def test_new_task_invalid_message_none_role(self):
127+
with self.assertRaises(TypeError):
128+
msg = Message.model_construct(
129+
role=None,
130+
parts=[Part(root=TextPart(text='test message'))],
131+
messageId=str(uuid.uuid4()),
132+
)
133+
new_task(msg)
134+
116135

117136
if __name__ == '__main__':
118137
unittest.main()

0 commit comments

Comments
 (0)