Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
Add nine-players werewolf game example in AgentScope (#681)
qbc5ebdcc706e3c
diff --git a/examples/game/werewolf/README.md b/examples/game/werewolf/README.mdnew file mode 100644index 000000000..deb00c15f--- /dev/null+++ b/examples/game/werewolf/README.md@@ -0,0 +1,44 @@+# πΊβοΈπ¨βπΎ Werewolf Game Powered by AgentScope++This is a 9-players werewolf game example built using AgentScope, showcasing **multi-agent interactions**,+**role-based gameplay**, and **structured output handling**.+Specifically, this game is consisted of three villagers, three werewolves, one seer, one witch and one hunter.++## QuickStart++Run the following command to start the game, ensuring you have set up your DashScope API key as an environment variable.++```bash+python main.py+```++> Note:+> - You can adjust the language, model and other parameters in `main.py`.+> - Different models may yield different game experiences.++Running the example with AgentScope Studio provides a more interactive experience.++- Demo Video in Chinese:++[](https://cloud.video.taobao.com/vod/KxyR66_CWaWwu76OPTvOV2Ye1Gas3i5p4molJtzhn_s.mp4)++- Demo Video in English:++[](https://cloud.video.taobao.com/vod/bMiRTfxPg2vm76wEoaIP2eJfkCi8CUExHRas-1LyK1I.mp4)++## Details++The game is built with the ``ReActAgent`` in AgentScope, utilizing its ability to generate structured outputs to+control the game flow and interactions.+We also use the ``MsgHub`` and pipelines in AgentScope to manage the complex interactions like discussion and voting.+It's very interesting to see how agents play the werewolf game with different roles and objectives.++Additionally, you can use the ``UserAgent`` to replace one of the agents to play with AI agents!+++## Further Reading++- [Structured Output](https://doc.agentscope.io/tutorial/task_agent.html#structured-output)+- [MsgHub and Pipelines](https://doc.agentscope.io/tutorial/task_pipeline.html)+- [Prompt Formatter](https://doc.agentscope.io/tutorial/task_prompt.html)+- [AgentScope Studio](https://doc.agentscope.io/tutorial/task_studio.html)diff --git a/examples/game/werewolf/main.py b/examples/game/werewolf/main.pynew file mode 100644index 000000000..af0c544b7--- /dev/null+++ b/examples/game/werewolf/main.py@@ -0,0 +1,326 @@+# -*- coding: utf-8 -*-+# pylint: disable=too-many-branches, too-many-statements, no-name-in-module+"""A werewolf game implemented by agentscope."""+import asyncio+import os++from structured_output import (+ DiscussionModel,+ get_vote_model,+ get_poison_model,+ WitchResurrectModel,+ get_seer_model,+ get_hunter_model,+)+from prompt import Prompts+from utils import (+ check_winning,+ majority_vote,+ get_player_name,+ names_to_str,+ EchoAgent,+ MAX_GAME_ROUND,+ MAX_DISCUSSION_ROUND,+)+from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeMultiAgentFormatter+from agentscope.model import DashScopeChatModel+from agentscope.pipeline import MsgHub, sequential_pipeline, fanout_pipeline++NAME_TO_ROLE = {}+moderator = EchoAgent()+healing, poison = True, True+villagers, werewolves, seer, witch, hunter = [], [], [], [], []+current_alive = []+++async def hunter_stage(+ hunter_agent: ReActAgent,+) -> str | None:+ """Because the hunter's stage may happen in two places: killed at night+ or voted during the day, we define a function here to avoid duplication."""+ global current_alive, moderator+ msg_hunter = await hunter_agent(+ await moderator(Prompts.to_hunter.format(name=hunter_agent.name)),+ structured_model=get_hunter_model(current_alive),+ )+ if msg_hunter.metadata.get("shoot"):+ return msg_hunter.metadata.get("name", None)+ return None+++def update_players(dead_players: list[str]) -> None:+ """Update the global alive players list by removing the dead players."""+ global werewolves, villagers, seer, hunter, witch, current_alive+ werewolves = [_ for _ in werewolves if _.name not in dead_players]+ villagers = [_ for _ in villagers if _.name not in dead_players]+ seer = [_ for _ in seer if _.name not in dead_players]+ hunter = [_ for _ in hunter if _.name not in dead_players]+ witch = [_ for _ in witch if _.name not in dead_players]+ current_alive = [_ for _ in current_alive if _.name not in dead_players]+++async def create_player(role: str) -> ReActAgent:+ """Create a player with the given name and role."""+ name = get_player_name()+ global NAME_TO_ROLE+ NAME_TO_ROLE[name] = role+ agent = ReActAgent(+ name=name,+ sys_prompt=Prompts.system_prompt.format(+ player_name=name,+ guidance=getattr(Prompts, f"notes_{role}"),+ ),+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ enable_thinking=True,+ ),+ formatter=DashScopeMultiAgentFormatter(),+ )+ await agent.observe(+ await moderator(+ f"[{name} ONLY] {name}, your role is {role}.",+ ),+ )+ return agent+++async def main() -> None:+ """The main entry of the werewolf game"""+ # Enable studio if you want+ import agentscope++ agentscope.init(+ studio_url="http://localhost:3000",+ project="Werewolf Game",+ )+ global healing, poison, villagers, werewolves, seer, witch, hunter+ global current_alive+ # Create players+ villagers = [await create_player("villager") for _ in range(3)]+ werewolves = [await create_player("werewolf") for _ in range(3)]+ seer = [await create_player("seer")]+ witch = [await create_player("witch")]+ hunter = [await create_player("hunter")]+ # Speak in order of names+ current_alive = sorted(+ werewolves + villagers + seer + witch + hunter,+ key=lambda _: _.name,+ )++ # Game begin!+ for _ in range(MAX_GAME_ROUND):+ # Create a MsgHub for all players to broadcast messages+ async with MsgHub(+ participants=current_alive,+ enable_auto_broadcast=False, # manual broadcast only+ name="all_players",+ ) as all_players_hub:+ # Night phase+ await all_players_hub.broadcast(+ await moderator(Prompts.to_all_night),+ )+ killed_player, poisoned_player, shot_player = None, None, None++ # Werewolves discuss+ async with MsgHub(+ werewolves,+ enable_auto_broadcast=True,+ announcement=await moderator(+ Prompts.to_wolves_discussion.format(+ names_to_str(werewolves),+ names_to_str(current_alive),+ ),+ ),+ ) as werewolves_hub:+ # Discussion+ res = None+ for _ in range(1, MAX_DISCUSSION_ROUND * len(werewolves) + 1):+ res = await werewolves[_ % len(werewolves)](+ structured_model=DiscussionModel,+ )+ if _ % len(werewolves) == 0 and res.metadata.get(+ "reach_agreement",+ ):+ break++ # Werewolves vote+ # Disable auto broadcast to avoid following other's votes+ werewolves_hub.set_auto_broadcast(False)+ msgs_vote = await fanout_pipeline(+ werewolves,+ msg=await moderator(content=Prompts.to_wolves_vote),+ structured_model=get_vote_model(current_alive),+ enable_gather=False,+ )+ killed_player, votes = majority_vote(+ [_.metadata.get("vote") for _ in msgs_vote],+ )+ # Postpone the broadcast of voting+ await werewolves_hub.broadcast(+ [+ *msgs_vote,+ await moderator(+ Prompts.to_wolves_res.format(votes, killed_player),+ ),+ ],+ )++ # Witch's turn+ await all_players_hub.broadcast(+ await moderator(Prompts.to_all_witch_turn),+ )+ msg_witch_poison = None+ for agent in witch:+ # Cannot heal witch herself+ msg_witch_resurrect = None+ if healing and killed_player != agent.name:+ msg_witch_resurrect = await agent(+ await moderator(+ Prompts.to_witch_resurrect.format(+ witch_name=agent.name,+ dead_name=killed_player,+ ),+ ),+ structured_model=WitchResurrectModel,+ )+ if msg_witch_resurrect.metadata.get("resurrect"):+ killed_player = None+ healing = False++ if poison and not (+ msg_witch_resurrect+ and msg_witch_resurrect.metadata["resurrect"]+ ):+ msg_witch_poison = await agent(+ await moderator(+ Prompts.to_witch_poison.format(+ witch_name=agent.name,+ ),+ ),+ structured_model=get_poison_model(current_alive),+ )+ if msg_witch_poison.metadata.get("poison"):+ poisoned_player = msg_witch_poison.metadata.get("name")+ poison = False++ # Seer's turn+ await all_players_hub.broadcast(+ await moderator(Prompts.to_all_seer_turn),+ )+ for agent in seer:+ msg_seer = await agent(+ await moderator(+ Prompts.to_seer.format(+ agent.name,+ names_to_str(current_alive),+ ),+ ),+ structured_model=get_seer_model(current_alive),+ )+ if msg_seer.metadata.get("name"):+ player = msg_seer.metadata["name"]+ await agent.observe(+ await moderator(+ Prompts.to_seer_result.format(+ agent_name=player,+ role=NAME_TO_ROLE[player],+ ),+ ),+ )++ # Hunter's turn+ for agent in hunter:+ # If killed and not by witch's poison+ if (+ killed_player == agent.name+ and poisoned_player != agent.name+ ):+ shot_player = await hunter_stage(agent)++ # Update alive players+ dead_tonight = [killed_player, poisoned_player, shot_player]+ update_players(dead_tonight)++ # Day phase+ if len([_ for _ in dead_tonight if _]) > 0:+ await all_players_hub.broadcast(+ await moderator(+ Prompts.to_all_day.format(+ names_to_str([_ for _ in dead_tonight if _]),+ ),+ ),+ )+ else:+ await all_players_hub.broadcast(+ await moderator(Prompts.to_all_peace),+ )++ # Check winning+ res = check_winning(current_alive, werewolves)+ if res:+ await moderator(res)+ return++ # Discussion+ await all_players_hub.broadcast(+ await moderator(+ Prompts.to_all_discuss.format(+ names=names_to_str(current_alive),+ ),+ ),+ )+ # Open the auto broadcast to enable discussion+ all_players_hub.set_auto_broadcast(True)+ await sequential_pipeline(current_alive)+ # Disable auto broadcast to avoid leaking info+ all_players_hub.set_auto_broadcast(False)++ # Voting+ msgs_vote = await fanout_pipeline(+ current_alive,+ await moderator(+ Prompts.to_all_vote.format(names_to_str(current_alive)),+ ),+ structured_model=get_vote_model(current_alive),+ enable_gather=False,+ )+ voted_player, votes = majority_vote(+ [_.metadata.get("vote") for _ in msgs_vote],+ )+ await all_players_hub.broadcast(+ [+ *msgs_vote,+ await moderator(+ Prompts.to_all_res.format(votes, voted_player),+ ),+ ],+ )++ shot_player = None+ for agent in hunter:+ if voted_player == agent.name:+ shot_player = await hunter_stage(agent)+ if shot_player:+ await all_players_hub.broadcast(+ await moderator(+ Prompts.to_all_hunter_shoot.format(+ shot_player,+ ),+ ),+ )++ # Update alive players+ dead_today = [voted_player, shot_player]+ update_players(dead_today)++ # Check winning+ res = check_winning(current_alive, werewolves)+ if res:+ await moderator(res)+ return+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/game/werewolf/prompt.py b/examples/game/werewolf/prompt.pynew file mode 100644index 000000000..aef2af796--- /dev/null+++ b/examples/game/werewolf/prompt.py@@ -0,0 +1,171 @@+# -*- coding: utf-8 -*-+# pylint: disable=line-too-long+"""Related prompts"""+++class Prompts:+ """Related prompts"""++ system_prompt = """You're a werewolf game player named {player_name}.++# YOUR TARGET+Your target is to win the game with your teammates as much as possible.++# GAME RULES+- In werewolf game, players are divided into three werewolves, three villagers, one seer, one hunter and one witch.+ - Werewolves: kill one player each night, and must hide identity during the day.+ - Villagers: ordinary players without special abilities, try to identify and eliminate werewolves.+ - Seer: A special villager who can checkone player's identity each night.+ - Witch: A special villager with two one-time-use potions: a healing potion to save a player from being killed at night, and a poison to eliminate one player at night.+ - Hunter: A special villager who can take one player down with them when they are eliminated.+- The game alternates between night and day phases until one side wins:+ - Night Phase+ - Werewolves choose one victim+ - Seer checks one player's identity+ - Witch decides whether to use potions+ - Moderator announces who died during the night+ - Day Phase+ - All players discuss and vote to eliminate one suspected player++# GAME GUIDANCE+- Try your best to win the game with your teammates, tricks, lies, and deception are all allowed, e.g. pretending to be a different role.+- During discussion, don't be political, be direct and to the point.+- The day phase voting provides important clues. For example, the werewolves may vote together, attack the seer, etc.+{guidance}++# NOTE+- [IMPORTANT] DO NOT make up any information that is not provided by the moderator or other players.+- This is a TEXT-based game, so DO NOT use or make up any non-textual information.+- Always critically reflect on whether your evidence exist, and avoid making assumptions.+- Your response should be specific and concise, provide clear reason and avoid unnecessary elaboration.+- Generate your one-line response by using the `generate_response` function.+- Don't repeat the others' speeches.+- Play the game in English.+""" # noqa++ notes_werewolf = """## GAME GUIDANCE FOR WEREWOLF+- Seer is your greatest threat, who can check one player's identity each night. Analyze players' speeches, find out the seer and eliminate him/her will greatly increase your chances of winning.+- In the first night, making random choices is common for werewolves since no information is available.+- Pretending to be other roles (seer, witch or villager) is a common strategy to hide your identity and mislead other villagers in the day phase.+- The outcome of the night phase provides important clues. For example, if witch uses the healing or poison potion, if the dead player is hunter, etc. Use this information to adjust your strategy.""" # noqa++ notes_seer = """## GAME GUIDANCE FOR SEER+- Seer is very important to villagers, exposing yourself too early may lead to being targeted by werewolves.+- Your ability to check one player's identity is crucial.+- The outcome of the night phase provides important clues. For example, if witch uses the healing or poison potion, if the dead player is hunter, etc. Use this information to adjust your strategy.""" # noqa++ notes_witch = """## GAME GUIDANCE FOR WITCH+- Witch has two powerful potions, use them wisely to protect key villagers or eliminate suspected werewolves.+- The outcome of the night phase provides important clues. For example, if the dead player is hunter, etc. Use this information to adjust your strategy.""" # noqa++ notes_hunter = """## GAME GUIDANCE FOR HUNTER+- Using your ability in day phase will expose your role (since only hunter can take one player down)+- The outcome of the night phase provides important clues. For example, if witch uses the healing or poison potion, etc. Use this information to adjust your strategy.""" # noqa++ notes_villager = """## GAME GUIDANCE FOR VILLAGER+- Protecting special villagers, especially the seer, is crucial for your team's success.+- Werewolves may pretend to be the seer. Be cautious and don't trust anyone easily.+- The outcome of the night phase provides important clues. For example, if witch uses the healing or poison potion, if the dead player is hunter, etc. Use this information to adjust your strategy.""" # noqa++ to_all_night = (+ "Night has fallen, everyone close your eyes. Werewolves open your "+ "eyes and choose a player to eliminate tonight."+ )++ to_wolves_discussion = (+ "[WEREWOLVES ONLY] {}, you should discuss and "+ "decide on a player to eliminate tonight. Current alive players "+ "are {}. Remember to set `reach_agreement` to True if you reach an "+ "agreement during the discussion."+ )++ to_wolves_vote = "[WEREWOLVES ONLY] Which player do you vote to kill?"++ to_wolves_res = (+ "[WEREWOLVES ONLY] The voting result is {}. So you have chosen to "+ "eliminate {}."+ )++ to_all_witch_turn = (+ "Witch's turn, witch open your eyes and decide your action tonight."+ )+ to_witch_resurrect = (+ "[WITCH ONLY] {witch_name}, you're the witch, and tonight {dead_name} "+ "is eliminated. You can resurrect him/her by using your healing "+ "potion, "+ "and note you can only use it once in the whole game. Do you want to "+ "resurrect {dead_name}? Give me your reason and decision."+ )++ to_witch_resurrect_no = (+ "[WITCH ONLY] The witch has chosen not to resurrect the player."+ )+ to_witch_resurrect_yes = (+ "[WITCH ONLY] The witch has chosen to resurrect the player."+ )++ to_witch_poison = (+ "[WITCH ONLY] {witch_name}, as a witch, you have a one-time-use "+ "poison potion, do you want to use it tonight? Give me your reason "+ "and decision."+ )++ to_all_seer_turn = (+ "Seer's turn, seer open your eyes and check one player's identity "+ "tonight."+ )++ to_seer = (+ "[SEER ONLY] {}, as the seer you can check one player's identity "+ "tonight. Who do you want to check? Give me your reason and decision."+ )++ to_seer_result = (+ "[SEER ONLY] You've checked {agent_name}, and the result is: {role}."+ )++ to_hunter = (+ "[HUNTER ONLY] {name}, as the hunter you're eliminated tonight. You "+ "can choose one player to take down with you. Also, you can choose "+ "not to use this ability. Give me your reason and decision."+ )++ to_all_hunter_shoot = (+ "The hunter has chosen to shoot {} down with him/herself."+ )++ to_all_day = (+ "The day is coming, all players open your eyes. Last night, "+ "the following player(s) has been eliminated: {}."+ )++ to_all_peace = (+ "The day is coming, all the players open your eyes. Last night is "+ "peaceful, no player is eliminated."+ )++ to_all_discuss = (+ "Now the alive players are {names}. The game goes on, it's time to "+ "discuss and vote a player to be eliminated. Now you each take turns "+ "to speak once in the order of {names}."+ )++ to_all_vote = (+ "Now the discussion is over. Everyone, please vote to eliminate one "+ "player from the alive players: {}."+ )++ to_all_res = "The voting result is {}. So {} has been voted out."++ to_all_wolf_win = (+ "There're {n_werewolves} werewolves alive and {n_villagers} villagers "+ "alive.\n"+ "The game is over and werewolves win!πΊπ"+ )++ to_all_village_win = (+ "All the werewolves have been eliminated.\n"+ "The game is over and villagers win!ποΈπ"+ )++ to_all_continue = "The game goes on."diff --git a/examples/game/werewolf/structured_output.py b/examples/game/werewolf/structured_output.pynew file mode 100644index 000000000..d229d032d--- /dev/null+++ b/examples/game/werewolf/structured_output.py@@ -0,0 +1,89 @@+# -*- coding: utf-8 -*-+"""The structured output models for werewolf game."""+from typing import Literal++from pydantic import BaseModel, Field++from agentscope.agent import AgentBase+++class DiscussionModel(BaseModel):+ """The output format for discussion."""++ reach_agreement: bool = Field(+ description="Whether you have reached an agreement or not",+ )+++def get_vote_model(agents: list[AgentBase]) -> type[BaseModel]:+ """Get the vote model by player names."""++ class VoteModel(BaseModel):+ """The vote output format."""++ vote: Literal[tuple(_.name for _ in agents)] = Field( # type: ignore+ description="The name of the player you want to vote for",+ )++ return VoteModel+++class WitchResurrectModel(BaseModel):+ """The output format for witch resurrect action."""++ resurrect: bool = Field(+ description="Whether you want to resurrect the player",+ )+++def get_poison_model(agents: list[AgentBase]) -> type[BaseModel]:+ """Get the poison model by player names."""++ class WitchPoisonModel(BaseModel):+ """The output format for witch poison action."""++ poison: bool = Field(+ description="Do you want to use the poison potion",+ )+ name: Literal[ # type: ignore+ tuple(_.name for _ in agents)+ ] | None = Field(+ description="The name of the player you want to poison, if you "+ "don't want to poison anyone, just leave it empty",+ default=None,+ )++ return WitchPoisonModel+++def get_seer_model(agents: list[AgentBase]) -> type[BaseModel]:+ """Get the seer model by player names."""++ class SeerModel(BaseModel):+ """The output format for seer action."""++ name: Literal[tuple(_.name for _ in agents)] = Field( # type: ignore+ description="The name of the player you want to check",+ )++ return SeerModel+++def get_hunter_model(agents: list[AgentBase]) -> type[BaseModel]:+ """Get the hunter model by player agents."""++ class HunterModel(BaseModel):+ """The output format for hunter action."""++ shoot: bool = Field(+ description="Whether you want to use the shooting ability or not",+ )+ name: Literal[ # type: ignore+ tuple(_.name for _ in agents)+ ] | None = Field(+ description="The name of the player you want to shoot, if you "+ "don't want to the ability, just leave it empty",+ default=None,+ )++ return HunterModeldiff --git a/examples/game/werewolf/utils.py b/examples/game/werewolf/utils.pynew file mode 100644index 000000000..a27d728b4--- /dev/null+++ b/examples/game/werewolf/utils.py@@ -0,0 +1,131 @@+# -*- coding: utf-8 -*-+"""Utility functions for the werewolf game."""+from typing import Any++import numpy as np++from prompt import Prompts++from agentscope.message import Msg+from agentscope.agent import ReActAgent, AgentBase++MAX_GAME_ROUND = 30+MAX_DISCUSSION_ROUND = 3++candidate_names = [+ "Batman",+ "Superman",+ "Joker",+ "Luoji",+ "Turing",+ "Einstein",+ "Newton",+ "Musk",+ "Jarvis",+ "Friday",+ "Spiderman",+ "Captain",+ "Harry",+ "Hermione",+ "Ron",+ "Gandalf",+ "Voldemort",+ "Frodo",+ "Aragorn",+ "Legolas",+ "Geralt",+ "Yennefer",+ "Triss",+ "Ciri",+ "Yeye",+ "Yaojing",+ "Dawa",+ "Erwa",+ "Sanwa",+ "Siwa",+ "Wuwa",+ "Wukong",+ "Bajie",+ "Shaseng",+ "Sanzang",+]+++def get_player_name() -> str:+ """Generate player name."""+ return candidate_names.pop(np.random.randint(len(candidate_names)))+++def check_winning(+ alive_agents: list,+ wolf_agents: list,+) -> str | None:+ """Check if the game is over and return the winning message."""+ if len(wolf_agents) * 2 >= len(alive_agents):+ return Prompts.to_all_wolf_win.format(+ n_werewolves=(+ f"{len(wolf_agents)}"+ + f"({names_to_str([_.name for _ in wolf_agents])})"+ ),+ n_villagers=len(alive_agents) - len(wolf_agents),+ )+ if alive_agents and not wolf_agents:+ return Prompts.to_all_village_win+ return None+++def majority_vote(votes: list[str]) -> tuple:+ """Return the vote with the most counts."""+ result = max(set(votes), key=votes.count)+ names, counts = np.unique(votes, return_counts=True)+ conditions = ", ".join(+ [f"{name}: {count}" for name, count in zip(names, counts)],+ )+ return result, conditions+++def names_to_str(agents: list[str] | list[ReActAgent]) -> str:+ """Return a string of agent names."""+ if not agents:+ return ""++ if len(agents) == 1:+ if isinstance(agents[0], ReActAgent):+ return agents[0].name+ return agents[0]++ names = []+ for agent in agents:+ if isinstance(agent, ReActAgent):+ names.append(agent.name)+ else:+ names.append(agent)+ return ", ".join([*names[:-1], "and " + names[-1]])+++class EchoAgent(AgentBase):+ """Echo agent that repeats the input message."""++ def __init__(self) -> None:+ super().__init__()+ self.name = "Moderator"++ async def reply(self, content: str) -> Msg:+ """Repeat the input content with its name and role."""+ msg = Msg(+ self.name,+ content,+ role="assistant",+ )+ await self.print(msg)+ return msg++ async def handle_interrupt(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> Msg:+ """Handle interrupt."""++ async def observe(self, msg: Msg | list[Msg] | None) -> None:+ """Observe the user's message."""diff --git a/src/agentscope/agent/_agent_base.py b/src/agentscope/agent/_agent_base.pyindex 863530433..291e4c4fa 100644--- a/src/agentscope/agent/_agent_base.py+++ b/src/agentscope/agent/_agent_base.py@@ -4,11 +4,12 @@ import asyncioimport jsonfrom asyncio import Taskfrom collections import OrderedDict-from typing import Callable, Any, Sequence+from typing import Callable, Anyimport shortuuidfrom ._agent_meta import _AgentMeta+from .._logging import loggerfrom ..module import StateModulefrom ..message import Msgfrom ..types import AgentHookTypes@@ -148,8 +149,9 @@ class AgentBase(StateModule, metaclass=_AgentMeta):self._stream_prefix = {}# The subscribers that will receive the reply message by their- # `observe` method.- self._subscribers: list[AgentBase] = []+ # `observe` method. The key is the MsgHub id, and the value is the+ # list of agents.+ self._subscribers: dict[str, list[AgentBase]] = {}# We add this variable in case developers want to disable the console# output of the agent, e.g., in a production environment.@@ -232,6 +234,7 @@ class AgentBase(StateModule, metaclass=_AgentMeta):self._reply_task = asyncio.current_task()reply_msg = await self.reply(*args, **kwargs)+ # The interruption is triggered by calling the interrupt methodexcept asyncio.CancelledError:reply_msg = await self.handle_interrupt(*args, **kwargs)@@ -248,8 +251,9 @@ class AgentBase(StateModule, metaclass=_AgentMeta):msg: Msg | list[Msg] | None,) -> None:"""Broadcast the message to all subscribers."""- for subscriber in self._subscribers:- await subscriber.observe(msg)+ for subscribers in self._subscribers.values():+ for subscriber in subscribers:+ await subscriber.observe(msg)async def handle_interrupt(self,@@ -436,15 +440,36 @@ class AgentBase(StateModule, metaclass=_AgentMeta):hooks = getattr(self, f"_instance_{hook_type}_hooks")hooks.clear()- def reset_subscribers(self, subscribers: Sequence["AgentBase"]) -> None:+ def reset_subscribers(+ self,+ msghub_name: str,+ subscribers: list["AgentBase"],+ ) -> None:"""Reset the subscribers of the agent.Args:+ msghub_name (`str`):+ The name of the MsgHub that manages the subscribers.subscribers (`list[AgentBase]`):A list of agents that will receive the reply message fromthis agent via their `observe` method."""- self._subscribers = [_ for _ in subscribers if _ != self]+ self._subscribers[msghub_name] = [_ for _ in subscribers if _ != self]++ def remove_subscribers(self, msghub_name: str) -> None:+ """Remove the msghub subscribers by the given msg hub name.++ Args:+ msghub_name (`str`):+ The name of the MsgHub that manages the subscribers.+ """+ if msghub_name not in self._subscribers:+ logger.warning(+ "MsgHub named '%s' not found",+ msghub_name,+ )+ else:+ self._subscribers.pop(msghub_name)def disable_console_output(self) -> None:"""This function will disable the console output of the agent, e.g.diff --git a/src/agentscope/model/_dashscope_model.py b/src/agentscope/model/_dashscope_model.pyindex 7c878c218..236cd9a55 100644--- a/src/agentscope/model/_dashscope_model.py+++ b/src/agentscope/model/_dashscope_model.py@@ -85,7 +85,6 @@ class DashScopeChatModel(ChatModelBase):self.api_key = api_keyself.enable_thinking = enable_thinking- self.incremental_output = self.streamself.generate_kwargs = generate_kwargs or {}if base_http_api_url is not None:@@ -147,8 +146,9 @@ class DashScopeChatModel(ChatModelBase):**self.generate_kwargs,**kwargs,"result_format": "message",- # In agentscope, the `incremental_output` must be `True`- "incremental_output": self.incremental_output,+ # In agentscope, the `incremental_output` must be `True` when+ # `self.stream` is True+ "incremental_output": self.stream,}if tools:diff --git a/src/agentscope/pipeline/__init__.py b/src/agentscope/pipeline/__init__.pyindex c7cdf7229..9e0f5b801 100644--- a/src/agentscope/pipeline/__init__.py+++ b/src/agentscope/pipeline/__init__.py@@ -3,11 +3,13 @@complex workflows and multi-agent conversations."""from ._msghub import MsgHub-from ._class import SequentialPipeline-from ._functional import sequential_pipeline+from ._class import SequentialPipeline, FanoutPipeline+from ._functional import sequential_pipeline, fanout_pipeline__all__ = ["MsgHub","SequentialPipeline","sequential_pipeline",+ "FanoutPipeline",+ "fanout_pipeline",]diff --git a/src/agentscope/pipeline/_class.py b/src/agentscope/pipeline/_class.pyindex 39f6fd799..7a4e740c1 100644--- a/src/agentscope/pipeline/_class.py+++ b/src/agentscope/pipeline/_class.py@@ -1,6 +1,8 @@# -*- coding: utf-8 -*-"""Pipeline classes."""-from ._functional import sequential_pipeline+from typing import Any++from ._functional import sequential_pipeline, fanout_pipelinefrom ..agent import AgentBasefrom ..message import Msg@@ -32,4 +34,57 @@ class SequentialPipeline:msg (`Msg | list[Msg] | None`, defaults to `None`):The initial input that will be passed to the first agent."""- return await sequential_pipeline(agents=self.agents, msg=msg)+ return await sequential_pipeline(+ agents=self.agents,+ msg=msg,+ )+++class FanoutPipeline:+ """An async fanout pipeline class, which distributes the same input to+ multiple agents. Compared with functional pipeline, this class can be+ re-used and configured with default parameters."""++ def __init__(+ self,+ agents: list[AgentBase],+ enable_gather: bool = True,+ ) -> None:+ """Initialize a fanout pipeline class++ Args:+ agents (`list[AgentBase]`):+ A list of agents to execute.+ enable_gather (`bool`, defaults to `True`):+ Whether to execute agents concurrently+ using `asyncio.gather()`. If False, agents are executed+ sequentially.+ """+ self.agents = agents+ self.enable_gather = enable_gather++ async def __call__(+ self,+ msg: Msg | list[Msg] | None = None,+ **kwargs: Any,+ ) -> list[Msg]:+ """Execute the fanout pipeline++ Args:+ msg (`Msg | list[Msg] | None`, defaults to `None`):+ The input message that will be distributed to all agents.+ **kwargs (`Any`):+ Additional keyword arguments passed to each agent during+ execution.++ Returns:+ `list[Msg]`:+ A list of output messages from all agents.+ """++ return await fanout_pipeline(+ agents=self.agents,+ msg=msg,+ enable_gather=self.enable_gather,+ **kwargs,+ )diff --git a/src/agentscope/pipeline/_functional.py b/src/agentscope/pipeline/_functional.pyindex 590f44c77..a6fd374cb 100644--- a/src/agentscope/pipeline/_functional.py+++ b/src/agentscope/pipeline/_functional.py@@ -1,5 +1,8 @@# -*- coding: utf-8 -*-"""Functional counterpart for Pipeline"""+import asyncio+from copy import deepcopy+from typing import Anyfrom ..agent import AgentBasefrom ..message import Msg@@ -32,7 +35,6 @@ async def sequential_pipeline(A list of agents.msg (`Msg | list[Msg] | None`, defaults to `None`):The initial input that will be passed to the first agent.-Returns:`Msg | list[Msg] | None`:The output of the last agent in the sequence.@@ -40,3 +42,63 @@ async def sequential_pipeline(for agent in agents:msg = await agent(msg)return msg+++async def fanout_pipeline(+ agents: list[AgentBase],+ msg: Msg | list[Msg] | None = None,+ enable_gather: bool = True,+ **kwargs: Any,+) -> list[Msg]:+ """A fanout pipeline that distributes the same input to multiple agents.+ This pipeline sends the same message (or a deep copy of it) to all agents+ and collects their responses. Agents can be executed either concurrently+ using asyncio.gather() or sequentially depending on the enable_gather+ parameter.++ Example:+ .. code-block:: python++ agent1 = ReActAgent(...)+ agent2 = ReActAgent(...)+ agent3 = ReActAgent(...)++ msg_input = Msg("user", "Hello", "user")++ # Concurrent execution (default)+ results = await fanout_pipeline(+ [agent1, agent2, agent3],+ msg_input+ )++ # Sequential execution+ results = await fanout_pipeline(+ [agent1, agent2, agent3],+ msg_input,+ enable_gather=False+ )++ Args:+ agents (`list[AgentBase]`):+ A list of agents.+ msg (`Msg | list[Msg] | None`, defaults to `None`):+ The initial input that will be passed to all agents.+ enable_gather (`bool`, defaults to `True`):+ Whether to execute agents concurrently using `asyncio.gather()`.+ If False, agents are executed sequentially.+ **kwargs (`Any`):+ Additional keyword arguments passed to each agent during execution.++ Returns:+ `list[Msg]`:+ A list of response messages from each agent.+ """+ if enable_gather:+ tasks = [+ asyncio.create_task(agent(deepcopy(msg), **kwargs))+ for agent in agents+ ]++ return await asyncio.gather(*tasks)+ else:+ return [await agent(deepcopy(msg), **kwargs) for agent in agents]diff --git a/src/agentscope/pipeline/_msghub.py b/src/agentscope/pipeline/_msghub.pyindex 3d8a1ceed..4dfb23433 100644--- a/src/agentscope/pipeline/_msghub.py+++ b/src/agentscope/pipeline/_msghub.py@@ -2,6 +2,8 @@"""MsgHub is designed to share messages among a group of agents."""from typing import Any+import shortuuid+from .._logging import loggerfrom ..agent import AgentBase@@ -40,6 +42,8 @@ class MsgHub:self,participants: list[AgentBase],announcement: list[Msg] | Msg | None = None,+ enable_auto_broadcast: bool = True,+ name: str | None = None,) -> None:"""Initialize a MsgHub context manager.@@ -49,9 +53,20 @@ class MsgHub:announcement οΌ`list[Msg] | Msg | None`):The message that will be broadcast to all participants whenentering the MsgHub.+ enable_auto_broadcast (`bool`, defaults to `True`):+ Whether to enable automatic broadcasting of the replied+ message from any participant to all other participants. If+ disabled, the MsgHub will only serve as a manual message+ broadcaster with the `announcement` argument and the+ `broadcast()` method.+ name (`str | None`):+ The name of this MsgHub. If not provided, a random ID+ will be generated."""+ self.name = name or shortuuid.uuid()self.participants = participantsself.announcement = announcement+ self.enable_auto_broadcast = enable_auto_broadcastasync def __aenter__(self) -> "MsgHub":"""Will be called when entering the MsgHub."""@@ -59,20 +74,21 @@ class MsgHub:# broadcast the input message to all participantsif self.announcement is not None:- for agent in self.participants:- await agent.observe(self.announcement)+ await self.broadcast(msg=self.announcement)return selfasync def __aexit__(self, *args: Any, **kwargs: Any) -> None:"""Will be called when exiting the MsgHub."""- for agent in self.participants:- agent.reset_subscribers([])+ if self.enable_auto_broadcast:+ for agent in self.participants:+ agent.remove_subscribers(self.name)def _reset_subscriber(self) -> None:"""Reset the subscriber for agent in `self.participant`"""- for agent in self.participants:- agent.reset_subscribers(self.participants)+ if self.enable_auto_broadcast:+ for agent in self.participants:+ agent.reset_subscribers(self.name, self.participants)def add(self,@@ -98,9 +114,6 @@ class MsgHub:for agent in participant:if agent in self.participants:- # Clear the subscriber of the deleted agent firstly- agent.reset_subscribers([])-# remove agent from self.participantself.participants.pop(self.participants.index(agent))else:@@ -121,3 +134,21 @@ class MsgHub:"""for agent in self.participants:await agent.observe(msg)++ def set_auto_broadcast(self, enable: bool) -> None:+ """Enable automatic broadcasting of the replied message from any+ participant to all other participants.++ Args:+ enable (`bool`):+ Whether to enable automatic broadcasting. If disabled, the+ MsgHub will only serve as a manual message broadcaster with+ the `announcement` argument and the `broadcast()` method.+ """+ if enable:+ self.enable_auto_broadcast = True+ self._reset_subscriber()+ else:+ self.enable_auto_broadcast = False+ for agent in self.participants:+ agent.remove_subscribers(self.name)diff --git a/tests/pipeline_test.py b/tests/pipeline_test.pyindex 32586744e..ce2aca09a 100644--- a/tests/pipeline_test.py+++ b/tests/pipeline_test.py@@ -1,5 +1,4 @@# -*- coding: utf-8 -*--# pylint: disable=signature-differs"""Unit tests for pipeline classes and functions"""from typing import Anyfrom unittest.async_case import IsolatedAsyncioTestCase@@ -7,7 +6,9 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom agentscope.message import Msgfrom agentscope.pipeline import (SequentialPipeline,+ FanoutPipeline,sequential_pipeline,+ fanout_pipeline,)from agentscope.agent import AgentBase@@ -22,8 +23,10 @@ class AddAgent(AgentBase):self.name = "Add"self.value = value- async def reply(self, x: Msg) -> Msg:+ async def reply(self, x: Msg | None) -> Msg | None:"""Reply function"""+ if x is None:+ return Nonex.metadata["result"] += self.valuereturn x@@ -47,8 +50,10 @@ class MultAgent(AgentBase):self.name = "Mult"self.value = value- async def reply(self, x: Msg) -> Msg:+ async def reply(self, x: Msg | None) -> Msg | None:"""Reply function"""+ if x is None:+ return Nonex.metadata["result"] *= self.valuereturn x@@ -106,3 +111,191 @@ class PipelineTest(IsolatedAsyncioTestCase):pipeline = SequentialPipeline([mult3, add1, add2])res = await pipeline(x)self.assertEqual(res.metadata["result"], 3)++ async def test_functional_sequential_pipeline_with_none_message(+ self,+ ) -> None:+ """Test functional sequential pipeline with None message input"""++ add1 = AddAgent(1)+ add2 = AddAgent(2)+ mult3 = MultAgent(3)++ # Test with None input+ res = await sequential_pipeline([add1, add2, mult3], None)+ self.assertIsNone(res)+ # Test with empty agent list and None input+ res = await sequential_pipeline([], None)+ self.assertIsNone(res)++ async def test_class_sequential_pipeline_with_none_message(self) -> None:+ """Test class-based sequential pipeline with None message input"""++ add1 = AddAgent(1)+ add2 = AddAgent(2)+ mult3 = MultAgent(3)++ # Test with None input+ pipeline = SequentialPipeline([add1, add2, mult3])+ res = await pipeline(None)+ self.assertIsNone(res)++ # Test with empty agent list and None input+ empty_pipeline = SequentialPipeline([])+ res = await empty_pipeline(None)+ self.assertIsNone(res)++ async def test_empty_agent_list(self) -> None:+ """Test pipeline with empty agent list"""++ x = Msg("user", "", "user", metadata={"result": 42})++ # Functional pipeline+ res = await sequential_pipeline([], x)+ self.assertEqual(res.metadata["result"], 42)+ self.assertEqual(res, x) # Should return the same message object++ # Class-based pipeline+ pipeline = SequentialPipeline([])+ res = await pipeline(x)+ self.assertEqual(res.metadata["result"], 42)+ self.assertEqual(res, x) # Should return the same message object++ async def test_single_agent_pipeline(+ self,+ ) -> None:+ """Test pipeline with single agent"""++ add1 = AddAgent(5)++ x = Msg("user", "", "user", metadata={"result": 10})++ # Functional pipeline+ res = await sequential_pipeline([add1], x)+ self.assertEqual(res.metadata["result"], 15)++ # Class-based pipeline+ pipeline = SequentialPipeline([add1])+ x = Msg("user", "", "user", metadata={"result": 10})+ res = await pipeline(x)+ self.assertEqual(res.metadata["result"], 15)++ # Test single agent with None input+ res = await sequential_pipeline([add1], None)+ self.assertIsNone(res)+ res = await pipeline(None)+ self.assertIsNone(res)++ # ==================== Fanout Pipeline Tests ====================++ async def test_functional_fanout_pipeline_concurrent(self) -> None:+ """Test fanout_pipeline executes agents concurrently with+ independent inputs"""++ add1 = AddAgent(1)+ add2 = AddAgent(2)+ mult3 = MultAgent(3)++ x = Msg("user", "", "user", metadata={"result": 0})+ res = await fanout_pipeline([add1, add2, mult3], x, enable_gather=True)+ # Each agent should process the original input independently+ self.assertEqual(len(res), 3)+ self.assertEqual(res[0].metadata["result"], 1) # 0 + 1+ self.assertEqual(res[1].metadata["result"], 2) # 0 + 2+ self.assertEqual(res[2].metadata["result"], 0) # 0 * 3++ # Test different order+ x = Msg("user", "", "user", metadata={"result": 0})+ res = await fanout_pipeline([mult3, add1, add2], x, enable_gather=True)+ self.assertEqual(len(res), 3)+ self.assertEqual(res[0].metadata["result"], 0) # 0 * 3+ self.assertEqual(res[1].metadata["result"], 1) # 0 + 1+ self.assertEqual(res[2].metadata["result"], 2) # 0 + 2++ async def test_functional_fanout_pipeline_sequential(self) -> None:+ """Test fanout_pipeline executes agents sequentially with+ independent inputs"""++ add1 = AddAgent(1)+ add2 = AddAgent(2)+ mult3 = MultAgent(3)++ x = Msg("user", "", "user", metadata={"result": 0})+ res = await fanout_pipeline(+ [add1, add2, mult3],+ x,+ enable_gather=False,+ )++ # Each agent should still process the original input independently+ self.assertEqual(len(res), 3)+ self.assertEqual(res[0].metadata["result"], 1) # 0 + 1+ self.assertEqual(res[1].metadata["result"], 2) # 0 + 2+ self.assertEqual(res[2].metadata["result"], 0) # 0 * 3++ async def test_class_fanout_pipeline_concurrent(self) -> None:+ """Test FanoutPipeline class with concurrent execution"""++ add1 = AddAgent(1)+ add2 = AddAgent(2)+ mult3 = MultAgent(3)++ x = Msg("user", "", "user", metadata={"result": 0})+ pipeline = FanoutPipeline([add1, add2, mult3], enable_gather=True)+ res = await pipeline(x)+ self.assertEqual(len(res), 3)+ self.assertEqual(res[0].metadata["result"], 1) # 0 + 1+ self.assertEqual(res[1].metadata["result"], 2) # 0 + 2+ self.assertEqual(res[2].metadata["result"], 0) # 0 * 3++ async def test_class_fanout_pipeline_sequential(self) -> None:+ """Test FanoutPipeline class with sequential execution"""++ add1 = AddAgent(1)+ add2 = AddAgent(2)+ mult3 = MultAgent(3)++ x = Msg("user", "", "user", metadata={"result": 0})+ pipeline = FanoutPipeline([add1, add2, mult3], enable_gather=False)+ res = await pipeline(x)++ self.assertEqual(len(res), 3)+ self.assertEqual(res[0].metadata["result"], 1) # 0 + 1+ self.assertEqual(res[1].metadata["result"], 2) # 0 + 2+ self.assertEqual(res[2].metadata["result"], 0) # 0 * 3++ async def test_fanout_pipeline_empty_agents(self) -> None:+ """Test fanout pipeline with empty agent list"""++ x = Msg("user", "", "user", metadata={"result": 42})++ # Functional pipeline+ res = await fanout_pipeline([], x)+ self.assertEqual(res, [])++ res = await fanout_pipeline([], x, enable_gather=False)+ self.assertEqual(res, [])++ # Class-based pipeline+ pipeline = FanoutPipeline([])+ res = await pipeline(x)+ self.assertEqual(res, [])++ async def test_fanout_pipeline_with_none_message(self) -> None:+ """Test fanout pipeline with None message input"""++ add1 = AddAgent(1)+ add2 = AddAgent(2)++ # Functional pipeline+ res = await fanout_pipeline([add1, add2], None)+ self.assertEqual(len(res), 2)+ self.assertIsNone(res[0])+ self.assertIsNone(res[1])++ # Class-based pipeline+ pipeline = FanoutPipeline([add1, add2])+ res = await pipeline(None)+ self.assertEqual(len(res), 2)+ self.assertIsNone(res[0])+ self.assertIsNone(res[1])