Pipeline

For multi-agent orchestration, AgentScope provides the agentscope.pipeline module as syntax sugar for chaining agents together, including

  • MsgHub: a message hub for broadcasting messages among multiple agents

  • sequential_pipeline and SequentialPipeline: a functional and class-based implementation that chains agents in a sequential manner

  • fanout_pipeline and FanoutPipeline: a functional and class-based implementation that distributes the same input to multiple agents

  1. import os, asyncio
  2. from agentscope.formatter import DashScopeMultiAgentFormatter
  3. from agentscope.message import Msg
  4. from agentscope.model import DashScopeChatModel
  5. from agentscope.agent import ReActAgent
  6. from agentscope.pipeline import MsgHub

Broadcasting with MsgHub

The MsgHub class is an async context manager, receiving a list of agents as its participants. When one participant generates a replying message, all other participants will receive this message by calling their observe method.

That means within a MsgHub context, developers don’t need to manually send a replying message from one agent to another. The broadcasting is automatically handled.

Here we create four agents: Alice, Bob, Charlie and David. Then we start a meeting with Alice, Bob and Charlie by introducing themselves. Note David is not included in this meeting.

  1. def create_agent(name: str, age: int, career: str) -> ReActAgent:
  2. """Create agent object by the given information."""
  3. return ReActAgent(
  4. name=name,
  5. sys_prompt=f"You're {name}, a {age}-year-old {career}",
  6. model=DashScopeChatModel(
  7. model_name="qwen-max",
  8. api_key=os.environ["DASHSCOPE_API_KEY"],
  9. ),
  10. formatter=DashScopeMultiAgentFormatter(),
  11. )
  12. alice = create_agent("Alice", 50, "teacher")
  13. bob = create_agent("Bob", 35, "engineer")
  14. charlie = create_agent("Charlie", 28, "designer")
  15. david = create_agent("David", 30, "developer")

Then we start a meeting and let them introduce themselves without manual message passing:

Hint

The message in announcement will be broadcasted to all participants when entering the MsgHub context.

  1. async def example_broadcast_message():
  2. """Example of broadcasting messages with MsgHub."""
  3. # Create a message hub
  4. async with MsgHub(
  5. participants=[alice, bob, charlie],
  6. announcement=Msg(
  7. "user",
  8. "Now introduce yourself in one sentence, including your name, age and career.",
  9. "user",
  10. ),
  11. ) as hub:
  12. # Group chat without manual message passing
  13. await alice()
  14. await bob()
  15. await charlie()
  16. asyncio.run(example_broadcast_message())
  1. Alice: Hello, I'm Alice, a 50-year-old teacher with a passion for literature and fostering young minds.
  2. Bob: Hello, I'm Bob, a 35-year-old engineer with a keen interest in solving complex technical challenges.
  3. Charlie: Hello, I'm Charlie, a 28-year-old designer with a flair for creating innovative and user-friendly designs.

Now let’s check if Bob, Charlie and David received Alice’s message.

  1. async def check_broadcast_message():
  2. """Check if the messages are broadcast correctly."""
  3. user_msg = Msg(
  4. "user",
  5. "Do you know who's Alice, and what she does? Answer me briefly.",
  6. "user",
  7. )
  8. await bob(user_msg)
  9. await charlie(user_msg)
  10. await david(user_msg)
  11. asyncio.run(check_broadcast_message())
  1. Bob: Alice is a 50-year-old teacher who has a passion for literature and fostering young minds.
  2. Charlie: Alice is a 50-year-old teacher who has a passion for literature and fostering young minds.
  3. David: I don't have specific information about a particular Alice since it's a common name. Could you provide more details, such as her last name or the context in which you're asking?

Now we observe that Bob and Charlie know Alice and her profession, while David has no idea about Alice since he is not included in the MsgHub context.

Dynamic Participant Management

Additionally, MsgHub supports to dynamically manage participants by the following methods:

  • add: add one or multiple agents as new participants

  • delete: remove one or multiple agents from participants, and they will no longer receive broadcasted messages

  • broadcast: broadcast a message to all current participants

Note

The newly added participants will not receive the previous messages.

  1. async with MsgHub(participants=[alice]) as hub:
  2. # Add new participants
  3. hub.add(david)
  4. # Remove participants
  5. hub.delete(alice)
  6. # Broadcast to all current participants
  7. await hub.broadcast(
  8. Msg("system", "Now we begin to ...", "system"),
  9. )

Pipeline

Pipeline serves as a syntax sugar for multi-agent orchestration.

Currently, AgentScope provides two main pipeline implementations:

  1. Sequential Pipeline: Execute agents one by one in a predefined order

  2. Fanout Pipeline: Distribute the same input to multiple agents and collect their responses

Sequential Pipeline

The sequential pipeline executes agents one by one, where the output of the previous agent becomes the input of the next agent.

For example, the two following code snippets are equivalent:

Code snippet 1: Manually call agents one by one

  1. msg = None
  2. msg = await alice(msg)
  3. msg = await bob(msg)
  4. msg = await charlie(msg)
  5. msg = await david(msg)

Code snippet 2: Use sequential pipeline

  1. from agentscope.pipeline import sequential_pipeline
  2. msg = await sequential_pipeline(
  3. # List of agents to be executed in order
  4. agents=[alice, bob, charlie, david],
  5. # The first input message, can be None
  6. msg=None
  7. )

Fanout Pipeline

The fanout pipeline distributes the same input message to multiple agents simultaneously and collects all their responses. This is useful when you want to gather different perspectives or expertise on the same topic.

For example, the two following code snippets are equivalent:

Code snippet 3: Manually call agents one by one

  1. from copy import deepcopy
  2. msgs = []
  3. msg = None
  4. for agent in [alice, bob, charlie, david]:
  5. msgs.append(await agent(deepcopy(msg)))

Code snippet 4: Use fanout pipeline

  1. from agentscope.pipeline import fanout_pipeline
  2. msgs = await fanout_pipeline(
  3. # List of agents to be executed in order
  4. agents=[alice, bob, charlie, david],
  5. # The first input message, can be None
  6. msg=None,
  7. enable_gather=False,
  8. )

Note

The enable_gather parameter controls the execution mode of the fanout pipeline:

  • enable_gather=True (default): Executes all agents concurrently using asyncio.gather(). This provides better performance for I/O-bound operations like API calls, as agents run in parallel.

  • enable_gather=False: Executes agents sequentially one by one. This is useful when you need deterministic execution order or want to avoid overwhelming external services with concurrent requests.

Choose concurrent execution for better performance, or sequential execution for predictable ordering and resource control.

Tip

By combining MsgHub and sequential_pipeline or fanout_pipeline, you can create more complex workflows very easily.

Advanced Pipeline Features

Additionally, for reusability, we also provide a class-based implementation:

Using SequentialPipeline class

  1. from agentscope.pipeline import SequentialPipeline
  2. # Create a pipeline object
  3. pipeline = SequentialPipeline(agents=[alice, bob, charlie, david])
  4. # Call the pipeline
  5. msg = await pipeline(msg=None)
  6. # Reuse the pipeline with different input
  7. msg = await pipeline(msg=Msg("user", "Hello!", "user"))

Using FanoutPipeline class

  1. from agentscope.pipeline import FanoutPipeline
  2. # Create a pipeline object
  3. pipeline = FanoutPipeline(agents=[alice, bob, charlie, david])
  4. # Call the pipeline
  5. msgs = await pipeline(msg=None)
  6. # Reuse the pipeline with different input
  7. msgs = await pipeline(msg=Msg("user", "Hello!", "user"))

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

Download Jupyter notebook: task_pipeline.ipynb

Download Python source code: task_pipeline.py

Download zipped: task_pipeline.zip

Gallery generated by Sphinx-Gallery