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

Revert "feat: Wokforce support configurable fail handling"

Wendong-Fan516cfcef23a0
diff --git a/camel/societies/workforce/__init__.py b/camel/societies/workforce/__init__.py
index 4513cbd12..b390553d2 100644
--- a/camel/societies/workforce/__init__.py
+++ b/camel/societies/workforce/__init__.py
@@ -14,7 +14,7 @@
from .role_playing_worker import RolePlayingWorker
from .single_agent_worker import SingleAgentWorker
-from .utils import FailureHandlingConfig, PipelineTaskBuilder, RecoveryStrategy
+from .utils import PipelineTaskBuilder
from .workflow_memory_manager import WorkflowSelectionMethod
from .workforce import Workforce, WorkforceMode
@@ -25,6 +25,4 @@ __all__ = [
"SingleAgentWorker",
"RolePlayingWorker",
"WorkflowSelectionMethod",
- "FailureHandlingConfig",
- "RecoveryStrategy",
]
diff --git a/camel/societies/workforce/prompts.py b/camel/societies/workforce/prompts.py
index 935c8f6dc..acba05ad8 100644
--- a/camel/societies/workforce/prompts.py
+++ b/camel/societies/workforce/prompts.py
@@ -333,9 +333,58 @@ Provide:
**STEP 2: DETERMINE RECOVERY STRATEGY (if quality insufficient)**
-If the task quality is insufficient, select the best recovery strategy from the ENABLED strategies below:
+If the task quality is insufficient, select the best recovery strategy:
-{available_strategies}
+**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:**
@@ -354,7 +403,6 @@ If the task quality is insufficient, select the best recovery strategy from the
- No explanations or text outside the JSON structure
- Ensure all required fields are included
- Use null for optional fields when not applicable
-- ONLY use strategies listed above as ENABLED
"""
)
@@ -369,60 +417,12 @@ FAILURE_ANALYSIS_RESPONSE_FORMAT = """JSON format:
QUALITY_EVALUATION_RESPONSE_FORMAT = """JSON format:
{
"quality_score": 0-100,
- "reasoning": "explanation (1-2 sentences)",
+ "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"
}"""
-# Strategy descriptions for dynamic prompt generation
-STRATEGY_DESCRIPTIONS = {
- "retry": """**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""",
- "reassign": """**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""",
- "replan": """**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""",
- "decompose": """**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""",
- "create_worker": """**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""",
-}
-
TASK_AGENT_SYSTEM_MESSAGE = """You are an intelligent task management assistant responsible for planning, analyzing, and quality control.
Your responsibilities include:
diff --git a/camel/societies/workforce/utils.py b/camel/societies/workforce/utils.py
index 5c14030c3..74d989595 100644
--- a/camel/societies/workforce/utils.py
+++ b/camel/societies/workforce/utils.py
@@ -224,110 +224,6 @@ class RecoveryStrategy(str, Enum):
return f"RecoveryStrategy.{self.name}"
-class FailureHandlingConfig(BaseModel):
- r"""Configuration for failure handling behavior in Workforce.
-
- This configuration allows users to customize how the Workforce handles
- task failures. This config allows users to disable reassignment or other
- recovery strategies as needed.
-
- Args:
- max_retries (int): Maximum number of retry attempts before giving up
- on a task. (default: :obj:`3`)
- enabled_strategies (Optional[List[RecoveryStrategy]]): List of recovery
- strategies that are allowed to be used. Can be specified as
- RecoveryStrategy enums or strings (e.g., ["retry", "replan"]).
- If None, all strategies are enabled (with LLM analysis).
- If an empty list, no recovery strategies are applied and failed
- tasks are marked as failed immediately. If only ["retry"] is
- specified, simple retry is used without LLM analysis.
- (default: :obj:`None` - all strategies enabled)
- halt_on_max_retries (bool): Whether to halt the entire workforce
- when a task exceeds max retries. If False, the task is marked
- as failed and the workflow continues (similar to PIPELINE mode
- behavior). (default: :obj:`True` for AUTO_DECOMPOSE mode behavior)
-
- Example:
- >>> # Using string list (simple)
- >>> config = FailureHandlingConfig(
- ... enabled_strategies=["retry", "replan", "decompose"],
- ... )
- >>>
- >>> # Using enum list
- >>> config = FailureHandlingConfig(
- ... enabled_strategies=[
- ... RecoveryStrategy.RETRY,
- ... RecoveryStrategy.REPLAN,
- ... ]
- ... )
- >>>
- >>> # Simple retry only
- >>> config = FailureHandlingConfig(
- ... enabled_strategies=["retry"],
- ... max_retries=2,
- ... )
- >>>
- >>> # No recovery - failed tasks are immediately marked as failed
- >>> config = FailureHandlingConfig(
- ... enabled_strategies=[],
- ... )
- >>>
- >>> # Allow failures without halting
- >>> config = FailureHandlingConfig(
- ... halt_on_max_retries=False,
- ... )
- """
-
- max_retries: int = Field(
- default=3,
- ge=1,
- description="Maximum retry attempts before giving up on a task",
- )
-
- enabled_strategies: Optional[List[RecoveryStrategy]] = Field(
- default=None,
- description="List of enabled recovery strategies. None means all "
- "enabled. Empty list means no recovery (immediate failure). "
- "Can be strings like ['retry', 'replan'] or RecoveryStrategy enums.",
- )
-
- halt_on_max_retries: bool = Field(
- default=True,
- description="Whether to halt workforce when max retries exceeded",
- )
-
- @field_validator("enabled_strategies", mode="before")
- @classmethod
- def validate_enabled_strategies(
- cls, v
- ) -> Optional[List[RecoveryStrategy]]:
- r"""Convert string list to RecoveryStrategy enum list."""
- if v is None:
- return None
- if not isinstance(v, list):
- raise ValueError("enabled_strategies must be a list or None")
-
- result = []
- for item in v:
- if isinstance(item, RecoveryStrategy):
- result.append(item)
- elif isinstance(item, str):
- try:
- result.append(RecoveryStrategy(item.lower()))
- except ValueError:
- valid = [s.value for s in RecoveryStrategy]
- raise ValueError(
- f"Invalid strategy '{item}'. "
- f"Valid options: {valid}"
- )
- else:
- raise ValueError(
- f"Strategy must be string or RecoveryStrategy, "
- f"got {type(item).__name__}"
- )
- return result
-
-
class FailureContext(BaseModel):
r"""Context information about a task failure."""
diff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.py
index 45cae1e6c..ec0fe51c6 100644
--- a/camel/societies/workforce/workforce.py
+++ b/camel/societies/workforce/workforce.py
@@ -55,7 +55,6 @@ from camel.societies.workforce.prompts import (
CREATE_NODE_PROMPT,
FAILURE_ANALYSIS_RESPONSE_FORMAT,
QUALITY_EVALUATION_RESPONSE_FORMAT,
- STRATEGY_DESCRIPTIONS,
TASK_AGENT_SYSTEM_MESSAGE,
TASK_ANALYSIS_PROMPT,
TASK_DECOMPOSE_PROMPT,
@@ -69,7 +68,6 @@ from camel.societies.workforce.structured_output_handler import (
)
from camel.societies.workforce.task_channel import TaskChannel
from camel.societies.workforce.utils import (
- FailureHandlingConfig,
PipelineTaskBuilder,
RecoveryStrategy,
TaskAnalysisResult,
@@ -243,15 +241,6 @@ class Workforce(BaseNode):
PIPELINE mode uses simple retry logic and allows failed
tasks to continue the workflow, passing error information
to dependent tasks. (default: :obj:`WorkforceMode.AUTO_DECOMPOSE`)
- failure_handling_config (Optional[Union[FailureHandlingConfig, Dict]]):
- Configuration for customizing failure handling behavior. Can be
- a FailureHandlingConfig instance or a dict with the same fields.
- Allows fine-grained control over which recovery strategies are
- enabled, maximum retry attempts, and whether to halt on max
- retries. The `enabled_strategies` field accepts both enum values
- and string lists like `["retry", "replan"]`. If None, uses
- default configuration with all strategies enabled.
- (default: :obj:`None`)
Example:
>>> import asyncio
@@ -276,16 +265,6 @@ class Workforce(BaseNode):
... task_agent=task_agent,
... )
>>>
- >>> # Workforce with failure handling config as dict (simple)
- >>> workforce = Workforce(
- ... "Research Team",
- ... failure_handling_config={
- ... "max_retries": 5,
- ... "enabled_strategies": ["retry", "replan"],
- ... "halt_on_max_retries": False,
- ... },
- ... )
- >>>
>>> # Process a task
>>> async def main():
... task = Task(content="Research AI trends", id="1")
@@ -316,9 +295,6 @@ class Workforce(BaseNode):
task_timeout_seconds: Optional[float] = None,
mode: WorkforceMode = WorkforceMode.AUTO_DECOMPOSE,
callbacks: Optional[List[WorkforceCallback]] = None,
- failure_handling_config: Optional[
- Union[FailureHandlingConfig, Dict[str, Any]]
- ] = None,
) -> None:
super().__init__(description)
self._child_listening_tasks: Deque[
@@ -334,15 +310,6 @@ class Workforce(BaseNode):
)
self.mode = mode
self._initial_mode = mode # Store initial mode for reset()
- # Initialize failure handling configuration (supports dict input)
- if failure_handling_config is None:
- self.failure_handling_config = FailureHandlingConfig()
- elif isinstance(failure_handling_config, dict):
- self.failure_handling_config = FailureHandlingConfig(
- **failure_handling_config
- )
- else:
- self.failure_handling_config = failure_handling_config
if self.use_structured_output_handler:
self.structured_handler = StructuredOutputHandler()
self._task: Optional[Task] = None
@@ -1399,64 +1366,6 @@ class Workforce(BaseNode):
self._update_dependencies_for_decomposition(task, subtasks)
return subtasks
- def _get_available_strategies_text(self, for_failure: bool) -> str:
- r"""Generate the available strategies text for the analysis prompt.
-
- This method generates a dynamic list of enabled recovery strategies
- based on the failure_handling_config. It only includes strategies
- that are both enabled in the config and applicable to the context
- (failure vs quality evaluation).
-
- Args:
- for_failure (bool): True for failure analysis, False for quality
- evaluation. Some strategies are only available in one context.
-
- Returns:
- str: Formatted text describing available strategies for the prompt.
- """
- # Define which strategies are available in each context
- if for_failure:
- # For failures: retry, replan, decompose, create_worker
- # (reassign is only for quality issues)
- context_strategies = [
- "retry",
- "replan",
- "decompose",
- "create_worker",
- ]
- else:
- # For quality: retry, reassign, replan, decompose
- # (create_worker is only for failures)
- context_strategies = ["retry", "reassign", "replan", "decompose"]
-
- # Filter by enabled strategies in config
- config_strategies = self.failure_handling_config.enabled_strategies
- enabled_strategies = []
- for strategy in context_strategies:
- # None means all enabled, otherwise check if in list
- if (
- config_strategies is None
- or RecoveryStrategy(strategy) in config_strategies
- ):
- enabled_strategies.append(strategy)
-
- if not enabled_strategies:
- raise ValueError(
- "_get_available_strategies_text called with no enabled "
- "strategies. Callers should check enabled_strategies != [] "
- "before calling this method."
- )
-
- # Build the strategies text
- strategies_text_parts = ["**Available Strategies (ENABLED):**\n"]
- for i, strategy in enumerate(enabled_strategies, 1):
- description = STRATEGY_DESCRIPTIONS.get(
- strategy, f"**{strategy}**"
- )
- strategies_text_parts.append(f"{i}. {description}\n")
-
- return "\n".join(strategies_text_parts)
-
def _analyze_task(
self,
task: Task,
@@ -1555,9 +1464,6 @@ class Workforce(BaseNode):
},
]
- # Generate available strategies text based on config
- available_strategies = self._get_available_strategies_text(for_failure)
-
# Format the unified analysis prompt
analysis_prompt = str(
TASK_ANALYSIS_PROMPT.format(
@@ -1570,7 +1476,6 @@ class Workforce(BaseNode):
issue_type=issue_type,
issue_specific_analysis=issue_analysis,
response_format=response_format,
- available_strategies=available_strategies,
)
)
@@ -4288,7 +4193,7 @@ class Workforce(BaseNode):
if (
failed_task
and failed_task.failure_count
- < self.failure_handling_config.max_retries
+ < MAX_TASK_RETRIES
):
failed_tasks_with_retry_potential.append(
dep_id
@@ -4340,8 +4245,7 @@ class Workforce(BaseNode):
f"Task {task.id} waiting: dependencies "
f"{failed_tasks_with_retry_potential} "
f"failed but may be retried "
- f"(attempt < "
- f"{self.failure_handling_config.max_retries})"
+ f"(attempt < {MAX_TASK_RETRIES})"
)
# else: Not all dependencies completed yet, skip this task
@@ -4365,9 +4269,6 @@ class Workforce(BaseNode):
"""
task.failure_count += 1
- # Use configurable max retries from failure_handling_config
- max_retries = self.failure_handling_config.max_retries
-
# Determine detailed failure information
failure_reason = task.result or "Unknown error"
worker_id = task.assigned_worker_id or "unknown"
@@ -4375,12 +4276,12 @@ class Workforce(BaseNode):
logger.error(
f"Task {task.id} failed (attempt "
- f"{task.failure_count}/{max_retries}): {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_retries}): "
+ f"(attempt {task.failure_count}/{MAX_TASK_RETRIES}): "
f"{failure_reason}{Fore.RESET}"
)
@@ -4398,49 +4299,42 @@ class Workforce(BaseNode):
cb.log_task_failed(task_failed_event)
# Check for immediate halt conditions after max retries.
- if task.failure_count >= max_retries:
- # Intent: handle max retry failures differently per mode and
- # config.
+ if task.failure_count >= MAX_TASK_RETRIES:
+ # Intent: handle max retry failures differently per mode.
# Pipeline mode continues to allow downstream recovery.
- # halt_on_max_retries=False also allows workflow to continue.
- # Auto-decompose mode with halt_on_max_retries=True halts.
+ # Auto-decompose mode halts to avoid cascading errors.
if self.mode == WorkforceMode.PIPELINE:
# PIPELINE: Mark as failed but continue workflow
# Intent: Failed tasks pass error info to downstream tasks
logger.warning(
- f"Task {task.id} failed after {max_retries} retries "
+ f"Task {task.id} failed after {MAX_TASK_RETRIES} retries "
f"in PIPELINE mode. Marking as failed and allowing the "
f"workflow to continue. Error: {failure_reason}"
)
- await self._mark_task_permanently_failed(task)
+ task.state = TaskState.FAILED
+ self._cleanup_task_tracking(task.id)
+ self._completed_tasks.append(task)
+ if task.id in self._assignees:
+ await self._channel.archive_task(task.id)
# Resume workflow: Check if downstream tasks can now proceed
# (they'll receive this failed task's error message)
await self._post_ready_tasks()
return False # Don't halt workforce
- # Check if halt_on_max_retries is disabled in config
- if not self.failure_handling_config.halt_on_max_retries:
- # Similar to PIPELINE mode: mark as failed but continue
- logger.warning(
- f"Task {task.id} failed after {max_retries} retries. "
- f"halt_on_max_retries=False, allowing workflow to "
- f"continue. Error: {failure_reason}"
- )
- await self._mark_task_permanently_failed(task)
- await self._post_ready_tasks()
- return False # Don't halt workforce
-
- # AUTO_DECOMPOSE with halt_on_max_retries=True: Halt immediately
+ # AUTO_DECOMPOSE: Halt immediately on max retries
# Intent: Stop execution to prevent cascading failures
logger.error(
f"Task {task.id} has exceeded maximum retry attempts "
- f"({max_retries}). Final failure reason: "
+ f"({MAX_TASK_RETRIES}). Final failure reason: "
f"{detailed_error}. "
f"Task content: '{task.content}'"
)
- await self._mark_task_permanently_failed(task)
+ self._cleanup_task_tracking(task.id)
+ self._completed_tasks.append(task)
+ if task.id in self._assignees:
+ await self._channel.archive_task(task.id)
return True # Halt workforce
if len(self._pending_tasks) > MAX_PENDING_TASKS_LIMIT:
@@ -4449,18 +4343,22 @@ class Workforce(BaseNode):
f"{MAX_PENDING_TASKS_LIMIT}). Halting to prevent task "
f"explosion. Last failed task: {task.id}"
)
- await self._mark_task_permanently_failed(task)
+ self._cleanup_task_tracking(task.id)
+ self._completed_tasks.append(task)
+ if task.id in self._assignees:
+ await self._channel.archive_task(task.id)
return True
- # Recovery strategies differ by mode and configuration.
+ # Recovery strategies differ by mode.
# Pipeline mode retries quickly without additional analysis.
+ # Auto-decompose mode analyzes the failure to choose a recovery plan.
if self.mode == WorkforceMode.PIPELINE:
# PIPELINE: Simple retry logic (no LLM analysis needed)
# Intent: Fast recovery for predefined workflows
logger.info(
f"Task {task.id} failed in PIPELINE mode. Will retry "
- f"(attempt {task.failure_count}/{max_retries})"
+ f"(attempt {task.failure_count}/{MAX_TASK_RETRIES})"
)
# Reset task to pending and retry with same configuration
task.state = TaskState.OPEN
@@ -4468,81 +4366,17 @@ class Workforce(BaseNode):
await self._post_ready_tasks()
return False
- # Check if no recovery strategies are enabled (empty list)
- if self.failure_handling_config.enabled_strategies == []:
- # No recovery - mark task as failed immediately
- logger.info(
- f"Task {task.id} failed. enabled_strategies=[], no recovery "
- f"will be attempted. Marking as failed."
- )
- await self._mark_task_permanently_failed(task)
- # Check halt behavior - only halt if max retries reached
- if (
- self.failure_handling_config.halt_on_max_retries
- and task.failure_count >= max_retries
- ):
- return True # Halt workforce
- await self._post_ready_tasks()
- return False
-
- # Check if only one strategy is enabled (skip LLM analysis)
- enabled = self.failure_handling_config.enabled_strategies
- if enabled is not None and len(enabled) == 1:
- single_strategy = enabled[0]
-
- logger.info(
- f"Task {task.id} failed. Only {single_strategy.value} "
- f"enabled,using it directly without LLM analysis "
- f"(attempt {task.failure_count}/{max_retries})"
- )
-
- # Create a minimal TaskAnalysisResult for the single strategy
- recovery_decision = TaskAnalysisResult(
- reasoning=f"Single strategy {single_strategy.value} enabled, "
- f"applying directly without LLM analysis",
- recovery_strategy=single_strategy,
- )
-
- # Clean up tracking before recovery
- if task.id in self._assignees:
- await self._channel.archive_task(task.id)
- self._cleanup_task_tracking(task.id)
-
- # Apply the single strategy
- try:
- is_decompose = await self._apply_recovery_strategy(
- task, recovery_decision
- )
- if is_decompose:
- self._completed_tasks.append(task)
- await self._post_ready_tasks()
- return False
- except Exception as e:
- logger.error(
- f"Single strategy {single_strategy.value} failed for "
- f"task {task.id}: {e}",
- exc_info=True,
- )
- # If strategy fails, mark task as failed
- task.state = TaskState.FAILED
- self._completed_tasks.append(task)
- if self.failure_handling_config.halt_on_max_retries:
- return True
- await self._post_ready_tasks()
- return False
-
- # AUTO_DECOMPOSE with multiple enabled strategies: Intelligent failure
- # analysis and recovery
+ # AUTO_DECOMPOSE: Intelligent failure analysis and recovery
# Intent: Use LLM analysis to choose an optimal recovery strategy.
recovery_decision = self._analyze_task(
task, for_failure=True, error_message=detailed_error
)
- # Fallback to RETRY if no strategy recommended
- if recovery_decision.recovery_strategy is None:
- recovery_decision.recovery_strategy = RecoveryStrategy.RETRY
-
- strategy_str = recovery_decision.recovery_strategy.value
+ strategy_str = (
+ recovery_decision.recovery_strategy.value
+ if recovery_decision.recovery_strategy
+ else "none"
+ )
logger.info(
f"Task {task.id} failure "
f"analysis: {strategy_str} - "
@@ -4572,7 +4406,7 @@ class Workforce(BaseNode):
exc_info=True,
)
# If max retries reached, halt the workforce
- if task.failure_count >= max_retries:
+ if task.failure_count >= MAX_TASK_RETRIES:
self._completed_tasks.append(task)
return True
self._completed_tasks.append(task)
@@ -4595,21 +4429,6 @@ class Workforce(BaseNode):
await self._post_ready_tasks()
return False
- async def _mark_task_permanently_failed(self, task: Task) -> None:
- r"""Mark a task as permanently failed and clean up tracking.
-
- This is a helper method to avoid code duplication when marking tasks
- as failed in various failure handling scenarios.
-
- Args:
- task (Task): The task to mark as permanently failed.
- """
- task.state = TaskState.FAILED
- self._cleanup_task_tracking(task.id)
- self._completed_tasks.append(task)
- if task.id in self._assignees:
- await self._channel.archive_task(task.id)
-
async def _handle_completed_task(self, task: Task) -> None:
worker_id = task.assigned_worker_id or "unknown"
processing_time_seconds = None
@@ -5109,11 +4928,9 @@ class Workforce(BaseNode):
if len(self.get_main_task_queue()) > 0:
print(
f"{Fore.RED}Task {returned_task.id} has "
- f"failed for "
- f"{self.failure_handling_config.max_retries}"
- f" "
- f"times after insufficient results, "
- f"skipping that task. Final error: "
+ f"failed for {MAX_TASK_RETRIES} times "
+ f"after insufficient results, skipping "
+ f"that task. Final error: "
f"{returned_task.result or 'Unknown err'}"
f"{Fore.RESET}"
)
@@ -5122,10 +4939,9 @@ class Workforce(BaseNode):
print(
f"{Fore.RED}Task {returned_task.id} has "
- f"failed for "
- f"{self.failure_handling_config.max_retries} "
- f"times after insufficient results, halting "
- f"the workforce. Final error: "
+ f"failed for {MAX_TASK_RETRIES} times after "
+ f"insufficient results, halting the "
+ f"workforce. Final error: "
f"{returned_task.result or 'Unknown error'}"
f"{Fore.RESET}"
)
@@ -5139,21 +4955,6 @@ class Workforce(BaseNode):
)
continue
else:
- # Skip quality evaluation if no recovery
- # strategies enabled
- # (no point analyzing if we can't do anything about it)
- if (
- self.failure_handling_config.enabled_strategies
- == []
- ):
- print(
- f"{Fore.CYAN}Task {returned_task.id} "
- f"completed (quality check skipped - "
- f"no recovery strategies enabled).{Fore.RESET}"
- )
- await self._handle_completed_task(returned_task)
- continue
-
quality_eval = self._analyze_task(
returned_task, for_failure=False
)
@@ -5167,14 +4968,7 @@ class Workforce(BaseNode):
)
# Check retry limit before attempting recovery
- # Use max_retries - 1 to allow at least one retry
- quality_retry_limit = max(
- 1, self.failure_handling_config.max_retries - 1
- )
- if (
- returned_task.failure_count
- >= quality_retry_limit
- ):
+ if returned_task.failure_count >= 2:
print(
f"{Fore.YELLOW}Task {returned_task.id} "
f"completed with low quality score: "
@@ -5210,12 +5004,6 @@ class Workforce(BaseNode):
f"Issues: {', '.join(quality_eval.issues)}"
)
- # Fallback to RETRY if no strategy recommended
- if quality_eval.recovery_strategy is None:
- quality_eval.recovery_strategy = (
- RecoveryStrategy.RETRY
- )
-
# Clean up tracking before attempting recovery
if returned_task.id in self._assignees:
await self._channel.archive_task(
@@ -5259,9 +5047,8 @@ class Workforce(BaseNode):
if len(self.get_main_task_queue()) > 0:
print(
f"{Fore.RED}Task {returned_task.id} has "
- f"failed for "
- f"{self.failure_handling_config.max_retries} "
- f"times, skipping that task. Final error: "
+ f"failed for {MAX_TASK_RETRIES} times, "
+ f"skipping that task. Final error: "
f"{returned_task.result or 'Unknown error'}"
f"{Fore.RESET}"
)
@@ -5270,8 +5057,8 @@ class Workforce(BaseNode):
print(
f"{Fore.RED}Task {returned_task.id} has failed "
- f"for {self.failure_handling_config.max_retries} "
- f"times, halting the workforce. Final error: "
+ f"for {MAX_TASK_RETRIES} times, halting "
+ f"the workforce. Final error: "
f"{returned_task.result or 'Unknown error'}"
f"{Fore.RESET}"
)