Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

fix: gracefully terminate the future when executing a task async

Dragos Ciupureanufeec6b440ef8
diff --git a/lib/crewai/src/crewai/task.py b/lib/crewai/src/crewai/task.py
index 85e8dbb17..13d30b564 100644
--- a/lib/crewai/src/crewai/task.py
+++ b/lib/crewai/src/crewai/task.py
@@ -494,8 +494,11 @@ class Task(BaseModel):
future: Future[TaskOutput],
) -> None:
"""Execute the task asynchronously with context handling."""
- result = self._execute_core(agent, context, tools)
- future.set_result(result)
+ try:
+ result = self._execute_core(agent, context, tools)
+ future.set_result(result)
+ except Exception as e:
+ future.set_exception(e)
async def aexecute_sync(
self,
diff --git a/lib/crewai/tests/test_task.py b/lib/crewai/tests/test_task.py
index 41c14cb87..9a0010d89 100644
--- a/lib/crewai/tests/test_task.py
+++ b/lib/crewai/tests/test_task.py
@@ -1727,3 +1727,24 @@ def test_task_output_includes_messages():
assert hasattr(task2_output, "messages")
assert isinstance(task2_output.messages, list)
assert len(task2_output.messages) > 0
+
+
+def test_async_execution_fails():
+ researcher = Agent(
+ role="Researcher",
+ goal="Make the best research and analysis on content about AI and AI agents",
+ backstory="You're an expert researcher, specialized in technology, software engineering, AI and startups. You work as a freelancer and is now working on doing research and analysis for a new customer.",
+ allow_delegation=False,
+ )
+
+ task = Task(
+ description="Give me a list of 5 interesting ideas to explore for na article, what makes them unique and interesting.",
+ expected_output="Bullet point list of 5 interesting ideas.",
+ async_execution=True,
+ agent=researcher,
+ )
+
+ with patch.object(Task, "_execute_core", side_effect=RuntimeError("boom!")):
+ with pytest.raises(RuntimeError, match="boom!"):
+ execution = task.execute_async(agent=researcher)
+ execution.result()