Skip to content

Build and run agents you can see, understand and trust.

Add multi-agent concurrent example (#693)

qbcc0ca74ac1dbf
diff --git a/README.md b/README.md
index 469525665..a9616f9e5 100644
--- a/README.md
+++ b/README.md
@@ -348,6 +348,7 @@ as_studio
- Workflow
- [Multi-agent Debate](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_debate)
- [Multi-agent Conversation](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_conversation)
+ - [Multi-agent Concurrent](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_concurrent)
- Evaluation
- [ACEBench](https://github.com/agentscope-ai/agentscope/tree/main/examples/evaluation/ace_bench)
- Functional
diff --git a/README_zh.md b/README_zh.md
index bd946b435..95c1ab8c0 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -350,6 +350,7 @@ as_studio
- 工作流
- [多智能体辩论](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_debate)
- [多智能体对话](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_conversation)
+ - [多智能体并发](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_concurrent)
- 评测
- [ACEBench](https://github.com/agentscope-ai/agentscope/tree/main/examples/evaluation/ace_bench)
- 功能演示
diff --git a/examples/workflows/multiagent_concurrent/README.md b/examples/workflows/multiagent_concurrent/README.md
new file mode 100644
index 000000000..e487c7054
--- /dev/null
+++ b/examples/workflows/multiagent_concurrent/README.md
@@ -0,0 +1,29 @@
+# Multiagent Concurrent
+
+This example demonstrates how to run multiple agents concurrently in AgentScope, where each agent operates
+independently and can perform tasks simultaneously.
+
+Specifically, we showcase two ways to achieve concurrency:
+
+- Using Python's `asyncio.gather` to run multiple agents asynchronously.
+- Using `fanout_pipeline` to execute multiple agents in parallel and gather their results.
+
+The fanout pipeline will distribute the input to multiple agents and collect their outputs, which is appropriate for
+scenarios like voting or parallel question answering.
+
+## QuickStart
+
+Install the agentscope package if you haven't already:
+
+```bash
+pip install agentscope
+```
+
+Then run the example script:
+
+```bash
+python main.py
+```
+
+## Further Reading
+- [Pipelines](https://doc.agentscope.io/tutorial/task_pipeline.html)
diff --git a/examples/workflows/multiagent_concurrent/main.py b/examples/workflows/multiagent_concurrent/main.py
new file mode 100644
index 000000000..226e22f50
--- /dev/null
+++ b/examples/workflows/multiagent_concurrent/main.py
@@ -0,0 +1,93 @@
+# -*- coding: utf-8 -*-
+"""Parallel Multi-Perspective Discussion System."""
+import asyncio
+from datetime import datetime
+from typing import Any
+
+import numpy as np
+
+from agentscope.agent import AgentBase
+from agentscope.message import Msg
+from agentscope.pipeline import fanout_pipeline
+
+
+class ExampleAgent(AgentBase):
+ """The example agent used to label the time."""
+
+ def __init__(self, name: str) -> None:
+ """The constructor of the example agent
+
+ Args:
+ name (`str`):
+ The agent name.
+ """
+ super().__init__()
+ self.name = name
+
+ async def reply(self, *args: Any, **kwargs: Any) -> Msg:
+ """The reply function of the example agent."""
+ # we record the start time
+ start_time = datetime.now()
+ await self.print(
+ Msg(
+ self.name,
+ f"begins at {start_time.strftime('%H:%M:%S.%f')}",
+ "assistant",
+ ),
+ )
+
+ # Sleep some time
+ await asyncio.sleep(np.random.choice([2, 3, 4]))
+
+ end_time = datetime.now()
+ msg = Msg(
+ self.name,
+ f"finishes at {end_time.strftime('%H:%M:%S.%f')}",
+ "user",
+ # Add some metadata for demonstration
+ metadata={
+ "time": (end_time - start_time).total_seconds(),
+ },
+ )
+ await self.print(msg)
+ return msg
+
+ async def handle_interrupt(
+ self,
+ *args: Any,
+ **kwargs: Any,
+ ) -> Msg:
+ """We leave this function unimplemented in this example, because we
+ won't use the interrupt functionality"""
+
+ async def observe(self, *args: Any, **kwargs: Any) -> None:
+ """Similar with the handle_interrupt function, leaving this empty"""
+
+
+async def main() -> None:
+ """The main entry of the concurrent example."""
+ alice = ExampleAgent("Alice")
+ bob = ExampleAgent("Bob")
+ chalice = ExampleAgent("Chalice")
+
+ print("Use 'asyncio.gather' to run the agents concurrently:")
+ futures = [alice(), bob(), chalice()]
+
+ await asyncio.gather(*futures)
+
+ print("\n\nUse fanout pipeline to run the agents concurrently:")
+ collected_res = await fanout_pipeline(
+ agents=[alice, bob, chalice],
+ enable_gather=True,
+ )
+ # Print the collected results
+ print("\n\nThe collected time used by each agent:")
+ for res in collected_res:
+ print(f"{res.name}: {res.metadata['time']} seconds")
+
+ print("\nThe average time used:")
+ avg_time = np.mean([res.metadata["time"] for res in collected_res])
+ print(f"{avg_time} seconds")
+
+
+asyncio.run(main())