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.

  1. Agent 1 started at 07:44:41.785
  2. Agent 2 started at 07:44:41.785
  3. Agent 1 finished at 07:44:44.788
  4. Agent 2 finished at 07:44:44.789
  1. import asyncio
  2. from datetime import datetime
  3. from typing import Any
  4. from agentscope.agent import AgentBase
  5. class ExampleAgent(AgentBase):
  6. """The example agent for concurrent execution."""
  7. def __init__(self, name: str) -> None:
  8. """Initialize the agent with its name."""
  9. super().__init__()
  10. self.name = name
  11. async def reply(self, *args: Any, **kwargs: Any) -> None:
  12. """Reply to the message."""
  13. start_time = datetime.now().strftime("%H:%M:%S.%f")[:-3]
  14. print(f"{self.name} started at {start_time}")
  15. await asyncio.sleep(3) # Simulate a long-running task
  16. end_time = datetime.now().strftime("%H:%M:%S.%f")[:-3]
  17. print(f"{self.name} finished at {end_time}")
  18. async def run_concurrent_agents() -> None:
  19. """Run the concurrent agents."""
  20. agent1 = ExampleAgent("Agent 1")
  21. agent2 = ExampleAgent("Agent 2")
  22. await asyncio.gather(agent1(), agent2())
  23. asyncio.run(run_concurrent_agents())

Total running time of the script: (0 minutes 3.005 seconds)

Download Jupyter notebook: workflow_concurrent_agents.ipynb

Download Python source code: workflow_concurrent_agents.py

Download zipped: workflow_concurrent_agents.zip

Gallery generated by Sphinx-Gallery