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

fix: workforce sub task status (#2796)

Wendong-Fandf20dc57dc32
diff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.py
index 6de54dbaf..ddc05f04e 100644
--- a/camel/societies/workforce/workforce.py
+++ b/camel/societies/workforce/workforce.py
@@ -573,6 +573,44 @@ class Workforce(BaseNode):
except Exception as e:
logger.warning(f"Error synchronizing shared memory: {e}")
+ def _update_dependencies_for_decomposition(
+ self, original_task: Task, subtasks: List[Task]
+ ) -> None:
+ r"""Update dependency tracking when a task is decomposed into subtasks.
+ Tasks that depended on the original task should now depend on all
+ subtasks. The last subtask inherits the original task's dependencies.
+ """
+ if not subtasks:
+ return
+
+ original_task_id = original_task.id
+ subtask_ids = [subtask.id for subtask in subtasks]
+
+ # Find tasks that depend on the original task
+ dependent_task_ids = [
+ task_id
+ for task_id, deps in self._task_dependencies.items()
+ if original_task_id in deps
+ ]
+
+ # Update dependent tasks to depend on all subtasks
+ for task_id in dependent_task_ids:
+ dependencies = self._task_dependencies[task_id]
+ dependencies.remove(original_task_id)
+ dependencies.extend(subtask_ids)
+
+ # The last subtask inherits original task's dependencies (if any)
+ if original_task_id in self._task_dependencies:
+ original_dependencies = self._task_dependencies[original_task_id]
+ if original_dependencies:
+ # Set dependencies for the last subtask to maintain execution
+ # order
+ self._task_dependencies[subtask_ids[-1]] = (
+ original_dependencies.copy()
+ )
+ # Remove original task dependencies as it's now decomposed
+ del self._task_dependencies[original_task_id]
+
def _cleanup_task_tracking(self, task_id: str) -> None:
r"""Clean up tracking data for a task to prevent memory leaks.
@@ -600,6 +638,10 @@ class Workforce(BaseNode):
for subtask in subtasks:
subtask.parent = task
+ # Update dependency tracking for decomposed task
+ if subtasks:
+ self._update_dependencies_for_decomposition(task, subtasks)
+
return subtasks
# Human intervention methods
@@ -1805,17 +1847,19 @@ class Workforce(BaseNode):
# Step 2: Iterate through all pending tasks and post those that are
# ready
posted_tasks = []
- # Pre-compute completed task IDs set for O(1) lookups
- completed_task_ids = {t.id for t in self._completed_tasks}
+ # Pre-compute completed task IDs and their states for O(1) lookups
+ completed_tasks_info = {t.id: t.state for t in self._completed_tasks}
for task in self._pending_tasks:
# A task must be assigned to be considered for posting
if task.id in self._task_dependencies:
dependencies = self._task_dependencies[task.id]
# Check if all dependencies for this task are in the completed
- # set
+ # set and their state is DONE
if all(
- dep_id in completed_task_ids for dep_id in dependencies
+ 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(
@@ -1932,19 +1976,35 @@ class Workforce(BaseNode):
# 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"
+
+ # Handle task completion differently for decomposed tasks
+ if task.id in self._assignees:
+ await self._channel.archive_task(task.id)
+
+ self._cleanup_task_tracking(task.id)
+ 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 decomposing failed "
- f"task {task.id}"
+ f"Syncing shared memory after task {task.id} decomposition"
)
self._sync_shared_memory()
+ # Check if any pending tasks are now ready to execute
await self._post_ready_tasks()
- action_taken = f"decomposed into {len(subtasks)} subtasks"
+ return False
+
+ # For reassigned tasks (depth > 3), handle normally
if task.id in self._assignees:
await self._channel.archive_task(task.id)
+ self._cleanup_task_tracking(task.id)
logger.debug(
f"Task {task.id} failed and was {action_taken}. "
f"Updating dependency state."
@@ -2037,31 +2097,65 @@ class Workforce(BaseNode):
break
if not found_and_removed:
- # Task was already removed from pending queue (expected case when
- # it had been popped immediately after posting). No need to
- # draw user attention with a warning; record at debug level.
+ # Task was already removed from pending queue (common case when
+ # it was posted and removed immediately).
logger.debug(
f"Completed task {task.id} was already removed from pending "
- "queue."
+ "queue (normal for posted tasks)."
)
# Archive the task and update dependency tracking
if task.id in self._assignees:
await self._channel.archive_task(task.id)
- # Ensure it's in completed tasks set
- self._completed_tasks.append(task)
+ # Ensure it's in completed tasks set by updating if it exists or
+ # appending if it's new.
+ task_found_in_completed = False
+ for i, t in enumerate(self._completed_tasks):
+ if t.id == task.id:
+ self._completed_tasks[i] = task
+ task_found_in_completed = True
+ break
+ if not task_found_in_completed:
+ self._completed_tasks.append(task)
# Handle parent task completion logic
parent = task.parent
- if parent and parent.id not in {t.id for t in self._completed_tasks}:
+ if parent:
+ # Check if all subtasks are completed and successful
all_subtasks_done = all(
- sub.id in {t.id for t in self._completed_tasks}
+ any(
+ t.id == sub.id and t.state == TaskState.DONE
+ for t in self._completed_tasks
+ )
for sub in parent.subtasks
)
if all_subtasks_done:
- # Set the parent task state to done
+ # Collect results from successful subtasks only
+ successful_results = []
+ for sub in parent.subtasks:
+ completed_subtask = next(
+ (
+ t
+ for t in self._completed_tasks
+ if t.id == sub.id and t.state == TaskState.DONE
+ ),
+ None,
+ )
+ if completed_subtask and completed_subtask.result:
+ successful_results.append(
+ f"--- Subtask {sub.id} Result ---\n"
+ f"{completed_subtask.result}"
+ )
+
+ # Set parent task state and result
parent.state = TaskState.DONE
+ parent.result = (
+ "\n\n".join(successful_results)
+ if successful_results
+ else "All subtasks completed"
+ )
+
logger.debug(
f"All subtasks of {parent.id} are done. "
f"Marking parent as complete."
diff --git a/camel/toolkits/slack_toolkit.py b/camel/toolkits/slack_toolkit.py
index c34c7786a..ef776216e 100644
--- a/camel/toolkits/slack_toolkit.py
+++ b/camel/toolkits/slack_toolkit.py
@@ -252,9 +252,6 @@ class SlackToolkit(BaseToolkit):
Returns:
str: A confirmation message indicating whether the message was sent
successfully or an error message.
-
- Raises:
- SlackApiError: If an error occurs while sending the message.
"""
from slack_sdk.errors import SlackApiError
@@ -268,7 +265,10 @@ class SlackToolkit(BaseToolkit):
response = slack_client.chat_postMessage(
channel=channel_id, text=message
)
- return str(response)
+ return (
+ f"Message: {message} sent successfully, "
+ f"got response: {response}"
+ )
except SlackApiError as e:
return f"Error creating conversation: {e.response['error']}"
diff --git a/test/toolkits/test_hybrid_browser_toolkit.py b/test/toolkits/test_hybrid_browser_toolkit.py
index 4d36bb91f..d517807ac 100644
--- a/test/toolkits/test_hybrid_browser_toolkit.py
+++ b/test/toolkits/test_hybrid_browser_toolkit.py
@@ -406,7 +406,7 @@ class TestHybridBrowserToolkit:
result = await toolkit.open_browser()
- assert result["result"] == "Browser session started."
+ assert result["result"] == "Visited test URL"
assert "snapshot" in result
@pytest.mark.asyncio
@@ -1124,8 +1124,8 @@ class TestHybridBrowserToolkit:
tools = toolkit.get_tools()
- # Default tools should be 5 tools (updated default configuration)
- assert len(tools) == 5
+ # Default tools should be 6 tools
+ assert len(tools) == 6
tool_names = [tool.func.__name__ for tool in tools]
expected_default_tools = [
@@ -1149,9 +1149,9 @@ class TestHybridBrowserToolkit:
tools = toolkit.get_tools()
- # Default tools should be 5, even with web_agent_model set
+ # Default tools should be 6, even with web_agent_model set
# unless solve_task is explicitly enabled
- assert len(tools) == 5
+ assert len(tools) == 6
tool_names = [tool.func.__name__ for tool in tools]
# Should not automatically include solve_task unless explicitly enabled
@@ -1344,5 +1344,5 @@ class TestHybridBrowserToolkit:
# Test a simple async operation
result = await toolkit.open_browser()
- assert result["result"] == "Browser session started."
+ assert result["result"] == "Visited test URL"
assert "snapshot" in result
diff --git a/test/toolkits/test_slack_functions.py b/test/toolkits/test_slack_functions.py
index 6304e5935..e4ec7e4cf 100644
--- a/test/toolkits/test_slack_functions.py
+++ b/test/toolkits/test_slack_functions.py
@@ -118,7 +118,10 @@ def test_send_slack_message(slack_toolkit):
mock_login.return_value = mock_client
mock_client.chat_postMessage.return_value = {}
response = slack_toolkit.send_slack_message("test_message", "123")
- assert response == "{}"
+ assert (
+ response
+ == "Message: test_message sent successfully, got response: {}"
+ )
def test_delete_slack_message(slack_toolkit):