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
- 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.
| Pattern | How the agents work together | Builder |
|---|---|---|
| Sequential | One after another, like an assembly line | SequentialBuilder (this lesson) |
| Concurrent | All at the same time on the same task, then the answers are combined | ConcurrentBuilder (this lesson) |
| Group chat | Take turns in one conversation, chosen by a manager | GroupChatBuilder (next lesson) |
| Handoff | Pass the conversation to the agent with the right skills | HandoffBuilder (next lesson) |
| Magentic | A manager agent plans the work and assigns steps | MagenticBuilder (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:
# 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())AgentResponse from editor Meet the Velo City E: 120 km per charge, just 23 kg, and a full charge takes 4 hours.
SequentialBuilder(participants=[...])wraps each agent in anAgentExecutorand connects them in the order given.- 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.
- 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())[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:
| Option | What it does |
|---|---|
name | The workflow's name, "Sequential" by default. Set your own when you use checkpoints |
checkpoint_storage | Saves checkpoints, as in the previous lesson |
chain_only_agent_responses=True | Each agent sees only the previous agent's reply instead of the whole conversation (like context_mode="last_agent") |
ensure_trailing_user_turn=True | Adds 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())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.
ConcurrentBuildercreates 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
AgentResponsewhosemessageshold each participant's final reply, in participant order.message.author_namesays 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())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, withexecutor_id,agent_responseandfull_conversation(see the Agents in Workflows lesson). - It can be a normal or an
asyncfunction. If it returns something other thanNone, that value becomes the workflow's output. Here it's a string. - Add a second parameter,
ctx: WorkflowContext[Never, str], to callctx.yield_output(...)yourself, for example to yield several outputs. Then returnNone. - For more control, pass your own
Executorwith a handler forlist[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:
[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. Withoutagents, every agent participant is reviewed.- Each pause is a normal
request_infoevent (see the previous lesson). Itsdatais the agent'sAgentExecutorResponse, andsource_executor_idis 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 withMessageobjects). - 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.WorkflowExecutorputs an orchestration inside a bigger workflow as one step.checkpoint_storage=on the builder saves the run, so a review can wait until tomorrow.WorkflowVizdraws the generated graph, which is a good way to see what a builder created.
Common mistakes
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.
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))
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 normalWorkflow. SequentialBuilderruns participants in order, and each one sees the whole conversation. The output is the last agent'sAgentResponse. Choose other replies withoutput_fromandintermediate_output_from.ConcurrentBuildersends the same input to every participant at once and combines the replies into oneAgentResponse.with_aggregator()replaces the combining step with your own function or executor. It receives alist[AgentExecutorResponse], and its return value becomes the output.with_request_info()lets a person approve or correct an agent's reply withAgentRequestInfoResponse.approve()orfrom_strings([...]).
Next: Group Chat and Handoff Orchestration.
Finished reading? Tick it off to track your progress.