Velamuvi AIAcademy

Lesson 32 of 39 · Orchestrations

Sequential and Concurrent Orchestration

Chain agents with SequentialBuilder, run them in parallel with ConcurrentBuilder, write custom aggregators and add human review in Microsoft Agent Framework.

  • 13 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain what an orchestration is and when to use one
  • Chain agents into a pipeline with SequentialBuilder and choose which replies you see
  • Run agents in parallel with ConcurrentBuilder and read the combined result
  • Combine parallel answers with a custom aggregator
  • Let a person review an agent's work with with_request_info()

Ready-made teams of agents

In the last lessons you wired agents into workflows yourself: executors, edges, fan-out, fan-in. Many teams of agents follow the same few shapes, so Agent Framework ships them ready-made.

PatternHow the agents work togetherBuilder
SequentialOne after another, like an assembly lineSequentialBuilder (this lesson)
ConcurrentAll at the same time on the same task, then the answers are combinedConcurrentBuilder (this lesson)
Group chatTake turns in one conversation, chosen by a managerGroupChatBuilder (next lesson)
HandoffPass the conversation to the agent with the right skillsHandoffBuilder (next lesson)
MagenticA manager agent plans the work and assigns stepsMagenticBuilder (the Magentic lesson)

The builders live in agent_framework.orchestrations (the agent-framework-orchestrations package, included in pip install agent-framework). Every builder's build() returns a normal Workflow, so everything from the workflow lessons still works: run(), streaming, events, checkpoints and as_agent().

Here are the two patterns of this lesson in plain Python, with functions standing in for agents:

Try it yourselfPython
# Sequential and concurrent orchestration in plain Python. Each "agent" is a function here.
def researcher(conversation):
    return "Range 120 km, weight 23 kg."

def writer(conversation):
    return "Meet the Velo City E. " + conversation[-1][1]

def editor(conversation):
    return conversation[-1][1].replace("Meet", "Say hello to")

# Sequential: each agent reads the whole conversation and adds its reply.
conversation = [("user", "Describe the Velo City E")]
for agent in [researcher, writer, editor]:
    conversation.append((agent.__name__, agent(conversation)))
for speaker, text in conversation:
    print(f"{speaker:>10}: {text}")

# Concurrent: every reviewer gets the same input, and an aggregator combines the replies.
reviewers = {
    "safety": lambda plan: "Add a helmet reminder.",
    "pricing": lambda plan: "35 EUR a day is fine.",
}
plan = "Rent the Velo City E for 35 EUR a day"
replies = [(name, review(plan)) for name, review in reviewers.items()]
print(" | ".join(f"{name}: {text}" for name, text in replies))

Sequential: an assembly line

A researcher collects facts, a writer turns them into a product description, and an editor polishes it:

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import SequentialBuilder


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    researcher = Agent(client=client, name="researcher",
                       instructions="List three facts about the product in one line.")
    writer = Agent(client=client, name="writer",
                   instructions="Write a two-sentence product description from the facts.")
    editor = Agent(client=client, name="editor",
                   instructions="Edit the text: fix grammar, keep it under 40 words. Reply with the text only.")

    workflow = SequentialBuilder(participants=[researcher, writer, editor]).build()
    result = await workflow.run("The Velo City E, our new rental e-bike")

    final = result.get_outputs()[0]                 # the last agent's AgentResponse
    print(type(final).__name__, "from", final.messages[-1].author_name)
    print(final.text)


asyncio.run(main())
Output
AgentResponse from editor
Meet the Velo City E: 120 km per charge, just 23 kg, and a full charge takes 4 hours.
  1. SequentialBuilder(participants=[...]) wraps each agent in an AgentExecutor and connects them in the order given.
  2. Each agent receives the whole conversation so far: the user's request plus every earlier agent's reply. So the editor knows what the user asked for and what the writer wrote.
  3. The workflow's output is the last participant's AgentResponse. The researcher's and writer's replies are hidden unless you ask for them (next section).

Watching every agent work

The output selection works as in a normal workflow: output_from chooses the participants whose replies are outputs, and intermediate_output_from the ones shown as progress. Both accept agents or their names. With streaming you can watch each agent write:

import asyncio

from agent_framework import Agent, AgentResponseUpdate
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import SequentialBuilder


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    researcher = Agent(client=client, name="researcher",
                       instructions="List three facts about the product in one line.")
    writer = Agent(client=client, name="writer",
                   instructions="Write a two-sentence product description from the facts.")
    editor = Agent(client=client, name="editor",
                   instructions="Edit the text: fix grammar, keep it under 40 words. Reply with the text only.")

    workflow = SequentialBuilder(
        participants=[researcher, writer, editor],
        output_from=[editor],                            # the final answer
        intermediate_output_from="all_other",            # progress: everyone else
    ).build()

    current = None
    async for event in workflow.run("The Velo City E, our new rental e-bike", stream=True):
        if event.type in ("output", "intermediate") and isinstance(event.data, AgentResponseUpdate):
            if event.executor_id != current:
                if current is not None:
                    print()
                current = event.executor_id
                print(f"[{event.type}: {current}] ", end="")
            print(event.data.text, end="", flush=True)
    print()


asyncio.run(main())
Output
[intermediate: researcher] Range 120 km. Weight 23 kg. Full charge in 4 hours.
[intermediate: writer] Meet the Velo City E: 120 km on one charge, and only 23 kg. It charges fully in 4 hours.
[output: editor] Meet the Velo City E: 120 km per charge, just 23 kg, and a full charge takes 4 hours.

"all_other" means every participant that isn't in output_from. Pass output_from as well: on its own, intermediate_output_from="all_other" makes every participant intermediate, including the last one, and get_outputs() comes back empty.

More options of SequentialBuilder:

OptionWhat it does
nameThe workflow's name, "Sequential" by default. Set your own when you use checkpoints
checkpoint_storageSaves checkpoints, as in the previous lesson
chain_only_agent_responses=TrueEach agent sees only the previous agent's reply instead of the whole conversation (like context_mode="last_agent")
ensure_trailing_user_turn=TrueAdds a short user message when a conversation ends with an assistant reply, for providers that return empty answers then

A participant can also be your own executor. It receives what the participant before it sends: an AgentExecutorResponse after an agent (pass it on with response.with_text(...), as in the Agents in Workflows lesson), or a list[Message] when it comes first. The same agent object can't appear twice: that raises ValueError: Duplicate agent participant detected (same agent instance provided twice).

Concurrent: everyone at once

Before a launch, three reviewers check Velo's new rental plan. They don't need each other's answers, so they can work at the same time:

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import ConcurrentBuilder


def reviewer(client, area: str) -> Agent:
    return Agent(client=client, name=f"{area}_reviewer",
                 instructions=f"You check {area} for Velo's launch plans. Reply with one short sentence.")


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    workflow = ConcurrentBuilder(
        participants=[reviewer(client, "safety"), reviewer(client, "marketing"), reviewer(client, "pricing")],
    ).build()

    result = await workflow.run("Plan: rent the Velo City E e-bike for 35 EUR a day from 1 March.")
    combined = result.get_outputs()[0]               # one AgentResponse with every reply
    for message in combined.messages:
        print(f"{message.author_name}: {message.text}")


asyncio.run(main())
Output
safety_reviewer: Add a reminder that riders must wear a helmet.
marketing_reviewer: Lead with the 120 km range: it beats every rival.
pricing_reviewer: 35 EUR a day matches other shops in Porto.
  • ConcurrentBuilder creates a dispatcher that sends the same input to every participant (fan-out), and an aggregator that waits for all of them (fan-in).
  • All participants run in the same superstep, so three model calls of about one second each take about one second in total, not three.
  • The default aggregator outputs one AgentResponse whose messages hold each participant's final reply, in participant order. message.author_name says who wrote it. The user's prompt isn't included.

Combining answers with a custom aggregator

Three separate opinions aren't a decision yet. with_aggregator(...) replaces the default aggregator, for example with a function that asks one more agent to turn the reviews into a to-do list:

import asyncio

from agent_framework import Agent, AgentExecutorResponse
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import ConcurrentBuilder

client = OpenAIChatClient(model="MODEL_NAME")
summarizer = Agent(client=client, name="summarizer",
                   instructions="Combine the reviews into a short to-do list for the launch team.")


async def to_do_list(results: list[AgentExecutorResponse]) -> str:      # the custom aggregator
    reviews = "\n".join(f"{r.executor_id}: {r.agent_response.text}" for r in results)
    print(reviews)
    return (await summarizer.run(reviews)).text       # the return value becomes the output


def reviewer(area: str) -> Agent:
    return Agent(client=client, name=f"{area}_reviewer",
                 instructions=f"You check {area} for Velo's launch plans. Reply with one short sentence.")


async def main():
    workflow = (
        ConcurrentBuilder(participants=[reviewer("safety"), reviewer("marketing"), reviewer("pricing")])
        .with_aggregator(to_do_list)
        .build()
    )
    result = await workflow.run("Plan: rent the Velo City E e-bike for 35 EUR a day from 1 March.")
    print("---")
    print(result.get_outputs()[0])


asyncio.run(main())
Output
safety_reviewer: Add a reminder that riders must wear a helmet.
marketing_reviewer: Lead with the 120 km range: it beats every rival.
pricing_reviewer: 35 EUR a day matches other shops in Porto.
---
1. Add a helmet reminder to the rental page.
2. Put the 120 km range in the headline.
3. Keep the price at 35 EUR a day.
  • The aggregator receives a list[AgentExecutorResponse], one per participant, with executor_id, agent_response and full_conversation (see the Agents in Workflows lesson).
  • It can be a normal or an async function. If it returns something other than None, that value becomes the workflow's output. Here it's a string.
  • Add a second parameter, ctx: WorkflowContext[Never, str], to call ctx.yield_output(...) yourself, for example to yield several outputs. Then return None.
  • For more control, pass your own Executor with a handler for list[AgentExecutorResponse].

A person in the loop

with_request_info() pauses the orchestration after an agent replies, so a person can approve the reply or send it back with feedback. It works on both builders. Here a person reviews each of the writer's drafts before the editor sees it:

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import AgentRequestInfoResponse, SequentialBuilder


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    writer = Agent(client=client, name="writer",
                   instructions="Write a two-sentence product description from the facts.")
    editor = Agent(client=client, name="editor",
                   instructions="Edit the text: fix grammar, keep it under 40 words. Reply with the text only.")
    workflow = (
        SequentialBuilder(participants=[writer, editor])
        .with_request_info(agents=[writer])              # a person reviews the writer's drafts
        .build()
    )

    result = await workflow.run("The Velo City E: range 120 km, 23 kg, 35 EUR a day")
    while requests := result.get_request_info_events():
        request = requests[0]                           # its data is the writer's AgentExecutorResponse
        print(f"[{request.source_executor_id}] {request.data.agent_response.text}")
        note = input("Feedback (press Enter to approve): ").strip()
        if note:
            answer = AgentRequestInfoResponse.from_strings([note])      # the writer tries again
        else:
            answer = AgentRequestInfoResponse.approve()                  # pass the draft on
        result = await workflow.run(responses={request.request_id: answer})

    print("Final:", result.get_outputs()[0].text)


asyncio.run(main())

What the reviewer sees in the terminal:

Output
[writer] Meet the Velo City E: 120 km on one charge, and only 23 kg.
Feedback (press Enter to approve): Please mention the price.
[writer] Meet the Velo City E: 120 km on one charge, 23 kg light. Rent it for 35 EUR a day.
Feedback (press Enter to approve): 
Final: Meet the Velo City E: 120 km per charge, 23 kg light. Rent it for 35 EUR a day.
  • with_request_info(agents=[writer]) limits the reviews to the writer. Without agents, every agent participant is reviewed.
  • Each pause is a normal request_info event (see the previous lesson). Its data is the agent's AgentExecutorResponse, and source_executor_id is the agent's name.
  • Answer with an AgentRequestInfoResponse. approve() passes the reply on unchanged. from_strings([...]) sends your notes to the same agent as user messages, and it tries again (from_messages([...]) does the same with Message objects).
  • The writer remembers its first draft, so "Please mention the price" is enough.

Orchestrations are workflows

Because build() returns a Workflow, you can combine orchestrations with everything you already know:

  • workflow.as_agent(name=...) turns a whole team into one agent, which can then be a participant in another orchestration.
  • WorkflowExecutor puts an orchestration inside a bigger workflow as one step.
  • checkpoint_storage= on the builder saves the run, so a review can wait until tomorrow.
  • WorkflowViz draws the generated graph, which is a good way to see what a builder created.

Common mistakes

Practice exercise

Write a custom aggregator in plain Python: turn the reviewers' replies into a numbered to-do list and leave out the reviewers that had nothing to change.

Your solutionPython
results = [
    ("safety_reviewer", "Add a helmet reminder."),
    ("marketing_reviewer", "Lead with the 120 km range."),
    ("pricing_reviewer", "OK"),
]

def to_do_list(results):
    # Return one numbered line per reviewer that asked for a change,
    # like "1. safety: Add a helmet reminder." (the name without "_reviewer").
    # Skip replies that are just "OK". Join the lines with "\n".
    pass

print(to_do_list(results))
Knowledge check

A ConcurrentBuilder workflow has three agents and no custom aggregator. What does result.get_outputs()[0] contain?

Summary

  • Orchestrations are ready-made multi-agent workflows from agent_framework.orchestrations. build() returns a normal Workflow.
  • SequentialBuilder runs participants in order, and each one sees the whole conversation. The output is the last agent's AgentResponse. Choose other replies with output_from and intermediate_output_from.
  • ConcurrentBuilder sends the same input to every participant at once and combines the replies into one AgentResponse.
  • with_aggregator() replaces the combining step with your own function or executor. It receives a list[AgentExecutorResponse], and its return value becomes the output.
  • with_request_info() lets a person approve or correct an agent's reply with AgentRequestInfoResponse.approve() or from_strings([...]).

Next: Group Chat and Handoff Orchestration.

Finished reading? Tick it off to track your progress.