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: handle multiple task outputs correctly in conditional tasks #1937

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
feat: validate at least one non-conditional task and refine task outputs
  • Loading branch information
commit 4b767b25e013698f45f75a0a725083d762cb2647
28 changes: 24 additions & 4 deletions src/crewai/crew.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,23 @@ def validate_context_no_future_tasks(self):
)
return self

@model_validator(mode="after")
def validate_must_have_non_conditional_task(self) -> "Crew":
"""Ensure that a crew has at least one non-conditional task."""
if not self.tasks:
return self # Empty task list is handled by other validators

non_conditional_count = sum(
1 for task in self.tasks if not isinstance(task, ConditionalTask)
)
if non_conditional_count == 0:
raise PydanticCustomError(
"only_conditional_tasks",
"Crew must include at least one non-conditional task.",
{},
)
return self

@property
def key(self) -> str:
source = [agent.key for agent in self.agents] + [
Expand Down Expand Up @@ -905,10 +922,13 @@ def _process_task_result(self, task: Task, output: TaskOutput) -> None:
)

def _create_crew_output(self, task_outputs: List[TaskOutput]) -> CrewOutput:
# Use the last task output as the final output
final_task_output = task_outputs[-1] if task_outputs else None
# Filter out empty task outputs
valid_task_outputs = [t for t in task_outputs if t.raw]

# Use the last valid task output as the final output
final_task_output = valid_task_outputs[-1] if valid_task_outputs else None
if not final_task_output:
raise ValueError("No task outputs available to create crew output.")
raise ValueError("No valid task outputs available to create crew output.")

final_string_output = final_task_output.raw
self._finish_execution(final_string_output)
Expand All @@ -918,7 +938,7 @@ def _create_crew_output(self, task_outputs: List[TaskOutput]) -> CrewOutput:
raw=final_task_output.raw,
pydantic=final_task_output.pydantic,
json_dict=final_task_output.json_dict,
tasks_output=task_outputs, # Use all task outputs directly
tasks_output=valid_task_outputs, # Only include valid task outputs
token_usage=token_usage,
)

Expand Down
Loading