🐫 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: update workforce process task to async, add eigent example (#2635)
Wendong-Fana88165103f68
diff --git a/camel/societies/workforce/prompts.py b/camel/societies/workforce/prompts.pyindex 07c19cad2..f4c794009 100644--- a/camel/societies/workforce/prompts.py+++ b/camel/societies/workforce/prompts.py@@ -182,8 +182,12 @@ Now you should summarize the scenario and return the result of the task.""")-WF_TASK_DECOMPOSE_PROMPT = r"""You need to split the given task into-subtasks according to the workers available in the group.+WF_TASK_DECOMPOSE_PROMPT = r"""You need to decompose the given task into subtasks according to the workers available in the group, following these important principles:++1. Keep tasks that are sequential and require the same type of worker together in one subtask+2. Only decompose tasks that can be handled in parallel and require different types of workers+3. This ensures efficient execution by minimizing context switching between workers+The content of the task is:==============================@@ -210,5 +214,9 @@ You must return the subtasks in the format of a numbered list within <tasks> tag<task>Subtask 2</task></tasks>-Though it's not a must, you should try your best effort to make each subtask achievable for a worker. The tasks should be clear and concise.+Each subtask should be:+- Clear and concise+- Achievable by a single worker+- 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"""diff --git a/camel/societies/workforce/utils.py b/camel/societies/workforce/utils.pyindex 235effed4..f535c9fe1 100644--- a/camel/societies/workforce/utils.py+++ b/camel/societies/workforce/utils.py@@ -62,24 +62,101 @@ class TaskAssignResult(BaseModel):)-def check_if_running(running: bool) -> Callable:- r"""Check if the workforce is (not) running, specified the boolean value.- If the workforce is not in the expected status, raise an exception.+def check_if_running(+ running: bool,+ max_retries: int = 3,+ retry_delay: float = 1.0,+ handle_exceptions: bool = False,+) -> Callable:+ r"""Check if the workforce is (not) running, specified by the boolean+ value. Provides fault tolerance through automatic retries and exception+ handling.++ Args:+ running (bool): Expected running state (True or False).+ max_retries (int, optional): Maximum number of retry attempts if the+ operation fails. Set to 0 to disable retries. (default: :obj:`3`)+ retry_delay (float, optional): Delay in seconds between retry attempts.+ (default: :obj:`1.0`)+ handle_exceptions (bool, optional): If True, catch and log exceptions+ instead of propagating them. (default: :obj:`False`)Raises:- RuntimeError: If the workforce is not in the expected status.+ RuntimeError: If the workforce is not in the expected status and+ retries are exhausted or disabled.+ Exception: Any exception raised by the decorated function if+ handle_exceptions is False and retries are exhausted."""+ import logging+ import time++ logger = logging.getLogger(__name__)def decorator(func):@wraps(func)def wrapper(self, *args, **kwargs):- if self._running != running:- status = "not running" if running else "running"- raise RuntimeError(- f"The workforce is {status}. Cannot perform the "- f"operation {func.__name__}."+ retries = 0+ last_exception = None++ while retries <= max_retries:+ try:+ # Check running state+ if self._running != running:+ status = "not running" if running else "running"+ error_msg = (+ f"The workforce is {status}. Cannot perform the "+ f"operation {func.__name__}."+ )++ # If we have retries left, wait and try again+ if retries < max_retries:+ logger.warning(+ f"{error_msg} Retrying in {retry_delay}s... "+ f"(Attempt {retries+1}/{max_retries})"+ )+ time.sleep(retry_delay)+ retries += 1+ continue+ else:+ raise RuntimeError(error_msg)++ return func(self, *args, **kwargs)++ except Exception as e:+ last_exception = e++ if isinstance(e, RuntimeError) and "workforce is" in str(+ e+ ):+ raise++ if retries < max_retries:+ logger.warning(+ f"Exception in {func.__name__}: {e}. "+ f"Retrying in {retry_delay}s... "+ f"(Attempt {retries+1}/{max_retries})"+ )+ time.sleep(retry_delay)+ retries += 1+ else:+ if handle_exceptions:+ logger.error(+ f"Failed to execute {func.__name__} after "+ f"{max_retries} retries: {e}"+ )+ return None+ else:+ # Re-raise the exception+ raise++ # This should not be reached, but just in case+ if handle_exceptions:+ logger.error(+ f"Unexpected failure in {func.__name__}: {last_exception}")- return func(self, *args, **kwargs)+ return None+ else:+ raise last_exceptionreturn wrapperdiff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.pyindex 074536225..020e2a524 100644--- a/camel/societies/workforce/workforce.py+++ b/camel/societies/workforce/workforce.py@@ -41,7 +41,12 @@ from camel.societies.workforce.utils import ()from camel.societies.workforce.worker import Workerfrom camel.tasks.task import Task, TaskState, validate_task_content-from camel.toolkits import CodeExecutionToolkit, SearchToolkit, ThinkingToolkit+from camel.toolkits import (+ CodeExecutionToolkit,+ SearchToolkit,+ TaskPlanningToolkit,+ ThinkingToolkit,+)from camel.types import ModelPlatformType, ModelTypefrom camel.utils import dependencies_required@@ -102,6 +107,7 @@ class Workforce(BaseNode):Example:>>> # Configure with custom model and shared memory+ >>> import asyncio>>> model = ModelFactory.create(... ModelPlatformType.OPENAI, ModelType.GPT_4O... )@@ -113,8 +119,11 @@ class Workforce(BaseNode):... )>>>>>> # Process a task- >>> task = Task(content="Research AI trends", id="1")- >>> result = workforce.process_task(task)+ >>> async def main():+ ... task = Task(content="Research AI trends", id="1")+ ... result = await workforce.process_task(task)+ ... return result+ >>> asyncio.run(main())"""def __init__(@@ -182,14 +191,23 @@ class Workforce(BaseNode):"a new worker for a task, etc.",)self.coordinator_agent = ChatAgent(- coord_agent_sys_msg, **(coordinator_agent_kwargs or {})+ coord_agent_sys_msg,+ **(coordinator_agent_kwargs or {}),)task_sys_msg = BaseMessage.make_assistant_message(role_name="Task Planner",- content="You are going to compose and decompose tasks.",+ content="You are going to compose and decompose tasks. Keep "+ "tasks that are sequential and require the same type of "+ "agent together in one agent process. Only decompose tasks "+ "that can be handled in parallel and require different types "+ "of agents. This ensures efficient execution by minimizing "+ "context switching between agents.",)- self.task_agent = ChatAgent(task_sys_msg, **(task_agent_kwargs or {}))+ _kwargs = dict(task_agent_kwargs or {})+ extra_tools = TaskPlanningToolkit().get_tools()+ _kwargs["tools"] = [*_kwargs.get("tools", []), *extra_tools]+ self.task_agent = ChatAgent(task_sys_msg, **_kwargs)# If there is one, will set by the workforce class wrapping thisself._task: Optional[Task] = None@@ -351,7 +369,7 @@ class Workforce(BaseNode):return subtasks@check_if_running(False)- def process_task(self, task: Task) -> Task:+ async def process_task(self, task: Task) -> Task:r"""The main entry point for the workforce to process a task. It willstart the workforce and all the child nodes under it, process thetask provided and return the updated task.@@ -387,7 +405,7 @@ class Workforce(BaseNode):self.set_channel(TaskChannel())- asyncio.run(self.start())+ await self.start()if subtasks:task.result = "\n\n".join(@@ -974,7 +992,9 @@ class Workforce(BaseNode):workforce_instance = self# Define functions first- def process_task(task_content, task_id=None, additional_info=None):+ async def process_task(+ task_content, task_id=None, additional_info=None+ ):r"""Process a task using the workforce.Args:@@ -996,7 +1016,8 @@ class Workforce(BaseNode):- message (str): Error message if status is "error"Example:- >>> result = process_task("Analyze market trends", "task_001")+ >>> result = await process_task("Analyze market trends",+ "task_001")>>> print(result["status"]) # "success" or "error""""task = Task(@@ -1006,7 +1027,7 @@ class Workforce(BaseNode):)try:- result_task = workforce_instance.process_task(task)+ result_task = await workforce_instance.process_task(task)return {"status": "success","task_id": result_task.id,diff --git a/camel/tasks/task.py b/camel/tasks/task.pyindex 00e3e15ec..72158cabe 100644--- a/camel/tasks/task.py+++ b/camel/tasks/task.py@@ -14,11 +14,21 @@import refrom enum import Enum-from typing import Any, Callable, Dict, List, Literal, Optional, Union+from typing import (+ TYPE_CHECKING,+ Any,+ Callable,+ Dict,+ List,+ Literal,+ Optional,+ Union,+)from pydantic import BaseModel-from camel.agents import ChatAgent+if TYPE_CHECKING:+ from camel.agents import ChatAgentfrom camel.logger import get_loggerfrom camel.messages import BaseMessagefrom camel.prompts import TextPrompt@@ -288,7 +298,7 @@ class Task(BaseModel):def decompose(self,- agent: ChatAgent,+ agent: "ChatAgent",prompt: Optional[str] = None,task_parser: Callable[[str, str], List["Task"]] = parse_response,) -> List["Task"]:@@ -323,7 +333,7 @@ class Task(BaseModel):def compose(self,- agent: ChatAgent,+ agent: "ChatAgent",template: TextPrompt = TASK_COMPOSE_PROMPT,result_parser: Optional[Callable[[str], str]] = None,):@@ -472,12 +482,13 @@ class TaskManager:def evolve(self,task: Task,- agent: ChatAgent,+ agent: "ChatAgent",template: Optional[TextPrompt] = None,task_parser: Optional[Callable[[str, str], List[Task]]] = None,) -> Optional[Task]:r"""Evolve a task to a new task.Evolve is only used for data generation.+Args:task (Task): A given task.agent (ChatAgent): An agent that used to evolve the task.diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex df6f5f40f..b12e5e09d 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -76,6 +76,7 @@ from .klavis_toolkit import KlavisToolkitfrom .aci_toolkit import ACIToolkitfrom .playwright_mcp_toolkit import PlaywrightMCPToolkitfrom .wolfram_alpha_toolkit import WolframAlphaToolkit+from .task_planning_toolkit import TaskPlanningToolkit__all__ = [@@ -140,4 +141,5 @@ __all__ = ['PlaywrightMCPToolkit','WolframAlphaToolkit','BohriumToolkit',+ 'TaskPlanningToolkit',]diff --git a/camel/toolkits/code_execution.py b/camel/toolkits/code_execution.pyindex 6a14dbe3e..e87cf5d50 100644--- a/camel/toolkits/code_execution.py+++ b/camel/toolkits/code_execution.py@@ -122,7 +122,7 @@ class CodeExecutionToolkit(BaseToolkit):def execute_command(self, command: str) -> Union[str, tuple[str, str]]:r"""Execute a command can be used to resolve the dependency of the- code.+ code. Useful if there's dependency issues when you try to execute code.Args:command (str): The command to execute.diff --git a/camel/toolkits/playwright_mcp_toolkit.py b/camel/toolkits/playwright_mcp_toolkit.pyindex d26d50ba8..dcb95dc9c 100644--- a/camel/toolkits/playwright_mcp_toolkit.py+++ b/camel/toolkits/playwright_mcp_toolkit.py@@ -62,7 +62,8 @@ class PlaywrightMCPToolkit(BaseToolkit):+ (additional_args or []),}}- }+ },+ timeout=timeout,)async def connect(self):diff --git a/camel/toolkits/pptx_toolkit.py b/camel/toolkits/pptx_toolkit.pyindex b4a49c67f..862903526 100644--- a/camel/toolkits/pptx_toolkit.py+++ b/camel/toolkits/pptx_toolkit.py@@ -260,7 +260,7 @@ class PPTXToolkit(BaseToolkit):provided, the default template will be used. (default: :obj:`None`)"""- import pptx+ from pptx import Presentation# Use template if provided, otherwise create new presentationif template is not None:@@ -270,9 +270,9 @@ class PPTXToolkit(BaseToolkit):f"Template file not found: {template_path}, using ""default template")- presentation = pptx.Presentation()+ presentation = Presentation()else:- presentation = pptx.Presentation(str(template_path))+ presentation = Presentation(str(template_path))# Clear all existing slides by removing them from the slide# listwhile len(presentation.slides) > 0:@@ -280,7 +280,7 @@ class PPTXToolkit(BaseToolkit):presentation.part.drop_rel(rId)del presentation.slides._sldIdLst[-1]else:- presentation = pptx.Presentation()+ presentation = Presentation()slide_width_inch, slide_height_inch = (self._get_slide_width_height_inches(presentation)diff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.pynew file mode 100644index 000000000..3b5aea44a--- /dev/null+++ b/examples/workforce/eigent.py@@ -0,0 +1,397 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import asyncio++from camel.agents.chat_agent import ChatAgent+from camel.messages.base import BaseMessage+from camel.models import BaseModelBackend, ModelFactory+from camel.societies.workforce import Workforce+from camel.tasks.task import Task+from camel.toolkits import (+ AudioAnalysisToolkit,+ CodeExecutionToolkit,+ DalleToolkit,+ FileWriteToolkit,+ HumanToolkit,+ ImageAnalysisToolkit,+ LinkedInToolkit,+ NotionToolkit,+ PlaywrightMCPToolkit,+ PPTXToolkit,+ RedditToolkit,+ SlackToolkit,+ TerminalToolkit,+ TwitterToolkit,+ VideoDownloaderToolkit,+ WhatsAppToolkit,+)+from camel.types import ModelPlatformType, ModelType+++def developer_agent_factory(model: BaseModelBackend, task_id: str):+ r"""Factory for creating a developer agent."""+ tools = [+ *TerminalToolkit().get_tools(),+ *HumanToolkit().get_tools(),+ *CodeExecutionToolkit().get_tools(),+ ]++ system_message = """You are a skilled coding assistant with DIRECT CODE+ EXECUTION CAPABILITIES. You can:+ - 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+ - 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."""++ return ChatAgent(+ system_message=BaseMessage.make_assistant_message(+ role_name="Developer Agent",+ content=system_message,+ ),+ model=model,+ tools=tools,+ )+++async def search_agent_factory(+ model: BaseModelBackend,+ task_id: str,+ playwright_toolkit: PlaywrightMCPToolkit,+):+ r"""Factory for creating a search agent, based on user-provided code+ structure."""+ # search_toolkits = SearchToolkit()+ # browser_toolkits = AsyncBrowserToolkit()+ terminal_toolkits = TerminalToolkit()+ human_toolkits = HumanToolkit()+ tools = [+ # FunctionTool(search_toolkits.search_wiki),+ # # FunctionTool(search_toolkits.search_duckduckgo),+ # # FunctionTool(search_toolkits.search_bing),+ # # FunctionTool(search_toolkits.search_baidu),+ *playwright_toolkit.get_tools(),+ # *browser_toolkits.get_tools(),+ *terminal_toolkits.get_tools(),+ *human_toolkits.get_tools(),+ ]++ system_message = """You are a helpful assistant that can search the web,+ extract webpage content, simulate browser actions, and provide relevant+ information to solve the given task.+ Keep in mind that:+ - Do not be overly confident in your own knowledge. Searching can provide+ a broader perspective and help validate existing knowledge.+ - If one way fails to provide an answer, try other ways or methods. The+ answer does exist.+ - When encountering verification challenges (like login, CAPTCHAs or robot+ checks), you MUST request help using the human toolkit.+ - If the search snippet is unhelpful but the URL comes from an+ authoritative source, try visit the website for more details.+ - For the page you have visited, you should check the subpages of the page+ to see if it can provide more information to solve the task.+ - When looking for specific numerical values (e.g., dollar amounts),+ prioritize reliable sources and avoid relying only on search snippets.+ - When solving tasks that require web searches, check Wikipedia first+ before exploring other websites.+ - You can also simulate browser actions to get more information or verify+ the information you have found.+ - Browser simulation is also helpful for finding target URLs. Browser+ simulation operations do not necessarily need to find specific answers,+ but can also help find web page URLs that contain answers (usually+ difficult to find through simple web searches). You can find the answer to+ the question by performing subsequent operations on the URL, such as+ extracting the content of the webpage.+ - Do not solely rely on document tools or browser simulation to find the+ answer, you should combine document tools and browser simulation to+ comprehensively process web page information. Some content may need to do+ browser simulation to get, or some content is rendered by javascript.+ - In your response, you should mention the urls you have visited and+ processed.++Here are some tips that help you perform web search:+- Never add too many keywords in your search query! Some detailed results need+ to perform browser interaction to get, not using search toolkit.+- If the question is complex, search results typically do not provide precise+ answers. It is not likely to find the answer directly using search toolkit+ only, the search query should be concise and focuses on finding official+ sources rather than direct answers.+ For example, as for the question "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 must be coarse-grained like "National Geographic YouTube" to+ find the youtube website first, and then try other fine-grained search+ terms step-by-step to find more urls.+- The results you return do not have to directly answer the original question,+ you only need to collect relevant information.++ """++ return ChatAgent(+ system_message=BaseMessage.make_assistant_message(+ role_name="Document Agent",+ content=system_message,+ ),+ model=model,+ tools=tools,+ )+++def document_agent_factory(model: BaseModelBackend, task_id: str):+ r"""Factory for creating a document agent, based on user-provided code+ structure."""+ tools = [+ *FileWriteToolkit().get_tools(),+ *PPTXToolkit().get_tools(),+ # *RetrievalToolkit().get_tools(),+ *HumanToolkit().get_tools(),+ ]++ system_message = """You are a Document Processing Assistant specialized in+ creating, modifying, and managing various document formats. Your+ capabilities include:++ 1. Document Creation & Editing:+ - Create and write to various file formats including Markdown (.md),+ Word documents (.docx), PDFs, CSV files, JSON, YAML, and HTML+ - Apply formatting options including custom encoding, font styles, and+ layout settings+ - Modify existing files with automatic backup functionality+ - Support for mathematical expressions in PDF documents through LaTeX+ rendering++ 2. PowerPoint Presentation Creation:+ - Create professional PowerPoint presentations with title slides and+ content slides+ - Format text with bold and italic styling+ - Create bullet point lists with proper hierarchical structure+ - Support for step-by-step process slides with visual indicators+ - Create tables with headers and rows of data+ - Support for custom templates and slide layouts++ 3. Human Interaction:+ - Ask questions to users and receive their responses+ - Send informative messages to users without requiring responses++ When working with documents, you should:+ - Suggest appropriate file formats based on content requirements+ - Maintain proper formatting and structure in all created documents+ - Provide clear feedback about document creation and modification processes+ - Ask clarifying questions when user requirements are ambiguous+ - Recommend best practices for document organization and presentation++ Your goal is to help users efficiently create, modify, and manage their+ documents with professional quality and appropriate formatting."""++ return ChatAgent(+ system_message=BaseMessage.make_assistant_message(+ role_name="Document Agent",+ content=system_message,+ ),+ model=model,+ tools=tools,+ )+++def multi_modal_agent_factory(model: BaseModelBackend, task_id: str):+ r"""Factory for creating a multi modal agent, based on user-provided code+ structure."""+ tools = [+ *VideoDownloaderToolkit().get_tools(),+ *AudioAnalysisToolkit().get_tools(),+ *ImageAnalysisToolkit().get_tools(),+ *DalleToolkit().get_tools(),+ *HumanToolkit().get_tools(),+ ]++ system_message = """You are a Multi-Modal Processing Assistant specialized+ in analyzing and generating various types of media content. Your+ capabilities include:++ 1. Audio Analysis & Processing:+ - Transcribe speech from audio files to text with high accuracy+ - Answer specific questions about audio content+ - Process audio from both local files and URLs+ - Handle various audio formats including MP3, WAV, and OGG++ 2. Image Analysis & Understanding:+ - Generate detailed descriptions of image content+ - Answer specific questions about images+ - Identify objects, text, people, and scenes in images+ - Process images from both local files and URLs++ 3. Image Generation:+ - Create high-quality images based on detailed text prompts using DALL-E+ - Generate images in 1024x1792 resolution+ - Save generated images to specified directories++ 4. Human Interaction:+ - Ask questions to users and receive their responses+ - Send informative messages to users without requiring responses++ When working with multi-modal content, you should:+ - Provide detailed and accurate descriptions of media content+ - Extract relevant information based on user queries+ - Generate appropriate media when requested+ - Explain your analysis process and reasoning+ - Ask clarifying questions when user requirements are ambiguous++ Your goal is to help users effectively process, understand, and create+ multi-modal content across audio and visual domains."""++ return ChatAgent(+ system_message=BaseMessage.make_assistant_message(+ role_name="Multi Modal Agent",+ content=system_message,+ ),+ model=model,+ tools=tools,+ )+++def social_medium_agent_factory(model: BaseModelBackend, task_id: str):+ r"""Factory for creating a social medium agent."""+ return ChatAgent(+ BaseMessage.make_assistant_message(+ role_name="Social Medium Agent",+ content="""You are a Social Media Management Assistant with+ comprehensive capabilities across multiple platforms. Your+ integrated toolkits enable you to:++1. WhatsApp Business Management (WhatsAppToolkit):+ - Send text messages to customers via the WhatsApp Business API+ - Send template messages for standardized communications+ - Retrieve business profile information++2. Twitter Account Management (TwitterToolkit):+ - Create tweets with text content (respecting character limits)+ - Create tweets with polls or as quote tweets+ - Delete existing tweets+ - Retrieve user profile information++3. LinkedIn Professional Networking (LinkedInToolkit):+ - Create posts on LinkedIn (respecting character limits)+ - Delete existing posts (with user confirmation)+ - Retrieve authenticated user's profile information++4. Reddit Content Analysis (RedditToolkit):+ - Collect top posts and comments from specified subreddits+ - Perform sentiment analysis on Reddit comments+ - Track keyword discussions across multiple subreddits++5. Notion Workspace Management (NotionToolkit):+ - List all pages in a Notion workspace+ - List all users with access to the workspace+ - Retrieve and extract text content from Notion blocks++6. Slack Workspace Interaction (SlackToolkit):+ - Create new Slack channels (public or private)+ - Join or leave existing channels+ - Send and delete messages in channels+ - Retrieve channel information and message history++7. Human Interaction (HumanToolkit):+ - Ask questions to users via console+ - Send messages to users via console++When assisting users, always:+1. Identify which platform's functionality is needed for the task+2. Check if required API credentials are available before attempting operations+3. Provide clear explanations of what actions you're taking+4. Handle rate limits and API restrictions appropriately+5. Ask clarifying questions when user requests are ambiguous""",+ ),+ model=model,+ tools=[+ *WhatsAppToolkit().get_tools(),+ *TwitterToolkit().get_tools(),+ *LinkedInToolkit().get_tools(),+ *RedditToolkit().get_tools(),+ *NotionToolkit().get_tools(),+ *SlackToolkit().get_tools(),+ *HumanToolkit().get_tools(),+ ],+ )+++async def main():+ playwright_toolkit = PlaywrightMCPToolkit() # Create instance+ try:+ await playwright_toolkit.connect() # Connect the instance++ # Create a single model backend for all agents+ model_backend = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ )++ task_id = 'workforce_task'++ # Create agents using factory functions+ search_agent = await search_agent_factory(+ model_backend, task_id, playwright_toolkit+ )+ developer_agent = developer_agent_factory(model_backend, task_id)+ document_agent = document_agent_factory(model_backend, task_id)+ multi_modal_agent = multi_modal_agent_factory(model_backend, task_id)+ # social_medium_agent = social_medium_agent_factory(model_backend,+ # task_id)++ workforce = Workforce(+ 'A workforce',+ graceful_shutdown_timeout=30.0, # 30 seconds for debugging+ share_memory=False,+ )++ workforce.add_single_agent_worker(+ "Search & Information Retrieval Agent", worker=search_agent+ ).add_single_agent_worker(+ "Software Development & Code Generation Agent",+ worker=developer_agent,+ ).add_single_agent_worker(+ "Document Creation & Management Agent", worker=document_agent+ ).add_single_agent_worker(+ "Multi-Modal Content Analysis & Generation Agent",+ worker=multi_modal_agent,+ )++ # specify the task to be solved+ human_task = Task(+ content=(+ """+ I want to read papers about GUI Agent. Please help me find+ ten papers, check the detailed content of the papers and help+ me write a comparison report, then create a nice slides(pptx)+ to introduce the latest research progress of GUI Agent.+ """+ ),+ id='0',+ )++ task = await workforce.process_task(human_task)+ print('Final Result of Original task:\n', task.result)+ finally:+ await playwright_toolkit.disconnect() # Disconnect the same instance+++if __name__ == "__main__":+ asyncio.run(main())