Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

enhance: workforce quality check (#3254)

Puzhen Zhang1f0a0b9eec8c
diff --git a/camel/societies/workforce/prompts.py b/camel/societies/workforce/prompts.py
index 172b2e2f3..4ab82a862 100644
--- a/camel/societies/workforce/prompts.py
+++ b/camel/societies/workforce/prompts.py
@@ -293,58 +293,139 @@ Each subtask should be:
- Written without any relative references (e.g., "the previous task").
"""
-FAILURE_ANALYSIS_PROMPT = TextPrompt(
- """You need to analyze a task failure and decide on the best recovery strategy.
-
-**TASK FAILURE DETAILS:**
-Task ID: {task_id}
-Task Content: {task_content}
-Failure Count: {failure_count}/3
-Error Message: {error_message}
-Worker ID: {worker_id}
-Task Depth: {task_depth}
-Additional Info: {additional_info}
-
-**AVAILABLE RECOVERY STRATEGIES:**
-
-1. **RETRY**: Attempt the same task again without changes
- - Use for: Network errors, temporary API issues, random failures
- - Avoid for: Fundamental task misunderstanding, capability gaps
-
-2. **REPLAN**: Modify the task content to address the underlying issue
- - Use for: Unclear requirements, insufficient context, correctable errors
- - Provide: Modified task content that addresses the failure cause
- - **CRITICAL**: The replanned task MUST be a clear, actionable
- instruction for an AI agent, not a question or request for a human.
-
-3. **DECOMPOSE**: Break the task into smaller, more manageable subtasks
- - Use for: Complex tasks, capability mismatches, persistent failures
- - Consider: Whether the task is too complex for a single worker
-
-4. **CREATE_WORKER**: Create a new worker node to handle the task
- - Use for: Fundamental task misunderstanding, capability gaps
-
-**ANALYSIS GUIDELINES:**
-
-- **Connection/Network Errors**: Almost always choose RETRY
-- **Model Processing Errors**: Consider REPLAN if the task can be clarified, otherwise DECOMPOSE
-- **Capability Gaps**: Choose DECOMPOSE to break into simpler parts. If a
- replan can work, ensure the new task is a command for an agent, not a
- request to a user.
-- **Ambiguous Requirements**: Choose REPLAN with clearer instructions
-- **High Failure Count**: Lean towards DECOMPOSE rather than repeated retries
-- **Deep Tasks (depth > 2)**: Prefer RETRY or REPLAN over further
- decomposition
+TASK_ANALYSIS_PROMPT = TextPrompt(
+ """You are analyzing a task to evaluate its quality and determine recovery actions if needed.
+
+**TASK INFORMATION:**
+- Task ID: {task_id}
+- Task Content: {task_content}
+- Task Result: {task_result}
+- Failure Count: {failure_count}
+- Task Depth: {task_depth}
+- Assigned Worker: {assigned_worker}
+
+**ISSUE TYPE: {issue_type}**
+
+{issue_specific_analysis}
+
+**STEP 1: EVALUATE TASK QUALITY**
+
+First, assess whether the task was completed successfully and meets quality standards:
+
+**For Task Failures (with error messages):**
+- The task did not complete successfully
+- An error occurred during execution
+- Quality is automatically insufficient
+- Focus on analyzing the error cause
+
+**For Quality Issues (task completed but needs evaluation):**
+Evaluate the task result based on these criteria:
+1. **Completeness**: Does the result fully address all task requirements?
+2. **Accuracy**: Is the result correct and well-structured?
+3. **Missing Elements**: Are there any missing components or quality issues?
+
+Provide:
+- Quality score (0-100): Objective assessment of result quality
+- Specific issues list: Any problems found in the result
+- Quality sufficient: Boolean indicating if quality meets standards
+
+**STEP 2: DETERMINE RECOVERY STRATEGY (if quality insufficient)**
+
+If the task quality is insufficient, select the best recovery strategy:
+
+**Available Strategies:**
+
+1. **retry** - Retry with the same worker and task content
+ - **Best for**:
+ * Network errors, connection timeouts, temporary API issues
+ * Random failures that are likely temporary
+ * Minor quality issues that may resolve on retry
+ - **Not suitable for**:
+ * Fundamental task misunderstandings
+ * Worker capability gaps
+ * Persistent quality problems
+
+2. **reassign** - Assign to a different worker
+ - **Best for**:
+ * Current worker lacks required skills/expertise
+ * Worker-specific quality issues
+ * Task requires different specialization
+ - **Not suitable for**:
+ * Task description is unclear (use replan instead)
+ * Task is too complex (use decompose instead)
+ - **Note**: Only available for quality issues, not failures
+
+3. **replan** - Modify task content with clearer instructions
+ - **Best for**:
+ * Unclear or ambiguous requirements
+ * Missing context or information
+ * Task description needs improvement
+ - **Requirements**:
+ * Provide modified_task_content with enhanced, clear instructions
+ * Modified task must be actionable for an AI agent
+ * Address the root cause identified in issues
+
+4. **decompose** - Break into smaller, manageable subtasks
+ - **Best for**:
+ * Task is too complex for a single worker
+ * Multiple distinct sub-problems exist
+ * Persistent failures despite retries
+ * Capability mismatches that need specialization
+ - **Consider**:
+ * Task depth (avoid if depth > 2)
+ * Whether subtasks can run in parallel
+
+5. **create_worker** - Create new specialized worker
+ - **Best for**:
+ * No existing worker has required capabilities
+ * Need specialized skills not currently available
+ - **Consider**:
+ * Whether decomposition could work instead
+ * Cost of creating new worker vs alternatives
+ - **Note**: Only available for task failures, not quality issues
+
+**DECISION GUIDELINES:**
+
+**Priority Rules:**
+1. Connection/Network Errors → **retry** (almost always)
+2. Deep Tasks (depth > 2) → Avoid decompose, prefer **retry** or **replan**
+3. Worker Skill Mismatch → **reassign** (quality) or **decompose** (failure)
+4. Unclear Requirements → **replan** with specifics
+5. Task Too Complex → **decompose** into subtasks
**RESPONSE FORMAT:**
-You must return a valid JSON object with these fields:
-- "strategy": one of "retry", "replan", or "decompose"
-- "reasoning": explanation for your choice (1-2 sentences)
-- "modified_task_content": new task content if strategy is "replan", null otherwise
+{response_format}
-**Example Response:**
-{{"strategy": "retry", "reasoning": "The connection error appears to be temporary and network-related, a simple retry should resolve this.", "modified_task_content": null}}
-
-**CRITICAL**: Return ONLY the JSON object. No explanations or text outside the JSON structure.
+**CRITICAL**:
+- Return ONLY a valid JSON object
+- No explanations or text outside the JSON structure
+- Ensure all required fields are included
+- Use null for optional fields when not applicable
"""
)
+
+FAILURE_ANALYSIS_RESPONSE_FORMAT = """JSON format:
+{
+ "reasoning": "explanation (1-2 sentences)",
+ "recovery_strategy": "retry|replan|decompose|create_worker",
+ "modified_task_content": "new content if replan, else null",
+ "issues": ["error1", "error2"]
+}"""
+
+QUALITY_EVALUATION_RESPONSE_FORMAT = """JSON format:
+{
+ "quality_score": 0-100,
+ "reasoning": "explanation (1-2 sentences)",
+ "issues": ["issue1", "issue2"],
+ "recovery_strategy": "retry|reassign|replan|decompose or null",
+ "modified_task_content": "new content if replan, else null"
+}"""
+
+TASK_AGENT_SYSTEM_MESSAGE = """You are an intelligent task management assistant responsible for planning, analyzing, and quality control.
+
+Your responsibilities include:
+1. **Task Decomposition**: Breaking down complex tasks into manageable subtasks that can be executed efficiently and in parallel when possible.
+2. **Failure Analysis**: Analyzing task failures to determine the root cause and recommend appropriate recovery strategies (retry, replan, decompose, or create new worker).
+3. **Quality Evaluation**: Assessing completed task results to ensure they meet quality standards and recommending recovery strategies if quality is insufficient (retry, reassign, replan, or decompose).
+
+You must provide structured, actionable analysis based on the task context, failure history, worker capabilities, and quality criteria. Your decisions directly impact the efficiency and success of the workforce system."""
diff --git a/camel/societies/workforce/structured_output_handler.py b/camel/societies/workforce/structured_output_handler.py
index 914970ea7..48096b8ae 100644
--- a/camel/societies/workforce/structured_output_handler.py
+++ b/camel/societies/workforce/structured_output_handler.py
@@ -19,8 +19,8 @@ from pydantic import BaseModel, ValidationError
from camel.logger import get_logger
from camel.societies.workforce.utils import (
- RecoveryDecision,
RecoveryStrategy,
+ TaskAnalysisResult,
TaskAssignResult,
WorkerConf,
)
@@ -65,9 +65,9 @@ class StructuredOutputHandler:
r'description.*?:\s*"([^"]+)"'
),
],
- 'RecoveryDecision': [
- r'"strategy"\s*:\s*"([^"]+)".*?"reasoning"\s*:\s*"([^"]+)"',
- r'strategy.*?:\s*"([^"]+)".*?reasoning.*?:\s*"([^"]+)"',
+ 'TaskAnalysisResult': [
+ r'"recovery_strategy"\s*:\s*"([^"]+)".*?"reasoning"\s*:\s*"([^"]+)"',
+ r'recovery_strategy.*?:\s*"([^"]+)".*?reasoning.*?:\s*"([^"]+)"',
],
}
@@ -239,12 +239,12 @@ Ensure the JSON is valid and properly formatted.
except (IndexError, AttributeError):
continue
- elif schema_name == 'RecoveryDecision':
+ elif schema_name == 'TaskAnalysisResult':
for pattern in patterns:
match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
if match:
try:
- strategy = match.group(1)
+ recovery_strategy = match.group(1)
reasoning = match.group(2)
# Look for modified_task_content
content_match = re.search(
@@ -252,14 +252,25 @@ Ensure the JSON is valid and properly formatted.
text,
re.IGNORECASE,
)
+ # Look for quality_score (for quality evaluation)
+ score_match = re.search(
+ r'"quality_score"\s*:\s*(\d+)',
+ text,
+ re.IGNORECASE,
+ )
return {
- 'strategy': strategy,
+ 'recovery_strategy': recovery_strategy,
'reasoning': reasoning,
'modified_task_content': (
content_match.group(1)
if content_match
else None
),
+ 'quality_score': (
+ int(score_match.group(1))
+ if score_match
+ else None
+ ),
}
except (IndexError, AttributeError):
continue
@@ -370,21 +381,22 @@ Ensure the JSON is valid and properly formatted.
else:
assignment['dependencies'] = []
- elif schema_name == 'RecoveryDecision':
- # Ensure strategy is valid
- if 'strategy' in fixed_data:
- strategy = fixed_data['strategy'].lower()
+ elif schema_name == 'TaskAnalysisResult':
+ # Ensure recovery_strategy is valid
+ if 'recovery_strategy' in fixed_data:
+ strategy = fixed_data['recovery_strategy'].lower()
valid_strategies = [
'retry',
'replan',
'decompose',
'create_worker',
+ 'reassign',
]
if strategy not in valid_strategies:
# Try to match partial
for valid in valid_strategies:
if valid.startswith(strategy) or strategy in valid:
- fixed_data['strategy'] = valid
+ fixed_data['recovery_strategy'] = valid
break
return fixed_data
@@ -410,10 +422,10 @@ Ensure the JSON is valid and properly formatted.
sys_msg="You are a helpful assistant.",
description="A general-purpose worker",
)
- elif schema_name == 'RecoveryDecision':
- return RecoveryDecision(
- strategy=RecoveryStrategy.RETRY,
+ elif schema_name == 'TaskAnalysisResult':
+ return TaskAnalysisResult(
reasoning="Unable to parse response, defaulting to retry",
+ recovery_strategy=RecoveryStrategy.RETRY,
modified_task_content=None,
)
else:
@@ -482,11 +494,11 @@ Ensure the JSON is valid and properly formatted.
description=f"Fallback worker for task: {task_content}...",
)
- elif schema_name == 'RecoveryDecision':
+ elif schema_name == 'TaskAnalysisResult':
# Default to retry strategy
- return RecoveryDecision(
- strategy=RecoveryStrategy.RETRY,
+ return TaskAnalysisResult(
reasoning=f"Fallback decision due to: {error_message}",
+ recovery_strategy=RecoveryStrategy.RETRY,
modified_task_content=None,
)
diff --git a/camel/societies/workforce/utils.py b/camel/societies/workforce/utils.py
index 388801246..c5231af66 100644
--- a/camel/societies/workforce/utils.py
+++ b/camel/societies/workforce/utils.py
@@ -42,6 +42,36 @@ class TaskResult(BaseModel):
)
+class QualityEvaluation(BaseModel):
+ r"""Quality evaluation result for a completed task.
+
+ .. deprecated::
+ Use :class:`TaskAnalysisResult` instead. This class is kept for
+ backward compatibility.
+ """
+
+ quality_sufficient: bool = Field(
+ description="Whether the task result meets quality standards."
+ )
+ quality_score: int = Field(
+ description="Quality score from 0 to 100.", ge=0, le=100
+ )
+ issues: List[str] = Field(
+ default_factory=list,
+ description="List of quality issues found in the result.",
+ )
+ recovery_strategy: Optional[str] = Field(
+ default=None,
+ description="Recommended recovery strategy if quality is "
+ "insufficient: "
+ "'retry', 'reassign', 'replan', or 'decompose'.",
+ )
+ modified_task_content: Optional[str] = Field(
+ default=None,
+ description="Modified task content for replan strategy.",
+ )
+
+
class TaskAssignment(BaseModel):
r"""An individual task assignment within a batch."""
@@ -52,7 +82,8 @@ class TaskAssignment(BaseModel):
dependencies: List[str] = Field(
default_factory=list,
description="List of task IDs that must complete before this task. "
- "This is critical for the task decomposition and execution.",
+ "This is critical for the task decomposition and "
+ "execution.",
)
# Allow LLMs to output dependencies as a comma-separated string or empty
@@ -60,7 +91,8 @@ class TaskAssignment(BaseModel):
# downstream logic does not break with validation errors.
@staticmethod
def _split_and_strip(dep_str: str) -> List[str]:
- r"""Utility to split a comma separated string and strip whitespace."""
+ r"""Utility to split a comma separated string and strip
+ whitespace."""
return [d.strip() for d in dep_str.split(',') if d.strip()]
@field_validator("dependencies", mode="before")
@@ -74,7 +106,8 @@ class TaskAssignment(BaseModel):
class TaskAssignResult(BaseModel):
- r"""The result of task assignment for both single and batch assignments."""
+ r"""The result of task assignment for both single and batch
+ assignments."""
assignments: List[TaskAssignment] = Field(
description="List of task assignments."
@@ -88,6 +121,7 @@ class RecoveryStrategy(str, Enum):
REPLAN = "replan"
DECOMPOSE = "decompose"
CREATE_WORKER = "create_worker"
+ REASSIGN = "reassign"
def __str__(self):
return self.value
@@ -116,17 +150,75 @@ class FailureContext(BaseModel):
)
-class RecoveryDecision(BaseModel):
- r"""Decision on how to recover from a task failure."""
+class TaskAnalysisResult(BaseModel):
+ r"""Unified result for task failure analysis and quality evaluation.
+
+ This model combines both failure recovery decisions and quality evaluation
+ results into a single structure. For failure analysis, only the recovery
+ strategy and reasoning fields are populated. For quality evaluation, all
+ fields including quality_score and issues are populated.
+ """
+
+ # Common fields - always populated
+ reasoning: str = Field(
+ description="Explanation for the analysis result or recovery "
+ "decision"
+ )
- strategy: RecoveryStrategy = Field(
- description="The chosen recovery strategy"
+ recovery_strategy: Optional[RecoveryStrategy] = Field(
+ default=None,
+ description="Recommended recovery strategy: 'retry', 'replan', "
+ "'decompose', 'create_worker', or 'reassign'. None indicates no "
+ "recovery needed (quality sufficient).",
)
- reasoning: str = Field(description="Explanation for the chosen strategy")
+
modified_task_content: Optional[str] = Field(
- default=None, description="Modified task content if strategy is REPLAN"
+ default=None,
+ description="Modified task content if strategy requires replan",
)
+ # Quality-specific fields - populated only for quality evaluation
+ quality_score: Optional[int] = Field(
+ default=None,
+ description="Quality score from 0 to 100 (only for quality "
+ "evaluation). "
+ "None indicates this is a failure analysis, "
+ "not quality evaluation.",
+ ge=0,
+ le=100,
+ )
+
+ issues: List[str] = Field(
+ default_factory=list,
+ description="List of issues found. For failures: error details. "
+ "For quality evaluation: quality issues.",
+ )
+
+ @property
+ def is_quality_evaluation(self) -> bool:
+ r"""Check if this is a quality evaluation result.
+
+ Returns:
+ bool: True if this is a quality evaluation (has quality_score),
+ False if this is a failure analysis.
+ """
+ return self.quality_score is not None
+
+ @property
+ def quality_sufficient(self) -> bool:
+ r"""For quality evaluations, check if quality meets standards.
+
+ Returns:
+ bool: True if quality is sufficient (score >= 70 and no recovery
+ strategy recommended), False otherwise. Always False for
+ failure analysis results.
+ """
+ return (
+ self.quality_score is not None
+ and self.quality_score >= 70
+ and self.recovery_strategy is None
+ )
+
def check_if_running(
running: bool,
@@ -178,7 +270,7 @@ def check_if_running(
if retries < max_retries:
logger.warning(
f"{error_msg} Retrying in {retry_delay}s... "
- f"(Attempt {retries+1}/{max_retries})"
+ f"(Attempt {retries + 1}/{max_retries})"
)
time.sleep(retry_delay)
retries += 1
@@ -200,7 +292,7 @@ def check_if_running(
logger.warning(
f"Exception in {func.__name__}: {e}. "
f"Retrying in {retry_delay}s... "
- f"(Attempt {retries+1}/{max_retries})"
+ f"(Attempt {retries + 1}/{max_retries})"
)
time.sleep(retry_delay)
retries += 1
@@ -218,7 +310,8 @@ def check_if_running(
# This should not be reached, but just in case
if handle_exceptions:
logger.error(
- f"Unexpected failure in {func.__name__}: {last_exception}"
+ f"Unexpected failure in {func.__name__}: "
+ f"{last_exception}"
)
return None
else:
diff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.py
index ba9a872e5..ccfd7dff8 100644
--- a/camel/societies/workforce/workforce.py
+++ b/camel/societies/workforce/workforce.py
@@ -50,7 +50,10 @@ from camel.societies.workforce.base import BaseNode
from camel.societies.workforce.prompts import (
ASSIGN_TASK_PROMPT,
CREATE_NODE_PROMPT,
- FAILURE_ANALYSIS_PROMPT,
+ FAILURE_ANALYSIS_RESPONSE_FORMAT,
+ QUALITY_EVALUATION_RESPONSE_FORMAT,
+ TASK_AGENT_SYSTEM_MESSAGE,
+ TASK_ANALYSIS_PROMPT,
TASK_DECOMPOSE_PROMPT,
)
from camel.societies.workforce.role_playing_worker import RolePlayingWorker
@@ -62,9 +65,8 @@ from camel.societies.workforce.structured_output_handler import (
)
from camel.societies.workforce.task_channel import TaskChannel
from camel.societies.workforce.utils import (
- FailureContext,
- RecoveryDecision,
RecoveryStrategy,
+ TaskAnalysisResult,
TaskAssignment,
TaskAssignResult,
WorkerConf,
@@ -367,7 +369,7 @@ class Workforce(BaseNode):
# Set up task agent with default system message and required tools
task_sys_msg = BaseMessage.make_assistant_message(
role_name="Task Planner",
- content="You are going to handle tasks.",
+ content=TASK_AGENT_SYSTEM_MESSAGE,
)
task_planning_tools = TaskPlanningToolkit().get_tools()
@@ -804,76 +806,124 @@ class Workforce(BaseNode):
self._update_dependencies_for_decomposition(task, subtasks)
return subtasks
- def _analyze_failure(
- self, task: Task, error_message: str
- ) -> RecoveryDecision:
- r"""Analyze a task failure and decide on the best recovery strategy.
+ def _analyze_task(
+ self,
+ task: Task,
+ *,
+ for_failure: bool,
+ error_message: Optional[str] = None,
+ ) -> TaskAnalysisResult:
+ r"""Unified task analysis for both failures and quality evaluation.
+
+ This method consolidates the logic for analyzing task failures and
+ evaluating task quality, using the unified TASK_ANALYSIS_PROMPT.
Args:
- task (Task): The failed task
- error_message (str): The error message from the failure
+ task (Task): The task to analyze
+ for_failure (bool): True for failure analysis, False for quality
+ evaluation
+ error_message (Optional[str]): Error message, required when
+ for_failure=True
Returns:
- RecoveryDecision: The decided recovery strategy with reasoning
+ TaskAnalysisResult: Unified analysis result with recovery strategy
+ and optional quality metrics
+
+ Raises:
+ ValueError: If for_failure=True but error_message is None
"""
- # First, do a quick smart analysis based on error patterns
- error_msg_lower = error_message.lower()
- if any(
- keyword in error_msg_lower
- for keyword in [
- 'connection',
- 'network',
- 'server disconnected',
- 'timeout',
- 'apiconnectionerror',
+ # Validate required parameters
+ if for_failure and error_message is None:
+ raise ValueError("error_message is required when for_failure=True")
+
+ # Determine task result and issue-specific analysis based on context
+ if for_failure:
+ task_result = "N/A (task failed)"
+ issue_type = "Task Failure"
+ issue_analysis = f"**Error Message:** {error_message}"
+ response_format = FAILURE_ANALYSIS_RESPONSE_FORMAT
+ result_schema = TaskAnalysisResult
+ fallback_values: Dict[str, Any] = {
+ "reasoning": "Defaulting to retry due to parsing error",
+ "recovery_strategy": RecoveryStrategy.RETRY,
+ "modified_task_content": None,
+ "issues": [error_message] if error_message else [],
+ }
+ examples: List[Dict[str, Any]] = [
+ {
+ "reasoning": "Temporary network error, worth retrying",
+ "recovery_strategy": "retry",
+ "modified_task_content": None,
+ "issues": ["Network timeout"],
+ }
]
- ):
- return RecoveryDecision(
- strategy=RecoveryStrategy.RETRY,
- reasoning="Network/connection error detected, retrying task",
- modified_task_content=None,
+ else:
+ # Quality evaluation
+ task_result = task.result or "No result available"
+ issue_type = "Quality Evaluation"
+ issue_analysis = (
+ "Provide a quality score (0-100) and list any specific "
+ "issues found."
)
+ response_format = QUALITY_EVALUATION_RESPONSE_FORMAT
+ result_schema = TaskAnalysisResult
+ fallback_values = {
+ "reasoning": (
+ "Defaulting to acceptable quality due to parsing error"
+ ),
+ "issues": [],
+ "recovery_strategy": None,
+ "modified_task_content": None,
+ "quality_score": 80,
+ }
+ examples = [
+ {
+ "reasoning": (
+ "Excellent implementation with comprehensive tests"
+ ),
+ "issues": [],
+ "recovery_strategy": None,
+ "modified_task_content": None,
+ "quality_score": 98,
+ },
+ {
+ "reasoning": (
+ "Implementation incomplete with missing features"
+ ),
+ "issues": [
+ "Incomplete implementation",
+ "Missing error handling",
+ ],
+ "recovery_strategy": "replan",
+ "modified_task_content": (
+ "Previous attempt was incomplete. "
+ "Please implement with: 1) Full feature "
+ "coverage, 2) Proper error handling"
+ ),
+ "quality_score": 45,
+ },
+ ]
- # Create failure context
- failure_context = FailureContext(
+ # Format the unified analysis prompt
+ analysis_prompt = TASK_ANALYSIS_PROMPT.format(
task_id=task.id,
task_content=task.content,
+ task_result=task_result,
failure_count=task.failure_count,
- error_message=error_message,
- worker_id=task.assigned_worker_id,
task_depth=task.get_depth(),
- additional_info=str(task.additional_info)
- if task.additional_info
- else None,
- )
-
- # Format the analysis prompt
- analysis_prompt = FAILURE_ANALYSIS_PROMPT.format(
- task_id=failure_context.task_id,
- task_content=failure_context.task_content,
- failure_count=failure_context.failure_count,
- error_message=failure_context.error_message,
- worker_id=failure_context.worker_id or "unknown",
- task_depth=failure_context.task_depth,
- additional_info=failure_context.additional_info or "None",
+ assigned_worker=task.assigned_worker_id or "unknown",
+ issue_type=issue_type,
+ issue_specific_analysis=issue_analysis,
+ response_format=response_format,
)
try:
- # Check if we should use structured handler
if self.use_structured_output_handler:
- # Use structured handler
enhanced_prompt = (
self.structured_handler.generate_structured_prompt(
base_prompt=analysis_prompt,
- schema=RecoveryDecision,
- examples=[
- {
- "strategy": "RETRY",
- "reasoning": "Temporary network error, "
- "worth retrying",
- "modified_task_content": None,
- }
- ],
+ schema=result_schema,
+ examples=examples,
)
)
@@ -882,43 +932,220 @@ class Workforce(BaseNode):
result = self.structured_handler.parse_structured_response(
response.msg.content if response.msg else "",
- schema=RecoveryDecision,
- fallback_values={
- "strategy": RecoveryStrategy.RETRY,
- "reasoning": "Defaulting to retry due to parsing "
- "issues",
- "modified_task_content": None,
- },
+ schema=result_schema,
+ fallback_values=fallback_values,
)
- # Ensure we return a RecoveryDecision instance
- if isinstance(result, RecoveryDecision):
+
+ if isinstance(result, TaskAnalysisResult):
return result
elif isinstance(result, dict):
- return RecoveryDecision(**result)
+ return result_schema(**result)
else:
- return RecoveryDecision(
- strategy=RecoveryStrategy.RETRY,
- reasoning="Failed to parse recovery decision",
- modified_task_content=None,
- )
+ # Fallback based on context
+ return TaskAnalysisResult(**fallback_values)
else:
- # Use existing native structured output code
self.task_agent.reset()
response = self.task_agent.step(
- analysis_prompt, response_format=RecoveryDecision
+ analysis_prompt, response_format=result_schema
)
return response.msg.parsed
except Exception as e:
logger.warning(
- f"Error during failure analysis: {e}, defaulting to RETRY"
+ f"Error during task analysis "
+ f"({'failure' if for_failure else 'quality'}): {e}, "
+ f"using fallback"
)
- return RecoveryDecision(
- strategy=RecoveryStrategy.RETRY,
- reasoning=f"Analysis failed due to error: {e!s}, "
- f"defaulting to retry",
- modified_task_content=None,
+ return TaskAnalysisResult(**fallback_values)
+
+ async def _apply_recovery_strategy(
+ self,
+ task: Task,
+ recovery_decision: TaskAnalysisResult,
+ ) -> bool:
+ r"""Apply the recovery strategy from a task analysis result.
+
+ This method centralizes the recovery logic for both execution failures
+ and quality-based failures.
+
+ Args:
+ task (Task): The task that needs recovery
+ recovery_decision (TaskAnalysisResult): The analysis result with
+ recovery strategy
+
+ Returns:
+ bool: True if workforce should halt (e.g., decompose needs
+ different handling), False otherwise
+ """
+ strategy = (
+ recovery_decision.recovery_strategy or RecoveryStrategy.RETRY
+ )
+ action_taken = ""
+
+ try:
+ if strategy == RecoveryStrategy.RETRY:
+ # Simply retry the task by reposting it to the same worker
+ # Check both _assignees dict and task.assigned_worker_id
+ assignee_id = (
+ self._assignees.get(task.id) or task.assigned_worker_id
+ )
+
+ if assignee_id:
+ # Retry with the same worker - no coordinator call needed
+ await self._post_task(task, assignee_id)
+ action_taken = f"retried with same worker {assignee_id}"
+ logger.info(
+ f"Task {task.id} retrying with same worker "
+ f"{assignee_id} (no coordinator call)"
+ )
+ else:
+ # No previous assignment exists - find a new assignee
+ logger.info(
+ f"Task {task.id} has no previous assignee, "
+ f"calling coordinator"
+ )
+ batch_result = await self._find_assignee([task])
+ assignment = batch_result.assignments[0]
+ self._assignees[task.id] = assignment.assignee_id
+ await self._post_task(task, assignment.assignee_id)
+ action_taken = (
+ f"retried with new worker {assignment.assignee_id}"
+ )
+
+ elif strategy == RecoveryStrategy.REPLAN:
+ # Modify the task content and retry
+ if recovery_decision.modified_task_content:
+ task.content = recovery_decision.modified_task_content
+ logger.info(f"Task {task.id} content modified for replan")
+
+ # Repost the modified task
+ if task.id in self._assignees:
+ assignee_id = self._assignees[task.id]
+ await self._post_task(task, assignee_id)
+ action_taken = (
+ f"replanned and retried with worker {assignee_id}"
+ )
+ else:
+ # Find a new assignee for the replanned task
+ batch_result = await self._find_assignee([task])
+ assignment = batch_result.assignments[0]
+ self._assignees[task.id] = assignment.assignee_id
+ await self._post_task(task, assignment.assignee_id)
+ action_taken = (
+ f"replanned and assigned to "
+ f"worker {assignment.assignee_id}"
+ )
+
+ elif strategy == RecoveryStrategy.REASSIGN:
+ # Reassign to a different worker
+ old_worker = task.assigned_worker_id
+ logger.info(
+ f"Task {task.id} will be reassigned from worker "
+ f"{old_worker}"
+ )
+
+ # Find a different worker
+ batch_result = await self._find_assignee([task])
+ assignment = batch_result.assignments[0]
+ new_worker = assignment.assignee_id
+
+ # If same worker, force find another
+ if new_worker == old_worker and len(self._children) > 1:
+ logger.info("Same worker selected, finding alternative")
+ # Try to find different worker by adding note to
+ # task content
+ task.content = (
+ f"{task.content}\n\n"
+ f"Note: Previous worker {old_worker} had quality "
+ f"issues. Needs different approach."
+ )
+ batch_result = await self._find_assignee([task])
+ assignment = batch_result.assignments[0]
+ new_worker = assignment.assignee_id
+
+ self._assignees[task.id] = new_worker
+ await self._post_task(task, new_worker)
+ action_taken = f"reassigned from {old_worker} to {new_worker}"
+ logger.info(
+ f"Task {task.id} reassigned from {old_worker} to "
+ f"{new_worker}"
+ )
+
+ elif strategy == RecoveryStrategy.DECOMPOSE:
+ # Decompose the task into subtasks
+ reason = (
+ "failure"
+ if not recovery_decision.is_quality_evaluation
+ else "quality issues"
+ )
+ logger.info(
+ f"Task {task.id} will be decomposed due to {reason}"
+ )
+ subtasks_result = self._decompose_task(task)
+
+ # Handle both streaming and non-streaming results
+ if isinstance(subtasks_result, Generator):
+ subtasks = []
+ for new_tasks in subtasks_result:
+ subtasks.extend(new_tasks)
+ else:
+ subtasks = subtasks_result
+
+ if self.metrics_logger and subtasks:
+ self.metrics_logger.log_task_decomposed(
+ parent_task_id=task.id,
+ subtask_ids=[st.id for st in subtasks],
+ )
+ for subtask in subtasks:
+ self.metrics_logger.log_task_created(
+ task_id=subtask.id,
+ description=subtask.content,
+ parent_task_id=task.id,
+ task_type=subtask.type,
+ metadata=subtask.additional_info,
+ )
+
+ # Insert subtasks at the head of the queue
+ self._pending_tasks.extendleft(reversed(subtasks))
+ await self._post_ready_tasks()
+ action_taken = f"decomposed into {len(subtasks)} subtasks"
+
+ logger.info(
+ f"Task {task.id} decomposed into {len(subtasks)} subtasks"
+ )
+
+ # Sync shared memory after task decomposition
+ if self.share_memory:
+ logger.info(
+ f"Syncing shared memory after task {task.id} "
+ f"decomposition"
+ )
+ self._sync_shared_memory()
+
+ # For decompose, we return early with special handling
+ return True
+
+ elif strategy == RecoveryStrategy.CREATE_WORKER:
+ assignee = await self._create_worker_node_for_task(task)
+ await self._post_task(task, assignee.node_id)
+ action_taken = (
+ f"created new worker {assignee.node_id} and assigned "
+ f"task {task.id} to it"
+ )
+
+ except Exception as e:
+ logger.error(
+ f"Recovery strategy {strategy} failed for task {task.id}: {e}",
+ exc_info=True,
)
+ raise
+
+ logger.debug(
+ f"Task {task.id} recovery: {action_taken}. "
+ f"Strategy: {strategy.value}"
+ )
+
+ return False
# Human intervention methods
async def _async_pause(self) -> None:
@@ -2882,20 +3109,119 @@ class Workforce(BaseNode):
f"Assigning task: {e}"
)
dependencies = self._task_dependencies[task.id]
- # Check if all dependencies for this task are in the completed
- # set and their state is DONE
- if all(
- dep_id in completed_tasks_info
- and completed_tasks_info[dep_id] == TaskState.DONE
- for dep_id in dependencies
- ):
- assignee_id = self._assignees[task.id]
- logger.debug(
- f"Posting task {task.id} to assignee {assignee_id}. "
- f"Dependencies met."
+
+ # Check if all dependencies are in completed state
+ all_deps_completed = all(
+ dep_id in completed_tasks_info for dep_id in dependencies
+ )
+
+ # Only proceed with dependency checks if all deps are completed
+ if all_deps_completed:
+ # Check if all dependencies succeeded (state is DONE)
+ all_deps_done = all(
+ completed_tasks_info[dep_id] == TaskState.DONE
+ for dep_id in dependencies
)
- await self._post_task(task, assignee_id)
- posted_tasks.append(task)
+
+ # Check if any dependency failed
+ any_dep_failed = any(
+ completed_tasks_info[dep_id] == TaskState.FAILED
+ for dep_id in dependencies
+ )
+
+ if all_deps_done:
+ # All dependencies completed successfully - post the
+ # task
+ assignee_id = self._assignees[task.id]
+ logger.debug(
+ f"Posting task {task.id} to "
+ f"assignee {assignee_id}. "
+ f"Dependencies met."
+ )
+ await self._post_task(task, assignee_id)
+ posted_tasks.append(task)
+ elif any_dep_failed:
+ # Check if any failed dependencies can still be retried
+ failed_deps = [
+ dep_id
+ for dep_id in dependencies
+ if completed_tasks_info[dep_id] == TaskState.FAILED
+ ]
+
+ # Check if any failed dependency is still retryable
+ failed_tasks_with_retry_potential = []
+ permanently_failed_deps = []
+
+ for dep_id in failed_deps:
+ # Find the failed dependency task
+ failed_task = next(
+ (
+ t
+ for t in self._completed_tasks
+ if t.id == dep_id
+ ),
+ None,
+ )
+ if (
+ failed_task
+ and failed_task.failure_count
+ < MAX_TASK_RETRIES
+ ):
+ failed_tasks_with_retry_potential.append(
+ dep_id
+ )
+ else:
+ permanently_failed_deps.append(dep_id)
+
+ # Only fail the task if ALL dependencies are
+ # permanently failed
+ if (
+ permanently_failed_deps
+ and not failed_tasks_with_retry_potential
+ ):
+ logger.error(
+ f"Task {task.id} cannot proceed: dependencies "
+ f"{permanently_failed_deps} have "
+ f"permanently failed. "
+ f"Marking task as failed."
+ )
+ task.state = TaskState.FAILED
+ task.result = (
+ f"Task failed due to permanently "
+ f"failed dependencies: "
+ f"{permanently_failed_deps}"
+ )
+
+ # Log the failure to metrics
+ if self.metrics_logger:
+ self.metrics_logger.log_task_failed(
+ task_id=task.id,
+ worker_id=task.assigned_worker_id
+ or "unknown",
+ error_message=task.result,
+ metadata={
+ 'failure_reason': (
+ 'dependency_failure'
+ ),
+ 'failed_dependencies': (
+ permanently_failed_deps
+ ),
+ },
+ )
+
+ self._completed_tasks.append(task)
+ self._cleanup_task_tracking(task.id)
+ posted_tasks.append(task) # Remove from pending
+ else:
+ # Some dependencies may still be retried, keep
+ # task pending
+ logger.debug(
+ f"Task {task.id} waiting: dependencies "
+ f"{failed_tasks_with_retry_potential} "
+ f"failed but may be retried "
+ f"(attempt < {MAX_TASK_RETRIES})"
+ )
+ # else: Not all dependencies completed yet, skip this task
# Step 3: Remove the posted tasks from the pending list
for task in posted_tasks:
@@ -2907,21 +3233,30 @@ class Workforce(BaseNode):
pass
async def _handle_failed_task(self, task: Task) -> bool:
+ r"""Handle a task that failed during execution.
+
+ Args:
+ task (Task): The failed task
+
+ Returns:
+ bool: True if workforce should halt, False otherwise
+ """
task.failure_count += 1
# Determine detailed failure information
- # Use the actual error/result stored in task.result
failure_reason = task.result or "Unknown error"
-
- # Add context about the worker and task
worker_id = task.assigned_worker_id or "unknown"
- worker_info = f" (assigned to worker: {worker_id})"
-
- detailed_error = f"{failure_reason}{worker_info}"
+ detailed_error = f"{failure_reason} (assigned to worker: {worker_id})"
logger.error(
f"Task {task.id} failed (attempt "
- f"{task.failure_count}/3): {detailed_error}"
+ f"{task.failure_count}/{MAX_TASK_RETRIES}): {detailed_error}"
+ )
+
+ print(
+ f"{Fore.RED}❌ Task {task.id} failed "
+ f"(attempt {task.failure_count}/{MAX_TASK_RETRIES}): "
+ f"{failure_reason}{Fore.RESET}"
)
if self.metrics_logger:
@@ -2936,24 +3271,20 @@ class Workforce(BaseNode):
},
)
- # Check for immediate halt conditions - return immediately if we
- # should halt
+ # Check for immediate halt conditions
if task.failure_count >= MAX_TASK_RETRIES:
logger.error(
f"Task {task.id} has exceeded maximum retry attempts "
- f"({MAX_TASK_RETRIES}). Final failure "
- f"reason: {detailed_error}. "
+ f"({MAX_TASK_RETRIES}). Final failure reason: "
+ f"{detailed_error}. "
f"Task content: '{task.content}'"
)
self._cleanup_task_tracking(task.id)
- # Mark task as completed for dependency tracking before halting
self._completed_tasks.append(task)
if task.id in self._assignees:
await self._channel.archive_task(task.id)
return True
- # If too many tasks are failing rapidly, also halt to prevent infinite
- # loops
if len(self._pending_tasks) > MAX_PENDING_TASKS_LIMIT:
logger.error(
f"Too many pending tasks ({len(self._pending_tasks)} > "
@@ -2961,18 +3292,24 @@ class Workforce(BaseNode):
f"explosion. Last failed task: {task.id}"
)
self._cleanup_task_tracking(task.id)
- # Mark task as completed for dependency tracking before halting
self._completed_tasks.append(task)
if task.id in self._assignees:
await self._channel.archive_task(task.id)
return True
# Use intelligent failure analysis to decide recovery strategy
- recovery_decision = self._analyze_failure(task, detailed_error)
+ recovery_decision = self._analyze_task(
+ task, for_failure=True, error_message=detailed_error
+ )
+ strategy_str = (
+ recovery_decision.recovery_strategy.value
+ if recovery_decision.recovery_strategy
+ else "none"
+ )
logger.info(
f"Task {task.id} failure "
- f"analysis: {recovery_decision.strategy.value} - "
+ f"analysis: {strategy_str} - "
f"{recovery_decision.reasoning}"
)
@@ -2981,105 +3318,23 @@ class Workforce(BaseNode):
await self._channel.archive_task(task.id)
self._cleanup_task_tracking(task.id)
+ # Apply recovery strategy
try:
- if recovery_decision.strategy == RecoveryStrategy.RETRY:
- # Simply retry the task by reposting it
- if task.id in self._assignees:
- assignee_id = self._assignees[task.id]
- await self._post_task(task, assignee_id)
- action_taken = f"retried with same worker {assignee_id}"
- else:
- # Find a new assignee and retry
- batch_result = await self._find_assignee([task])
- assignment = batch_result.assignments[0]
- self._assignees[task.id] = assignment.assignee_id
- await self._post_task(task, assignment.assignee_id)
- action_taken = (
- f"retried with new worker {assignment.assignee_id}"
- )
-
- elif recovery_decision.strategy == RecoveryStrategy.REPLAN:
- # Modify the task content and retry
- if recovery_decision.modified_task_content:
- task.content = recovery_decision.modified_task_content
- logger.info(f"Task {task.id} content modified for replan")
-
- # Repost the modified task
- if task.id in self._assignees:
- assignee_id = self._assignees[task.id]
- await self._post_task(task, assignee_id)
- action_taken = (
- f"replanned and retried with worker {assignee_id}"
- )
- else:
- # Find a new assignee for the replanned task
- batch_result = await self._find_assignee([task])
- assignment = batch_result.assignments[0]
- self._assignees[task.id] = assignment.assignee_id
- await self._post_task(task, assignment.assignee_id)
- action_taken = (
- f"replanned and assigned to "
- f"worker {assignment.assignee_id}"
- )
-
- elif recovery_decision.strategy == RecoveryStrategy.DECOMPOSE:
- # Decompose the task into subtasks
- subtasks_result = self._decompose_task(task)
-
- # Handle both streaming and non-streaming results
- if isinstance(subtasks_result, Generator):
- # This is a generator (streaming mode)
- subtasks = []
- for new_tasks in subtasks_result:
- subtasks.extend(new_tasks)
- else:
- # This is a regular list (non-streaming mode)
- subtasks = subtasks_result
- if self.metrics_logger and subtasks:
- self.metrics_logger.log_task_decomposed(
- parent_task_id=task.id,
- subtask_ids=[st.id for st in subtasks],
- )
- for subtask in subtasks:
- self.metrics_logger.log_task_created(
- task_id=subtask.id,
- description=subtask.content,
- parent_task_id=task.id,
- task_type=subtask.type,
- metadata=subtask.additional_info,
- )
- # Insert packets at the head of the queue
- self._pending_tasks.extendleft(reversed(subtasks))
-
- await self._post_ready_tasks()
- action_taken = f"decomposed into {len(subtasks)} subtasks"
-
- logger.debug(
- f"Task {task.id} failed and was {action_taken}. "
- f"Dependencies updated for subtasks."
- )
-
- # Sync shared memory after task decomposition
- if self.share_memory:
- logger.info(
- f"Syncing shared memory after "
- f"task {task.id} decomposition"
- )
- self._sync_shared_memory()
+ is_decompose = await self._apply_recovery_strategy(
+ task, recovery_decision
+ )
- # Check if any pending tasks are now ready to execute
- await self._post_ready_tasks()
+ # For decompose, we handle it specially
+ if is_decompose:
+ # Task was decomposed, add to completed tasks
+ self._completed_tasks.append(task)
return False
- elif recovery_decision.strategy == RecoveryStrategy.CREATE_WORKER:
- assignee = await self._create_worker_node_for_task(task)
- await self._post_task(task, assignee.node_id)
- action_taken = (
- f"created new worker {assignee.node_id} and assigned "
- f"task {task.id} to it"
- )
except Exception as e:
- logger.error(f"Recovery strategy failed for task {task.id}: {e}")
+ logger.error(
+ f"Recovery strategy failed for task {task.id}: {e}",
+ exc_info=True,
+ )
# If max retries reached, halt the workforce
if task.failure_count >= MAX_TASK_RETRIES:
self._completed_tasks.append(task)
@@ -3087,18 +3342,17 @@ class Workforce(BaseNode):
self._completed_tasks.append(task)
return False
+ # Task is being retried - don't add to completed tasks
+ # It will be added when it actually completes or permanently fails
logger.debug(
- f"Task {task.id} failed and was {action_taken}. "
- f"Updating dependency state."
+ f"Task {task.id} is being retried (strategy: "
+ f"{recovery_decision.recovery_strategy}). "
+ f"Not adding to completed tasks until final outcome."
)
- # Mark task as completed for dependency tracking
- self._completed_tasks.append(task)
- # Sync shared memory after task completion to share knowledge
+ # Sync shared memory after task recovery
if self.share_memory:
- logger.info(
- f"Syncing shared memory after task {task.id} completion"
- )
+ logger.info(f"Syncing shared memory after task {task.id} recovery")
self._sync_shared_memory()
# Check if any pending tasks are now ready to execute
@@ -3608,11 +3862,88 @@ class Workforce(BaseNode):
)
continue
else:
- print(
- f"{Fore.CYAN}🎯 Task {returned_task.id} completed "
- f"successfully.{Fore.RESET}"
+ quality_eval = self._analyze_task(
+ returned_task, for_failure=False
)
- await self._handle_completed_task(returned_task)
+
+ if not quality_eval.quality_sufficient:
+ logger.info(
+ f"Task {returned_task.id} quality check: "
+ f"score={quality_eval.quality_score}, "
+ f"issues={quality_eval.issues}, "
+ f"strategy={quality_eval.recovery_strategy}"
+ )
+
+ # Check retry limit before attempting recovery
+ if returned_task.failure_count >= 2:
+ print(
+ f"{Fore.YELLOW}Task {returned_task.id} "
+ f"completed with low quality score: "
+ f"{quality_eval.quality_score} "
+ f"(retry limit reached){Fore.RESET}"
+ )
+ await self._handle_completed_task(
+ returned_task
+ )
+ continue
+
+ # Print visual feedback for quality-failed tasks
+ # with recovery strategy
+ recovery_action = (
+ quality_eval.recovery_strategy.value
+ if quality_eval.recovery_strategy
+ else ""
+ )
+ print(
+ f"{Fore.YELLOW}⚠️ Task {returned_task.id} "
+ f"failed quality check (score: "
+ f"{quality_eval.quality_score}). "
+ f"Issues: {', '.join(quality_eval.issues)}. "
+ f"Recovery: {recovery_action}{Fore.RESET}"
+ )
+
+ # Mark as failed for recovery
+ returned_task.failure_count += 1
+ returned_task.state = TaskState.FAILED
+ returned_task.result = (
+ f"Quality insufficient (score: "
+ f"{quality_eval.quality_score}). "
+ f"Issues: {', '.join(quality_eval.issues)}"
+ )
+
+ # Clean up tracking before attempting recovery
+ if returned_task.id in self._assignees:
+ await self._channel.archive_task(
+ returned_task.id
+ )
+ self._cleanup_task_tracking(returned_task.id)
+
+ # Apply LLM-recommended recovery strategy
+ try:
+ is_decompose = (
+ await self._apply_recovery_strategy(
+ returned_task, quality_eval
+ )
+ )
+
+ # For decompose, cleanup happens in the method
+ if is_decompose:
+ continue
+
+ except Exception as e:
+ logger.error(
+ f"Error handling quality-failed task "
+ f"{returned_task.id}: {e}",
+ exc_info=True,
+ )
+ continue
+ else:
+ print(
+ f"{Fore.CYAN}Task {returned_task.id} "
+ f"completed successfully (quality score: "
+ f"{quality_eval.quality_score}).{Fore.RESET}"
+ )
+ await self._handle_completed_task(returned_task)
elif returned_task.state == TaskState.FAILED:
try:
halt = await self._handle_failed_task(returned_task)
diff --git a/camel/societies/workforce/workforce_logger.py b/camel/societies/workforce/workforce_logger.py
index 779c73ad3..049d53249 100644
--- a/camel/societies/workforce/workforce_logger.py
+++ b/camel/societies/workforce/workforce_logger.py
@@ -495,6 +495,11 @@ class WorkforceLogger:
tasks_handled_by_worker: Dict[str, int] = {}
+ # Track unique task final states to avoid double-counting
+ task_final_states: Dict[
+ str, str
+ ] = {} # task_id -> 'completed' or 'failed'
+
# Helper function to check if a task is the main task (has no parent)
def is_main_task(task_id: str) -> bool:
return (
@@ -528,7 +533,9 @@ class WorkforceLogger:
elif event_type == 'task_completed':
# Exclude main task from total count
if not is_main_task(task_id):
- kpis['total_tasks_completed'] += 1
+ # Track final state - a completed task overwrites any
+ # previous failed state
+ task_final_states[task_id] = 'completed'
# Count tasks handled by worker (only for non-main tasks)
if 'worker_id' in entry and entry['worker_id'] is not None:
worker_id = entry['worker_id']
@@ -550,7 +557,11 @@ class WorkforceLogger:
elif event_type == 'task_failed':
# Exclude main task from total count
if not is_main_task(task_id):
- kpis['total_tasks_failed'] += 1
+ # Only track as failed if not already completed
+ # (in case of retries, the final completion overwrites
+ # failed state)
+ if task_final_states.get(task_id) != 'completed':
+ task_final_states[task_id] = 'failed'
# Count tasks handled by worker (only for non-main tasks)
if 'worker_id' in entry and entry['worker_id'] is not None:
worker_id = entry['worker_id']
@@ -565,6 +576,14 @@ class WorkforceLogger:
kpis['total_workforce_running_time_seconds'] = (
last_timestamp - first_timestamp
).total_seconds()
+
+ # Count unique tasks by final state
+ for _task_id, state in task_final_states.items():
+ if state == 'completed':
+ kpis['total_tasks_completed'] += 1
+ elif state == 'failed':
+ kpis['total_tasks_failed'] += 1
+
# Calculate worker utilization based on proportion of tasks handled
total_tasks_processed_for_utilization = (
kpis['total_tasks_completed'] + kpis['total_tasks_failed']
@@ -610,9 +629,9 @@ class WorkforceLogger:
kpis['total_workers_created'] = len(self._worker_information)
- # Current pending tasks (simplified)
- kpis['current_pending_tasks'] = kpis['total_tasks_created'] - (
- kpis['total_tasks_completed'] + kpis['total_tasks_failed']
+ # Current pending tasks - tasks created but not yet completed or failed
+ kpis['current_pending_tasks'] = kpis['total_tasks_created'] - len(
+ task_final_states
)
return kpis