🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
enhance: Workforce failed task handling (#2802)
Wendong-Fan3e84c0888131
diff --git a/camel/societies/workforce/prompts.py b/camel/societies/workforce/prompts.pyindex 32eb08d22..09a083bc0 100644--- a/camel/societies/workforce/prompts.py+++ b/camel/societies/workforce/prompts.py@@ -97,6 +97,11 @@ Please keep in mind the task you are going to process, the content of the task t{content}==============================+Here is the content of the parent task for you to refer to:+==============================+{parent_task_content}+==============================+Here are results of some prerequisite tasks that you can refer to:==============================@@ -127,16 +132,22 @@ concluding remarks, explanations, or any other text outside the JSON structure iROLEPLAY_PROCESS_TASK_PROMPT = TextPrompt("""You need to process the task. It is recommended that tools be actively called when needed.-Here are results of some prerequisite tasks that you can refer to:++The content of the task that you need to do is:==============================-{dependency_task_info}+{content}==============================-The content of the task that you need to do is:+Here is the content of the parent task for you to refer to:+==============================+{parent_task_content}+==============================++Here are results of some prerequisite tasks that you can refer to:==============================-{content}+{dependency_task_info}==============================Here are some additional information about the task:@@ -255,3 +266,54 @@ Each subtask should be:- Contain all sequential steps that should be performed by the same worker type- Only separated from other subtasks when parallel execution by different worker types is beneficial"""++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++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+- **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++**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++**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.+"""+)diff --git a/camel/societies/workforce/role_playing_worker.py b/camel/societies/workforce/role_playing_worker.pyindex 7e844ca22..5e3175050 100644--- a/camel/societies/workforce/role_playing_worker.py+++ b/camel/societies/workforce/role_playing_worker.py@@ -104,6 +104,7 @@ class RolePlayingWorker(Worker):dependency_tasks_info = self._get_dep_tasks_info(dependencies)prompt = ROLEPLAY_PROCESS_TASK_PROMPT.format(content=task.content,+ parent_task_content=task.parent.content if task.parent else "",dependency_task_info=dependency_tasks_info,additional_info=task.additional_info,)diff --git a/camel/societies/workforce/single_agent_worker.py b/camel/societies/workforce/single_agent_worker.pyindex 45c85ceff..23453398c 100644--- a/camel/societies/workforce/single_agent_worker.py+++ b/camel/societies/workforce/single_agent_worker.py@@ -273,6 +273,7 @@ class SingleAgentWorker(Worker):dependency_tasks_info = self._get_dep_tasks_info(dependencies)prompt = PROCESS_TASK_PROMPT.format(content=task.content,+ parent_task_content=task.parent.content if task.parent else "",dependency_tasks_info=dependency_tasks_info,additional_info=task.additional_info,)diff --git a/camel/societies/workforce/utils.py b/camel/societies/workforce/utils.pyindex 18a1e680b..388801246 100644--- a/camel/societies/workforce/utils.py+++ b/camel/societies/workforce/utils.py@@ -11,8 +11,9 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from enum import Enumfrom functools import wraps-from typing import Callable, List+from typing import Callable, List, Optionalfrom pydantic import BaseModel, Field, field_validator@@ -80,6 +81,53 @@ class TaskAssignResult(BaseModel):)+class RecoveryStrategy(str, Enum):+ r"""Strategies for handling failed tasks."""++ RETRY = "retry"+ REPLAN = "replan"+ DECOMPOSE = "decompose"+ CREATE_WORKER = "create_worker"++ def __str__(self):+ return self.value++ def __repr__(self):+ return f"RecoveryStrategy.{self.name}"+++class FailureContext(BaseModel):+ r"""Context information about a task failure."""++ task_id: str = Field(description="ID of the failed task")+ task_content: str = Field(description="Content of the failed task")+ failure_count: int = Field(+ description="Number of times this task has failed"+ )+ error_message: str = Field(description="Detailed error message")+ worker_id: Optional[str] = Field(+ default=None, description="ID of the worker that failed"+ )+ task_depth: int = Field(+ description="Depth of the task in the decomposition hierarchy"+ )+ additional_info: Optional[str] = Field(+ default=None, description="Additional context about the task"+ )+++class RecoveryDecision(BaseModel):+ r"""Decision on how to recover from a task failure."""++ strategy: RecoveryStrategy = Field(+ description="The chosen recovery strategy"+ )+ 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"+ )++def check_if_running(running: bool,max_retries: int = 3,diff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.pyindex ddc05f04e..f581b374a 100644--- a/camel/societies/workforce/workforce.py+++ b/camel/societies/workforce/workforce.py@@ -14,6 +14,7 @@from __future__ import annotationsimport asyncio+import concurrent.futuresimport jsonimport timeimport uuid@@ -28,6 +29,7 @@ from typing import (Optional,Set,Tuple,+ Union,)from colorama import Fore@@ -40,12 +42,16 @@ from camel.societies.workforce.base import BaseNodefrom camel.societies.workforce.prompts import (ASSIGN_TASK_PROMPT,CREATE_NODE_PROMPT,+ FAILURE_ANALYSIS_PROMPT,WF_TASK_DECOMPOSE_PROMPT,)from camel.societies.workforce.role_playing_worker import RolePlayingWorkerfrom camel.societies.workforce.single_agent_worker import SingleAgentWorkerfrom camel.societies.workforce.task_channel import TaskChannelfrom camel.societies.workforce.utils import (+ FailureContext,+ RecoveryDecision,+ RecoveryStrategy,TaskAssignment,TaskAssignResult,WorkerConf,@@ -214,7 +220,9 @@ class Workforce(BaseNode):share_memory: bool = False,) -> None:super().__init__(description)- self._child_listening_tasks: Deque[asyncio.Task] = deque()+ self._child_listening_tasks: Deque[+ Union[asyncio.Task, concurrent.futures.Future]+ ] = deque()self._children = children or []self.new_worker_agent = new_worker_agentself.graceful_shutdown_timeout = graceful_shutdown_timeout@@ -611,6 +619,31 @@ class Workforce(BaseNode):# Remove original task dependencies as it's now decomposeddel self._task_dependencies[original_task_id]+ def _increment_in_flight_tasks(self, task_id: str) -> None:+ r"""Safely increment the in-flight tasks counter with logging."""+ self._in_flight_tasks += 1+ logger.debug(+ f"Incremented in-flight tasks for {task_id}. "+ f"Count: {self._in_flight_tasks}"+ )++ def _decrement_in_flight_tasks(+ self, task_id: str, context: str = ""+ ) -> None:+ r"""Safely decrement the in-flight tasks counter with safety checks."""+ if self._in_flight_tasks > 0:+ self._in_flight_tasks -= 1+ logger.debug(+ f"Decremented in-flight tasks for {task_id} ({context}). "+ f"Count: {self._in_flight_tasks}"+ )+ else:+ logger.debug(+ f"Attempted to decrement in-flight tasks for {task_id} "+ f"({context}) but counter is already 0. "+ f"Counter: {self._in_flight_tasks}"+ )+def _cleanup_task_tracking(self, task_id: str) -> None:r"""Clean up tracking data for a task to prevent memory leaks.@@ -634,9 +667,6 @@ class Workforce(BaseNode):)self.task_agent.reset()subtasks = task.decompose(self.task_agent, decompose_prompt)- task.subtasks = subtasks- for subtask in subtasks:- subtask.parent = task# Update dependency tracking for decomposed taskif subtasks:@@ -644,6 +674,79 @@ class Workforce(BaseNode):return subtasks+ def _analyze_failure(+ self, task: Task, error_message: str+ ) -> RecoveryDecision:+ r"""Analyze a task failure and decide on the best recovery strategy.++ Args:+ task (Task): The failed task+ error_message (str): The error message from the failure++ Returns:+ RecoveryDecision: The decided recovery strategy with reasoning+ """+ # 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',+ ]+ ):+ return RecoveryDecision(+ strategy=RecoveryStrategy.RETRY,+ reasoning="Network/connection error detected, retrying task",+ modified_task_content=None,+ )++ # Create failure context+ failure_context = FailureContext(+ task_id=task.id,+ task_content=task.content,+ 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",+ )++ try:+ # Get decision from task agent+ self.task_agent.reset()+ response = self.task_agent.step(+ analysis_prompt, response_format=RecoveryDecision+ )+ return response.msg.parsed++ except Exception as e:+ logger.warning(+ f"Error during failure analysis: {e}, defaulting to RETRY"+ )+ return RecoveryDecision(+ strategy=RecoveryStrategy.RETRY,+ reasoning=f"Analysis failed due to error: {e!s}, "+ f"defaulting to retry",+ modified_task_content=None,+ )+# Human intervention methodsasync def _async_pause(self) -> None:r"""Async implementation of pause to run on the event loop."""@@ -1029,9 +1132,6 @@ class Workforce(BaseNode):needed>>> print(result.result)"""- import asyncio- import concurrent.futures-# Check if we're already in an event looptry:current_loop = asyncio.get_running_loop()@@ -1206,7 +1306,39 @@ class Workforce(BaseNode):return self._task- @check_if_running(False)+ def _start_child_node_when_paused(+ self, start_coroutine: Coroutine+ ) -> None:+ r"""Helper to start a child node when workforce is paused.++ Args:+ start_coroutine: The coroutine to start (e.g., worker_node.start())+ """+ if self._state == WorkforceState.PAUSED and hasattr(+ self, '_child_listening_tasks'+ ):+ if self._loop and not self._loop.is_closed():+ # Use thread-safe coroutine execution for dynamic addition+ child_task: Union[asyncio.Task, concurrent.futures.Future]+ try:+ # Check if we're in the same thread as the loop+ current_loop = asyncio.get_running_loop()+ if current_loop is self._loop:+ # Same loop context - use create_task+ child_task = self._loop.create_task(start_coroutine)+ else:+ # Different loop context - use thread-safe approach+ child_task = asyncio.run_coroutine_threadsafe(+ start_coroutine, self._loop+ )+ except RuntimeError:+ # No running loop in current thread - use thread-safe+ # approach+ child_task = asyncio.run_coroutine_threadsafe(+ start_coroutine, self._loop+ )+ self._child_listening_tasks.append(child_task)+def add_single_agent_worker(self,description: str,@@ -1214,6 +1346,7 @@ class Workforce(BaseNode):pool_max_size: int = DEFAULT_WORKER_POOL_SIZE,) -> Workforce:r"""Add a worker node to the workforce that uses a single agent.+ Can be called when workforce is paused to dynamically add workers.Args:description (str): Description of the worker node.@@ -1223,7 +1356,15 @@ class Workforce(BaseNode):Returns:Workforce: The workforce node itself.++ Raises:+ RuntimeError: If called while workforce is running (not paused)."""+ if self._state == WorkforceState.RUNNING:+ raise RuntimeError(+ "Cannot add workers while workforce is running. "+ "Pause the workforce first."+ )# Ensure the worker agent shares this workforce's pause controlself._attach_pause_event_to_agent(worker)@@ -1233,6 +1374,14 @@ class Workforce(BaseNode):pool_max_size=pool_max_size,)self._children.append(worker_node)++ # If we have a channel set up, set it for the new worker+ if hasattr(self, '_channel') and self._channel is not None:+ worker_node.set_channel(self._channel)++ # If workforce is paused, start the worker's listening task+ self._start_child_node_when_paused(worker_node.start())+if self.metrics_logger:self.metrics_logger.log_worker_created(worker_id=worker_node.node_id,@@ -1241,7 +1390,6 @@ class Workforce(BaseNode):)return self- @check_if_running(False)def add_role_playing_worker(self,description: str,@@ -1253,6 +1401,7 @@ class Workforce(BaseNode):chat_turn_limit: int = 3,) -> Workforce:r"""Add a worker node to the workforce that uses `RolePlaying` system.+ Can be called when workforce is paused to dynamically add workers.Args:description (str): Description of the node.@@ -1272,7 +1421,15 @@ class Workforce(BaseNode):Returns:Workforce: The workforce node itself.++ Raises:+ RuntimeError: If called while workforce is running (not paused)."""+ if self._state == WorkforceState.RUNNING:+ raise RuntimeError(+ "Cannot add workers while workforce is running. "+ "Pause the workforce first."+ )# Ensure provided kwargs carry pause_event so that internally created# ChatAgents (assistant/user/summarizer) inherit it.assistant_agent_kwargs = self._ensure_pause_event_in_kwargs(@@ -1295,6 +1452,14 @@ class Workforce(BaseNode):chat_turn_limit=chat_turn_limit,)self._children.append(worker_node)++ # If we have a channel set up, set it for the new worker+ if hasattr(self, '_channel') and self._channel is not None:+ worker_node.set_channel(self._channel)++ # If workforce is paused, start the worker's listening task+ self._start_child_node_when_paused(worker_node.start())+if self.metrics_logger:self.metrics_logger.log_worker_created(worker_id=worker_node.node_id,@@ -1303,20 +1468,35 @@ class Workforce(BaseNode):)return self- @check_if_running(False)def add_workforce(self, workforce: Workforce) -> Workforce:r"""Add a workforce node to the workforce.+ Can be called when workforce is paused to dynamically add workers.Args:workforce (Workforce): The workforce node to be added.Returns:Workforce: The workforce node itself.++ Raises:+ RuntimeError: If called while workforce is running (not paused)."""+ if self._state == WorkforceState.RUNNING:+ raise RuntimeError(+ "Cannot add workers while workforce is running. "+ "Pause the workforce first."+ )# Align child workforce's pause_event with this one for unified# control of worker agents only.workforce._pause_event = self._pause_eventself._children.append(workforce)++ # If we have a channel set up, set it for the new workforce+ if hasattr(self, '_channel') and self._channel is not None:+ workforce.set_channel(self._channel)++ # If workforce is paused, start the child workforce's listening task+ self._start_child_node_when_paused(workforce.start())return selfasync def _async_reset(self) -> None:@@ -1654,15 +1834,13 @@ class Workforce(BaseNode):)try:- self._in_flight_tasks += 1await self._channel.post_task(task, self.node_id, assignee_id)+ self._increment_in_flight_tasks(task.id)logger.debug(f"Posted task {task.id} to {assignee_id}. "f"In-flight tasks: {self._in_flight_tasks}")except Exception as e:- # Decrement counter if posting failed- self._in_flight_tasks -= 1logger.error(f"Failed to post task {task.id} to {assignee_id}: {e}")@@ -1789,10 +1967,6 @@ class Workforce(BaseNode):timeout=TASK_TIMEOUT_SECONDS,)except Exception as e:- # Decrement in-flight counter to prevent hanging- if self._in_flight_tasks > 0:- self._in_flight_tasks -= 1-error_msg = (f"Error getting returned task {e} in "f"workforce {self.node_id}. "@@ -1804,8 +1978,11 @@ class Workforce(BaseNode):if self._pending_tasks and self._assignees:for task in self._pending_tasks:if task.id in self._assignees:- # Mark this real task as failed+ # Mark task as failed and decrement countertask.set_state(TaskState.FAILED)+ self._decrement_in_flight_tasks(+ task.id, "timeout/error in _get_returned_task"+ )return taskreturn None@@ -1905,7 +2082,6 @@ class Workforce(BaseNode):task_id=task.id,worker_id=worker_id,error_message=detailed_error,- error_type="TaskFailure",metadata={'failure_count': task.failure_count,'task_content': task.content,@@ -1944,21 +2120,57 @@ class Workforce(BaseNode):await self._channel.archive_task(task.id)return True- if task.get_depth() > 3:- # Create a new worker node and reassign- assignee = await self._create_worker_node_for_task(task)+ # Use intelligent failure analysis to decide recovery strategy+ recovery_decision = self._analyze_failure(task, detailed_error)- # Sync shared memory after creating new worker to provide context- if self.share_memory:- logger.info(- f"Syncing shared memory after creating new worker "- f"{assignee.node_id} for failed task {task.id}"+ logger.info(+ f"Task {task.id} failure "+ f"analysis: {recovery_decision.strategy.value} - "+ f"{recovery_decision.reasoning}"+ )++ 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}")- self._sync_shared_memory()- await self._post_task(task, assignee.node_id)- action_taken = f"reassigned to new worker {assignee.node_id}"- else:+ 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 subtaskssubtasks = self._decompose_task(task)if self.metrics_logger and subtasks:self.metrics_logger.log_task_decomposed(@@ -2000,7 +2212,14 @@ class Workforce(BaseNode):await self._post_ready_tasks()return False- # For reassigned tasks (depth > 3), handle normally+ 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"+ )+if task.id in self._assignees:await self._channel.archive_task(task.id)@@ -2275,7 +2494,9 @@ class Workforce(BaseNode):await self._post_ready_tasks()continue- self._in_flight_tasks -= 1+ self._decrement_in_flight_tasks(+ returned_task.id, "task returned successfully"+ )# Check for stop request after getting taskif self._stop_requested:@@ -2360,8 +2581,9 @@ class Workforce(BaseNode):except Exception as e:# Decrement in-flight counter to prevent hanging- if self._in_flight_tasks > 0:- self._in_flight_tasks -= 1+ self._decrement_in_flight_tasks(+ "unknown", "exception in task processing loop"+ )logger.error(f"Error processing task in workforce {self.node_id}: {e}"@@ -2440,8 +2662,20 @@ class Workforce(BaseNode):for task in self._child_listening_tasks:if not task.done():task.cancel()++ # Handle both asyncio.Task and concurrent.futures.+ # Future+ awaitables = []+ for task in self._child_listening_tasks:+ if isinstance(task, concurrent.futures.Future):+ # Convert Future to awaitable+ awaitables.append(asyncio.wrap_future(task))+ else:+ # Already an asyncio.Task+ awaitables.append(task)+await asyncio.gather(- *self._child_listening_tasks,+ *awaitables,return_exceptions=True,)diff --git a/camel/societies/workforce/workforce_logger.py b/camel/societies/workforce/workforce_logger.pyindex 83e4cd65f..779c73ad3 100644--- a/camel/societies/workforce/workforce_logger.py+++ b/camel/societies/workforce/workforce_logger.py@@ -180,7 +180,6 @@ class WorkforceLogger:self,task_id: str,error_message: str,- error_type: str,worker_id: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,) -> None:@@ -190,7 +189,6 @@ class WorkforceLogger:task_id=task_id,worker_id=worker_id,error_message=error_message,- error_type=error_type,metadata=metadata or {},)if task_id in self._task_hierarchy:@@ -484,7 +482,6 @@ class WorkforceLogger:'total_tasks_created': 0,'total_tasks_completed': 0,'total_tasks_failed': 0,- 'error_types_count': {},'worker_utilization': {},'current_pending_tasks': 0,'total_workforce_running_time_seconds': 0.0,@@ -560,11 +557,6 @@ class WorkforceLogger:tasks_handled_by_worker[worker_id] = (tasks_handled_by_worker.get(worker_id, 0) + 1)- error_type = entry['error_type']- kpis['error_types_count'][error_type] = (- kpis['error_types_count'].get(error_type, 0) + 1- )-elif event_type == 'queue_status':pass # Placeholder for nowdiff --git a/camel/tasks/task.py b/camel/tasks/task.pyindex e4bf10a1c..17621cdb5 100644--- a/camel/tasks/task.py+++ b/camel/tasks/task.py@@ -430,6 +430,8 @@ class Task(BaseModel):tasks = task_parser(response.msg.content, self.id)for task in tasks:task.additional_info = self.additional_info+ task.parent = self+ self.subtasks = tasksreturn tasksdef compose(diff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.pyindex 2a37406a2..6a52a853d 100644--- a/examples/workforce/eigent.py+++ b/examples/workforce/eigent.py@@ -22,7 +22,6 @@ from camel.societies.workforce import Workforcefrom camel.tasks.task import Taskfrom camel.toolkits import (AudioAnalysisToolkit,- CodeExecutionToolkit,Crawl4AIToolkit,EdgeOnePagesMCPToolkit,ExcelToolkit,@@ -87,34 +86,39 @@ def developer_agent_factory(send_message_to_user,HumanToolkit().ask_human_via_console,*TerminalToolkit(clone_current_env=True).get_tools(),- *CodeExecutionToolkit().get_tools(),*edgeone_pages_mcp_toolkit.get_tools(),]- system_message = """You are a skilled coding assistant with DIRECT CODE- EXECUTION CAPABILITIES. You MUST use the `send_message_to_user` tool to- inform the user of every decision and action you take. Your message must- include a short title and a one-sentence description. This is a- mandatory part of your workflow.+ system_message = """You are a skilled coding assistant. You can write and+ execute code by using the available terminal tools. You MUST use the+ `send_message_to_user` tool to inform the user of every decision and+ action you take. Your message must include a short title and a+ one-sentence description. This is a mandatory part of your workflow.Your capabilities include:- - WRITE AND EXECUTE code in real-time to solve tasks- - RUN terminal commands to install packages, process files, or test- functionality- - VERIFY your solutions through immediate execution and testing- - UTILIZE any Python libraries (requests, BeautifulSoup, pandas, etc.)- needed for efficient solutions- - IMPLEMENT complete, production-ready code rather than theoretical- examples- - USE edgeone pages mcp toolkit to create and edit web pages. After you- create a web page, you can ask the search agent to visit it for+ - Writing code to solve tasks. To execute the code, you MUST first save+ it to a file in the workspace (e.g., `script.py`), and then run it using+ the terminal tool (e.g., `python script.py`).+ - Running terminal commands to install packages (e.g., with `pip`),+ process files, or test functionality. All files you create should be in+ the designated workspace.+ - Verifying your solutions through immediate execution and testing in the+ terminal.+ - Utilizing any Python libraries (e.g., requests, BeautifulSoup, pandas,+ etc.) needed for efficient solutions. You can install missing packages+ using `pip` in the terminal.+ - Implementing complete, production-ready code rather than theoretical+ examples.+ - Using the `edgeone_pages_mcp_toolkit` to create and edit web pages.+ After you create a web page, you can ask the search agent to visit it forverification.- - DEMONSTRATE results with proper error handling and practical- implementation- - If there's dependency issues when you try to execute code, you should- use the terminal toolkit to install the dependencies.- - ASK for human input via the console if you are stuck or need+ - Demonstrating results with proper error handling and practical+ implementation.+ - Asking for human input via the console if you are stuck or needclarification.++ Remember to manage your terminal sessions. You can create new sessions+ and run commands in them."""return ChatAgent(@@ -127,7 +131,7 @@ def developer_agent_factory()-@api_keys_required([(None, 'EXA_API_KEY')])+@api_keys_required([(None, 'EXA_API_KEY'), (None, 'GOOGLE_API_KEY')])def search_agent_factory(model: BaseModelBackend,task_id: str,@@ -137,8 +141,8 @@ def search_agent_factory("""tools = [# FunctionTool(SearchToolkit().search_wiki),- SearchToolkit().search_exa,- # FunctionTool(SearchToolkit().search_bing),+ SearchToolkit().search_google,+ SearchToolkit().search_bing,# FunctionTool(SearchToolkit().search_baidu),*HybridBrowserToolkit(headless=False).get_tools(),*TerminalToolkit().get_tools(),@@ -157,6 +161,17 @@ def search_agent_factory(and a one-sentence description. This is a mandatory part of yourworkflow.+ ### Web Search Workflow+ 1. **Search First**: You MUST start by using a search engine to get+ initial URLs. Use `search_google` for English queries and+ `search_bing` for Chinese queries. Do not use browser tools before+ this step.+ 2. **Browse URLs**: After getting search results, use the `visit_page`+ tool from the browser toolkit to open promising URLs.+ 3. **Explore and Scrape**: Once on a page, use browser tools to read+ content, scrape information, and navigate to other linked pages to+ gather all necessary data.+### Core Principles- For each decision you make and action you take, you must send a messageto the user to keep them informed.@@ -174,35 +189,18 @@ def search_agent_factory(report, so make them clear, concise, and well-organized. Includeheadings, details, and any relevant URLs or sources.- ### Web Search Strategy- - When solving tasks that require web searches, check Wikipedia first- before exploring other websites.- - If a question is complex, your search query should be concise and focus- on finding official sources. For example, to answer "What is the maximum- length in meters of #9 in the first National Geographic short on YouTube- that was ever released according to the Monterey Bay Aquarium website?",- your first search term should be coarse-grained like "National- Geographic YouTube" to find the official channel first, then narrow down- your search.- - If the search snippet is unhelpful but the URL comes from an- authoritative source, try visiting the website for more details.- - When looking for specific numerical values (e.g., dollar amounts),- prioritize reliable sources and avoid relying only on search snippets.-- ### Browser Interaction- - When using `open_browser` or `visit_page` without a specific URL in- mind, start from a search engine like Brave Search- (https://search.brave.com) instead of trying to guess the URL.- - You can simulate browser actions to get more information or verify what- you have found. This is also helpful for finding target URLs that are- hard to find with simple web searches.- - After visiting a page, check its subpages for more relevant- information.- - Do not rely solely on browser simulation. Combine search, scraper, and- browser tools to process web page information comprehensively. Some- content may require browser simulation to access.+ ### Guidelines+ - If a search query is complex, break it down. Start with broad terms to+ find authoritative sources, then narrow your search.+ - If a search snippet is unhelpful but the URL seems authoritative, visit+ the page to investigate further.+ - IMPORTANT: You MUST only use URLs from search results or scraped from+ pages you have visited. NEVER invent or guess URLs.+ - After visiting a page, check its subpages for more relevant information.+ - Combine search, scraper, and browser tools for comprehensive information+ gathering.- In your response, you should mention the URLs you have visited and- processed.+ processed.### Handling Obstacles- When encountering verification challenges (like login, CAPTCHAs or@@ -236,6 +234,7 @@ def document_agent_factory(*MarkItDownToolkit().get_tools(),*ExcelToolkit().get_tools(),NoteTakingToolkit().read_note,+ SearchToolkit().search_exa,]system_message = """You are a Document Processing Assistant specialized in@@ -321,6 +320,7 @@ def multi_modal_agent_factory(model: BaseModelBackend, task_id: str):*OpenAIImageToolkit().get_tools(),send_message_to_user,HumanToolkit().ask_human_via_console,+ SearchToolkit().search_exa,]system_message = """You are a Multi-Modal Processing Assistant specialized@@ -438,6 +438,7 @@ operations.*SlackToolkit().get_tools(),send_message_to_user,HumanToolkit().ask_human_via_console,+ SearchToolkit().search_exa,],)diff --git a/examples/workforce/hackathon_judges.py b/examples/workforce/hackathon_judges.pyindex e845e98cc..a9765996a 100644--- a/examples/workforce/hackathon_judges.py+++ b/examples/workforce/hackathon_judges.py@@ -332,7 +332,6 @@ and trends on AI and Open Sourced projects.)total_tasks_created: 8total_tasks_completed: 8total_tasks_failed: 0-error_types_count: {}worker_utilization: {'dd947275-ccd5-49b2-9563-fb4f5f80ca60': '37.50%','9fd6b827-4891-4af8-8daa-656be0f4d1b3': '12.50%','661df9e3-6ebd-4977-be74-7ea929531dd8': '12.50%',diff --git a/test/workforce/test_workforce.py b/test/workforce/test_workforce.pyindex 3a8f8e976..f0d4010a5 100644--- a/test/workforce/test_workforce.py+++ b/test/workforce/test_workforce.py@@ -415,3 +415,76 @@ def test_cross_agent_memory_access(mock_model, sample_shared_memory):# Both should know both pieces of informationfor content in [alice_content, bob_content]:assert "blue42" in content and "314" in content+++def test_dynamic_worker_addition():+ r"""Test adding workers dynamically during different workforce states"""+ workforce = Workforce(description="Dynamic Test Workforce")+ from camel.societies.workforce.workforce import WorkforceState++ # Test 1: Add worker in IDLE state (should work)+ agent1 = ChatAgent("You are a test agent.")+ workforce.add_single_agent_worker("Test Worker 1", agent1)+ assert len(workforce._children) == 1++ # Test 2: Add worker in PAUSED state (should work)+ workforce._state = WorkforceState.PAUSED+ agent2 = ChatAgent("You are another test agent.")+ workforce.add_single_agent_worker("Test Worker 2", agent2)+ assert len(workforce._children) == 2++ # Test 3: Try to add worker in RUNNING state (should fail)+ workforce._state = WorkforceState.RUNNING+ agent3 = ChatAgent("You should not be added.")++ with pytest.raises(+ RuntimeError, match="Cannot add workers while workforce is running"+ ):+ workforce.add_single_agent_worker("Should Fail", agent3)++ assert len(workforce._children) == 2 # No new worker added+++async def test_dynamic_worker_types():+ r"""Test adding different types of workers during pause"""+ workforce = Workforce(description="Worker Types Test")+ from camel.societies.workforce.workforce import WorkforceState++ workforce._state = WorkforceState.PAUSED++ # Add SingleAgentWorker+ agent = ChatAgent("You are a specialist.")+ workforce.add_single_agent_worker("Specialist", agent)+ assert len(workforce._children) == 1++ # Add RolePlayingWorker+ workforce.add_role_playing_worker(+ description="Analysis Team",+ assistant_role_name="Analyst",+ user_role_name="Expert",+ )+ assert len(workforce._children) == 2++ # Add nested Workforce+ nested = Workforce(description="Sub-team")+ workforce.add_workforce(nested)+ assert len(workforce._children) == 3+++def test_start_child_node_helper():+ r"""Test the _start_child_node_when_paused helper function"""+ workforce = Workforce(description="Helper Test")+ from camel.societies.workforce.workforce import WorkforceState++ async def mock_coroutine():+ return "test"++ # Should do nothing when not paused+ workforce._state = WorkforceState.IDLE+ workforce._start_child_node_when_paused(mock_coroutine())++ # Should do nothing when no loop+ workforce._state = WorkforceState.PAUSED+ workforce._loop = None+ workforce._start_child_node_when_paused(mock_coroutine())