🐫 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
feat: enhance_workforce_human_in_the_loop (#2757)
Tao Sun13d623181c45
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex e9f9151a0..5bc13d4f9 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -13,10 +13,12 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========from __future__ import annotations+import asyncioimport jsonimport loggingimport textwrapimport threading+import timeimport uuidfrom collections import defaultdictfrom pathlib import Path@@ -175,6 +177,9 @@ class ChatAgent(BaseAgent):terminate its execution. (default: :obj:`None`)mask_tool_output (Optional[bool]): Whether to return a sanitizedplaceholder instead of the raw tool output. (default: :obj:`False`)+ pause_event (Optional[asyncio.Event]): Event to signal pause of the+ agent's operation. When clear, the agent will pause its execution.+ (default: :obj:`None`)"""def __init__(@@ -209,6 +214,7 @@ class ChatAgent(BaseAgent):agent_id: Optional[str] = None,stop_event: Optional[threading.Event] = None,mask_tool_output: bool = False,+ pause_event: Optional[asyncio.Event] = None,) -> None:if isinstance(model, ModelManager):self.model_backend = model@@ -285,6 +291,7 @@ class ChatAgent(BaseAgent):self.stop_event = stop_eventself.mask_tool_output = mask_tool_outputself._secure_result_store: Dict[str, Any] = {}+ self.pause_event = pause_eventdef reset(self):r"""Resets the :obj:`ChatAgent` to its initial state."""@@ -1148,6 +1155,10 @@ class ChatAgent(BaseAgent):iteration_count = 0while True:+ if self.pause_event is not None and not self.pause_event.is_set():+ while not self.pause_event.is_set():+ time.sleep(0.001)+try:openai_messages, num_tokens = self.memory.get_context()accumulated_context_tokens += num_tokens@@ -1189,6 +1200,12 @@ class ChatAgent(BaseAgent):external_tool_call_requests = []external_tool_call_requests.append(tool_call_request)else:+ if (+ self.pause_event is not None+ and not self.pause_event.is_set()+ ):+ while not self.pause_event.is_set():+ time.sleep(0.001)tool_call_records.append(self._execute_tool(tool_call_request))@@ -1292,6 +1309,8 @@ class ChatAgent(BaseAgent):step_token_usage = self._create_token_usage_tracker()iteration_count = 0while True:+ if self.pause_event is not None and not self.pause_event.is_set():+ await self.pause_event.wait()try:openai_messages, num_tokens = self.memory.get_context()accumulated_context_tokens += num_tokens@@ -1333,6 +1352,11 @@ class ChatAgent(BaseAgent):external_tool_call_requests = []external_tool_call_requests.append(tool_call_request)else:+ if (+ self.pause_event is not None+ and not self.pause_event.is_set()+ ):+ await self.pause_event.wait()tool_call_record = await self._aexecute_tool(tool_call_request)@@ -2173,6 +2197,7 @@ class ChatAgent(BaseAgent):),max_iteration=self.max_iteration,stop_event=self.stop_event,+ pause_event=self.pause_event,)# Copy memory if requesteddiff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.pyindex ffbca232e..fcc1e3e28 100644--- a/camel/societies/workforce/workforce.py+++ b/camel/societies/workforce/workforce.py@@ -395,6 +395,40 @@ class Workforce(BaseNode):"better context continuity during task handoffs.")+ # ------------------------------------------------------------------+ # Helper for propagating pause control to externally supplied agents+ # ------------------------------------------------------------------++ def _attach_pause_event_to_agent(self, agent: ChatAgent) -> None:+ r"""Ensure the given ChatAgent shares this workforce's pause_event.++ If the agent already has a different pause_event we overwrite it and+ emit a debug log (it is unlikely an agent needs multiple independent+ pause controls once managed by this workforce)."""+ try:+ existing_pause_event = getattr(agent, "pause_event", None)+ if existing_pause_event is not self._pause_event:+ if existing_pause_event is not None:+ logger.debug(+ f"Overriding pause_event for agent {agent.agent_id} "+ f"(had different pause_event: "+ f"{id(existing_pause_event)} "+ f"-> {id(self._pause_event)})"+ )+ agent.pause_event = self._pause_event+ except AttributeError:+ # Should not happen, but guard against unexpected objects+ logger.warning(+ f"Cannot attach pause_event to object {type(agent)} - "+ f"missing pause_event attribute"+ )++ def _ensure_pause_event_in_kwargs(self, kwargs: Optional[Dict]) -> Dict:+ r"""Insert pause_event into kwargs dict for ChatAgent construction."""+ new_kwargs = dict(kwargs) if kwargs else {}+ new_kwargs.setdefault("pause_event", self._pause_event)+ return new_kwargs+def __repr__(self):return (f"Workforce {self.node_id} ({self.description}) - "@@ -1138,6 +1172,9 @@ class Workforce(BaseNode):Returns:Workforce: The workforce node itself."""+ # Ensure the worker agent shares this workforce's pause control+ self._attach_pause_event_to_agent(worker)+worker_node = SingleAgentWorker(description=description,worker=worker,@@ -1184,6 +1221,18 @@ class Workforce(BaseNode):Returns:Workforce: The workforce node itself."""+ # 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(+ assistant_agent_kwargs+ )+ user_agent_kwargs = self._ensure_pause_event_in_kwargs(+ user_agent_kwargs+ )+ summarize_agent_kwargs = self._ensure_pause_event_in_kwargs(+ summarize_agent_kwargs+ )+worker_node = RolePlayingWorker(description=description,assistant_role_name=assistant_role_name,@@ -1212,6 +1261,9 @@ class Workforce(BaseNode):Returns:Workforce: The workforce node itself."""+ # 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)return self@@ -1245,14 +1297,17 @@ class Workforce(BaseNode):# Handle asyncio.Event in a thread-safe wayif self._loop and not self._loop.is_closed():# If we have a loop, use it to set the event safely- asyncio.run_coroutine_threadsafe(- self._async_reset(), self._loop- ).result()- else:try:- self._reset_task = asyncio.create_task(self._async_reset())- except RuntimeError:- asyncio.run(self._async_reset())+ asyncio.run_coroutine_threadsafe(+ self._async_reset(), self._loop+ ).result()+ except RuntimeError as e:+ logger.warning(f"Failed to reset via existing loop: {e}")+ # Fallback to direct event manipulation+ self._pause_event.set()+ else:+ # No active loop, directly set the event+ self._pause_event.set()if hasattr(self, 'metrics_logger') and self.metrics_logger is not None:self.metrics_logger.reset_task_data()@@ -1656,7 +1711,12 @@ class Workforce(BaseNode):model_config_dict={"temperature": 0},)- return ChatAgent(worker_sys_msg, model=model, tools=function_list) # type: ignore[arg-type]+ return ChatAgent(+ worker_sys_msg,+ model=model,+ tools=function_list, # type: ignore[arg-type]+ pause_event=self._pause_event,+ )async def _get_returned_task(self) -> Optional[Task]:r"""Get the task that's published by this node and just get returneddiff --git a/examples/workforce/human_in_the_loop/simple_hotkey_demo.py b/examples/workforce/human_in_the_loop/simple_hotkey_demo.pyindex b6713d311..43e39f220 100644--- a/examples/workforce/human_in_the_loop/simple_hotkey_demo.py+++ b/examples/workforce/human_in_the_loop/simple_hotkey_demo.py@@ -132,10 +132,10 @@ def simple_intervention_menu(workforce: Workforce):return Falseelse:- print("❌ Invalid choice. Please enter 1-6.")+ print("❌ Invalid choice. Please enter 1-5.")except (KeyboardInterrupt, EOFError):- print("\n🔄 Enter 5 to resume or 6 to stop")+ print("\n🔄 Enter 4 to resume or 5 to stop")def main():