Sub topic 5
The orchestrator pattern
An orchestrator (also called a manager) is an agent that stays in charge of a task for its whole life. It breaks the request into subtasks, calls specialist agents as if they were tools, reads their results, and writes the final answer. This chapter covers how that works, how to build it, and where it fails.
I assume you can read Python and JSON. I also assume you know the basic agent loop (model, instructions, tools, repeat) and how tool calling works, as covered in earlier chapters.
The core idea
In a handoff, control of the conversation moves to another agent. In an orchestrator design, control never moves. The orchestrator is the only agent that talks to the user. Specialists are called, return a string, and disappear.
This works because of the "agent as a tool" idea. From the orchestrator's side, a specialist looks like any other function: it takes arguments, runs, and returns text. Inside, the specialist is a full agent with its own instructions, tools, and loop.
Why it keeps the pieces separate
Three properties make this pattern useful.
- Isolated context. Each specialist starts with a fresh message history containing only the task text. It does not see the user's full conversation or the other specialists' work unless the orchestrator passes it along. This keeps each specialist's context small and focused.
- Single point of control. Retries, limits, logging, and approval checks can all live in the orchestrator.
- Replaceable parts. You can swap a specialist's model, prompt, or tools without touching the others, as long as the task-in, string-out contract holds.
A runnable implementation
The following example contains the agent loop, a helper that wraps an agent as a tool, and a scripted stand-in for the model so you can run it without an API key. In a real system, call_model would call your LLM provider.
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class Agent:
name: str
instructions: str
tools: dict[str, Callable] = field(default_factory=dict)
handoffs: dict[str, "Agent"] = field(default_factory=dict)
def run(start: Agent, messages: list, call_model, max_turns: int = 10):
agent = start
for _ in range(max_turns):
reply = call_model(agent, messages)
if reply["type"] == "final":
return agent.name, reply["text"]
if reply["type"] == "handoff":
agent = agent.handoffs[reply["target"]]
continue
result = agent.tools[reply["name"]](**reply["args"])
messages.append({"role": "tool", "name": reply["name"], "content": str(result)})
raise RuntimeError("max_turns exceeded")
def as_tool(worker: Agent, call_model):
def tool(task: str) -> str:
# The worker starts with a fresh history containing only the task.
_, text = run(worker, [{"role": "user", "content": task}], call_model)
return text
return tool
def build_orchestrator(researcher: Agent, writer: Agent, call_model) -> Agent:
return Agent(
name="orchestrator",
instructions="Split the request into subtasks, call the specialists, and combine their answers.",
tools={
"research": as_tool(researcher, call_model),
"write": as_tool(writer, call_model),
},
)
def fake_model(agent, messages):
"""A scripted model: the orchestrator researches, then writes, then answers."""
if agent.name == "researcher":
return {"type": "final", "text": "Fact: handoffs transfer control."}
if agent.name == "writer":
return {"type": "final", "text": "Summary of -> " + messages[-1]["content"]}
used = [m["name"] for m in messages if m["role"] == "tool"]
last_tool = next((m["content"] for m in reversed(messages) if m["role"] == "tool"), "")
if "research" not in used:
return {"type": "tool", "name": "research", "args": {"task": "Find facts about handoffs"}}
if "write" not in used:
return {"type": "tool", "name": "write", "args": {"task": last_tool}}
return {"type": "final", "text": last_tool}
researcher = Agent("researcher", "Find facts.")
writer = Agent("writer", "Write clear prose.")
orchestrator = build_orchestrator(researcher, writer, fake_model)
print(run(orchestrator, [{"role": "user", "content": "Explain handoffs"}], fake_model))The output is:
('orchestrator', 'Summary of -> Fact: handoffs transfer control.')The orchestrator is the agent that returns the answer. Note that each tool result is appended to the orchestrator's messages, so the orchestrator accumulates context while the specialists stay small.
Designing the orchestrator's instructions
The orchestrator's prompt does most of the work. A useful prompt states:
- What each specialist is for, in one line each. The model chooses tools from their names and descriptions, so vague names such as
helper2lead to wrong calls. - What a good subtask looks like. Tell the orchestrator that each task string must be self-contained, because the specialist sees nothing else.
- How to combine results, for example "cite which specialist supplied each claim".
- When to stop. Say what counts as done, so the orchestrator does not keep calling specialists to polish an acceptable answer.
Also keep each specialist's tool list narrow. A researcher needs search. It does not need the refund API.
Common errors
Under-specified tasks. The most frequent bug is an orchestrator that writes task="summarize it". The specialist has no idea what "it" is. Fix this in the prompt, and consider validating that task strings are above a minimum length or contain required fields.
Context bloat in the orchestrator. Every specialist result lands in the orchestrator's history. After several calls with long outputs, the orchestrator slows down and loses focus. Have specialists return concise results, or have the tool wrapper truncate or summarize them.
Lost information. The reverse problem is a specialist that returns only a conclusion while the orchestrator needed the evidence. Define the return format, for example "answer, then a list of sources".
Unbounded delegation. If a specialist is itself an orchestrator, or if the orchestrator can call the same specialist repeatedly, cost grows quickly. Put a max_turns on every run, including the inner ones. The wrapper above does this through the default. Also consider a per-request budget on total tool calls.
Uncaught specialist exceptions. In the code above, a RuntimeError from a worker propagates and kills the whole run. Often a better choice is to catch it in the wrapper and return an error string the orchestrator can reason about:
def as_safe_tool(worker: Agent, call_model):
def tool(task: str) -> str:
try:
_, text = run(worker, [{"role": "user", "content": task}], call_model)
return text
except Exception as exc:
return f"ERROR from {worker.name}: {exc}"
return toolThe orchestrator can then retry with a clearer task, try a different specialist, or tell the user it could not finish. Retries and failure policy get a full chapter later.
Trade-offs
| Aspect | Orchestrator | Handoff |
|---|---|---|
| Who talks to the user | Always the orchestrator | The currently active agent |
| Specialist context | Only the task text | Usually the full history |
| Extra model calls | One per delegation, plus orchestrator turns | Fewer, since the new agent continues directly |
| Merging several results | Natural | Awkward, since only one agent is active |
| Debugging | One place to inspect | Follow the trail of transfers |
The orchestrator pays an overhead: the orchestrator reads every result and then rewrites it. For a task that needs one specialist and a direct reply, that is wasted effort, and a handoff is cheaper. The orchestrator pattern earns its cost when a request needs several specialists, when results must be combined, or when one agent must enforce rules over the whole workflow.
Checklist for building one
- Give every specialist a clear name, a one-line description, and a narrow tool list.
- Pass self-contained task strings, and include any needed facts in them.
- Set
max_turnson the orchestrator and on each specialist. - Catch specialist errors and return them as text.
- Limit the size of specialist outputs.
- Log each delegation: task in, result out, and elapsed time.
Exercise
In the example, the orchestrator calls write with task=last_tool, which is the researcher's output. The writer then returns "Summary of -> Fact: handoffs transfer control." Suppose the user's original request said "Write for beginners", but the orchestrator passes only the research text to the writer. What goes wrong, and how do you fix it?
Show answer
The writer sees only its task string, so it never learns the audience requirement. Its output will not match the user's request. Fix this by having the orchestrator include the requirement in the task, for example "Write a beginner-level summary of: <facts>". You can also enforce it by changing the tool signature to take an audience argument or by adding a rule to the orchestrator's prompt that every task must restate the user's constraints.
Exercise
A specialist raises an exception inside as_tool. Compare what happens with as_tool and with as_safe_tool. When might you prefer to let the exception propagate?
Show answer
With as_tool, the exception escapes through the orchestrator's run call and the whole request fails. With as_safe_tool, the orchestrator receives an "ERROR from ..." string as a tool result and can retry, switch specialists, or report the problem. Propagating can be preferable for unrecoverable faults such as bad credentials or a configuration bug, where retrying only wastes calls and you want the failure to be visible immediately.