.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "tutorial/workflow_concurrent_agents.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_tutorial_workflow_concurrent_agents.py: Concurrent Agents =================================== With the help of asynchronous programming, the concurrent agents can be executed by ``asyncio.gather`` in Python. A simple example is shown below, where two agents are created and executed concurrently. .. GENERATED FROM PYTHON SOURCE LINES 9-42 .. rst-class:: sphx-glr-script-out .. code-block:: none Agent 1 started at 10:11:23.896 Agent 2 started at 10:11:23.897 Agent 1 finished at 10:11:26.900 Agent 2 finished at 10:11:26.900 | .. code-block:: Python import asyncio from datetime import datetime from typing import Any from agentscope.agent import AgentBase class ExampleAgent(AgentBase): """The example agent for concurrent execution.""" def __init__(self, name: str) -> None: """Initialize the agent with its name.""" super().__init__() self.name = name async def reply(self, *args: Any, **kwargs: Any) -> None: """Reply to the message.""" start_time = datetime.now().strftime("%H:%M:%S.%f")[:-3] print(f"{self.name} started at {start_time}") await asyncio.sleep(3) # Simulate a long-running task end_time = datetime.now().strftime("%H:%M:%S.%f")[:-3] print(f"{self.name} finished at {end_time}") async def run_concurrent_agents() -> None: """Run the concurrent agents.""" agent1 = ExampleAgent("Agent 1") agent2 = ExampleAgent("Agent 2") await asyncio.gather(agent1(), agent2()) asyncio.run(run_concurrent_agents()) .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 3.005 seconds) .. _sphx_glr_download_tutorial_workflow_concurrent_agents.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: workflow_concurrent_agents.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: workflow_concurrent_agents.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: workflow_concurrent_agents.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_