Lesson 34 of 39 · Orchestrations
Magentic Orchestration
Let a manager agent plan a task, track progress and assign steps with MagenticBuilder: task and progress ledgers, plan review by a person, events and limits.
- 12 min read
- Intermediate
- Reviewed
- Explain how a Magentic manager plans, tracks progress and replans
- Build a Magentic workflow with MagenticBuilder and a manager agent
- Follow the plan and the progress ledgers through MagenticOrchestratorEvent
- Let a person approve or revise the plan with MagenticPlanReviewRequest
- Set limits on rounds, stalls and resets, and customise the StandardMagenticManager
A manager that plans
Group chats and handoffs work well when you know the shape of the conversation. Some tasks are more open: "write a rental guide", "find out why sales dropped". Nobody knows the exact steps in advance. Magentic orchestration handles these with a manager that plans first, then directs the team step by step. The design comes from Microsoft Research's Magentic-One system.
The loop looks like this:
- The manager writes the task ledger: facts, then a plan.
- Each round it writes a progress ledger, picks the next agent and sends it an instruction.
- If the team stalls (no progress, or a loop) too often, the manager replans: it updates the facts and writes a new plan.
- When the request is satisfied, the manager writes the final answer.
Here is that loop in plain Python, with functions standing in for agents:
# A Magentic manager in plain Python: a plan, then a progress ledger every round.
plan = {"researcher": "look up price, range and helmet rules", "writer": "write the guide"}
done = {}
def progress_ledger():
# The manager asks itself the same questions every round.
if "writer" in done:
return {"is_request_satisfied": True}
next_speaker = "researcher" if "researcher" not in done else "writer"
return {"is_request_satisfied": False, "next_speaker": next_speaker,
"instruction": plan[next_speaker]}
agents = {
"researcher": lambda instruction: "35 EUR a day, 120 km, helmet required",
"writer": lambda instruction: "Guide: " + done["researcher"],
}
for round_index in range(10): # max_round_count = 10
ledger = progress_ledger()
if ledger["is_request_satisfied"]:
print("Final answer:", done["writer"])
break
name = ledger["next_speaker"]
done[name] = agents[name](ledger["instruction"])
print(f"round {round_index}: {name} <- {ledger['instruction']!r}")Magentic is the most flexible orchestration and also the most expensive one. If you already know the steps, a sequential orchestration or a workflow is cheaper, faster and easier to predict.
Your first Magentic workflow
MagenticBuilder from agent_framework.orchestrations needs the participants and a manager. The easiest manager is an ordinary agent passed as manager_agent: the builder wraps it in a StandardMagenticManager, which writes all the prompts for planning, progress checks and the final answer.
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import MagenticBuilder
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
researcher = Agent(client=client, name="researcher", description="Finds facts about Velo's bikes and rules",
instructions="You find facts for Velo, a bike rental shop in Porto. Answer briefly.")
writer = Agent(client=client, name="writer", description="Writes short customer guides",
instructions="You write short guides for Velo's customers.")
manager = Agent(client=client, name="manager", instructions="You coordinate Velo's team of agents.")
workflow = MagenticBuilder(
participants=[researcher, writer],
manager_agent=manager, # becomes a StandardMagenticManager
max_round_count=10, # at most 10 rounds of coordination
max_stall_count=3, # replan after 3 rounds without progress
max_reset_count=2, # give up after 2 replans
).build()
result = await workflow.run("Write a short guide to renting a Velo City E: price, range and helmet rules.")
print(result.get_outputs()[0].text)
asyncio.run(main())Renting a Velo City E in Porto: 35 EUR a day, about 120 km per charge, and a helmet is included and required. Pick it up at Rua das Flores 12.
The output is the manager's final answer, written from everything the team said. The participants' own replies are hidden unless you list them in output_from or intermediate_output_from, as in the other orchestrations.
As always, the agents' description values matter: the manager reads them to write the plan and to choose who works next. Behind the scenes, build() turns the manager into a MagenticOrchestrator executor and wraps each agent in a MagenticAgentExecutor, with edges both ways between them.
Watching the manager think
A streamed run sends magentic_orchestrator events. Their data is a MagenticOrchestratorEvent with an event_type and a content:
event_type | When | content |
|---|---|---|
PLAN_CREATED | After the first plan | The task ledger as a Message |
PROGRESS_LEDGER_UPDATED | Every round | A MagenticProgressLedger |
REPLANNED | After a replan (a stall, or a revised plan) | The new task ledger as a Message |
import asyncio
from agent_framework import Agent, AgentResponseUpdate
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import (
MagenticBuilder,
MagenticOrchestratorEvent,
MagenticOrchestratorEventType,
MagenticProgressLedger,
)
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
researcher = Agent(client=client, name="researcher", description="Finds facts about Velo's bikes and rules",
instructions="You find facts for Velo, a bike rental shop in Porto. Answer briefly.")
writer = Agent(client=client, name="writer", description="Writes short customer guides",
instructions="You write short guides for Velo's customers.")
manager = Agent(client=client, name="manager", instructions="You coordinate Velo's team of agents.")
workflow = MagenticBuilder(participants=[researcher, writer], manager_agent=manager, max_round_count=10).build()
task = "Write a short guide to renting a Velo City E: price, range and helmet rules."
async for event in workflow.run(task, stream=True):
if event.type == "magentic_orchestrator" and isinstance(event.data, MagenticOrchestratorEvent):
if event.data.event_type == MagenticOrchestratorEventType.PLAN_CREATED:
print("PLAN CREATED")
elif isinstance(event.data.content, MagenticProgressLedger):
ledger = event.data.content
if ledger.is_request_satisfied.answer:
print("LEDGER: request satisfied, writing the final answer")
else:
print(f"LEDGER: next {ledger.next_speaker.answer}: {ledger.instruction_or_question.answer}")
elif event.type == "output" and isinstance(event.data, AgentResponseUpdate):
print(event.data.text, end="")
print()
asyncio.run(main())PLAN CREATED LEDGER: next researcher: Find the daily price, the range and the helmet rules. LEDGER: next writer: Write a five-line rental guide from the researcher's facts. LEDGER: request satisfied, writing the final answer Renting a Velo City E in Porto: 35 EUR a day, about 120 km per charge, and a helmet is included and required. Pick it up at Rua das Flores 12.
A MagenticProgressLedger has five fields, one per question: is_request_satisfied, is_in_loop, is_progress_being_made, next_speaker and instruction_or_question. Each is a MagenticProgressLedgerItem with a reason and an answer, so you can log why the manager decided what it did. That is very useful when a run goes wrong.
A person reviews the plan
With enable_plan_review=True, the workflow pauses after planning and asks a person to check the plan. The request's data is a MagenticPlanReviewRequest with the plan message. Answer with review.approve() or review.revise(feedback): both return a MagenticPlanReviewResponse, which you send back with workflow.run(responses=...). A revision makes the manager replan with your feedback, and then it asks again.
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import MagenticBuilder, MagenticPlanReviewRequest
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
researcher = Agent(client=client, name="researcher", description="Finds facts about Velo's bikes and rules",
instructions="You find facts for Velo, a bike rental shop in Porto. Answer briefly.")
writer = Agent(client=client, name="writer", description="Writes short customer guides",
instructions="You write short guides for Velo's customers.")
manager = Agent(client=client, name="manager", instructions="You coordinate Velo's team of agents.")
workflow = MagenticBuilder(participants=[researcher, writer], manager_agent=manager,
enable_plan_review=True, max_round_count=10).build()
result = await workflow.run("Write a short guide to renting a Velo City E: price, range and helmet rules.")
while requests := result.get_request_info_events():
review: MagenticPlanReviewRequest = requests[0].data
print("PROPOSED PLAN:")
print(review.plan.text.split("Here is the plan to follow as best as possible:")[-1].strip())
feedback = input("Feedback (Enter to approve): ")
answer = review.revise(feedback) if feedback else review.approve()
result = await workflow.run(responses={requests[0].request_id: answer})
print(result.get_outputs()[0].text)
asyncio.run(main())PROPOSED PLAN: - researcher: look up price, range and helmet rules - writer: turn the facts into a short guide Feedback (Enter to approve): Also give the pick-up address. PROPOSED PLAN: The plan left out the pick-up address. - researcher: look up price, range, helmet rules and the pick-up address - writer: turn the facts into a short guide Feedback (Enter to approve): Renting a Velo City E in Porto: 35 EUR a day, about 120 km per charge, and a helmet is included and required. Pick it up at Rua das Flores 12.
The plan message holds the whole task ledger (the task, the team, the facts and the plan), so the code prints only the part after "Here is the plan to follow as best as possible:". After a replan caused by stalling, a review request also carries current_progress (the latest progress ledger) and is_stalled=True.
Limits: rounds, stalls and resets
An open-ended manager needs guard rails. max_round_count and max_reset_count have no limit by default, so set them yourself:
max_round_count: the most coordination rounds in total, counted across resets. When it is reached, the output is a message fromMAGENTIC_MANAGER_NAME("magentic_manager") that says "Workflow terminated due to reaching maximum round count."max_stall_count(default 3): a round with no progress, or a loop, adds 1 to a stall counter, and a round with progress takes 1 away. When the counter goes above the limit, the manager resets: it clears the conversation, sends every agent aMagenticResetSignalso it starts a fresh session, and replans.max_reset_count: the most resets. When the number of resets reaches it, the run ends with "Workflow terminated due to reaching maximum reset count."
Customising the manager
To change how the manager thinks, create the StandardMagenticManager yourself and pass it as manager=. Every prompt can be replaced, for example the one for the final answer. Keep the placeholders that the default prompt uses: for the final answer that is {task}, which the manager fills in.
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import MagenticBuilder, StandardMagenticManager
FINAL_ANSWER_PROMPT = """We are working on the following task:
{task}
We have completed the task. Write the final answer for a tourist in two short sentences."""
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
researcher = Agent(client=client, name="researcher", description="Finds facts about Velo's bikes and rules",
instructions="You find facts for Velo, a bike rental shop in Porto. Answer briefly.")
writer = Agent(client=client, name="writer", description="Writes short customer guides",
instructions="You write short guides for Velo's customers.")
manager_agent = Agent(client=client, name="manager", instructions="You coordinate Velo's team of agents.")
manager = StandardMagenticManager(manager_agent, final_answer_prompt=FINAL_ANSWER_PROMPT, max_round_count=10)
workflow = MagenticBuilder(participants=[researcher, writer], manager=manager).build()
result = await workflow.run("Write a short guide to renting a Velo City E: price, range and helmet rules.")
print(result.get_outputs()[0].text)
asyncio.run(main())Rent the Velo City E for 35 EUR a day and ride about 120 km on one charge. A helmet is included, and you must wear it.
The other prompts are task_ledger_facts_prompt, task_ledger_plan_prompt, task_ledger_full_prompt, task_ledger_facts_update_prompt, task_ledger_plan_update_prompt and progress_ledger_prompt. For a completely different strategy, subclass MagenticManagerBase and write its four methods: plan, replan, create_progress_ledger and prepare_final_answer. Each one receives a MagenticContext with the task, the chat history, the agents' descriptions and the round, stall and reset counts.
Common mistakes
Write the manager's stall rule in plain Python, the same way Magentic counts stalls: decide for each progress ledger whether to finish, replan or ask the next agent.
ledgers = [
{"satisfied": False, "progress": False, "next": "researcher"},
{"satisfied": False, "progress": True, "next": "researcher"},
{"satisfied": False, "progress": False, "next": "writer"},
{"satisfied": False, "progress": False, "next": "writer"},
{"satisfied": False, "progress": True, "next": "writer"},
{"satisfied": True, "progress": True, "next": "writer"},
]
max_stall_count = 1
stalls = 0
for ledger in ledgers:
# Print "finish" and stop if the request is satisfied.
# Otherwise: no progress adds 1 to stalls, progress takes 1 away (never below 0).
# If stalls is now above max_stall_count, print "replan" and set stalls back to 0.
# Otherwise print "ask" and the next speaker, for example "ask writer".
pass
# Output must be exactly:
# ask researcher
# ask researcher
# ask writer
# replan
# ask writer
# finish
What does a Magentic manager do when the stall counter goes above max_stall_count?
Summary
- Magentic orchestration lets a manager plan an open task, direct agents step by step and replan when stuck.
MagenticBuilderneeds participants and a manager:manager_agent=wraps an agent in aStandardMagenticManager.- The manager keeps a task ledger (facts and plan) and writes a
MagenticProgressLedgerevery round; follow both throughMagenticOrchestratorEventevents. enable_plan_review=Truepauses with aMagenticPlanReviewRequest; answer withapprove()orrevise(feedback).- Always set
max_round_count, and tunemax_stall_countandmax_reset_count. Customise prompts onStandardMagenticManager, or subclassMagenticManagerBase.
Next: Declarative Agents and Workflows.
Finished reading? Tick it off to track your progress.