Orchestration patterns for AI agents

Once a task needs more than one model call or more than one agent, something has to decide who runs next. This guide explains the main orchestration patterns, how to build each one, and how to keep a multi-step system reliable.

Orchestration in 60 seconds

  • What it is: the control layer that sequences model calls, tools, and agents.
  • Eight patterns: single agent, pipeline, router, parallel fan-out and merge, supervisor with workers, graph or state machine, peer handoff, and critic loops. Human checkpoints can be added to any of them.
  • The key distinction: in a workflow, your code decides the path. In an agent, the model decides the path. Use the least freedom that solves the task.
  • Reliability comes from the basics: timeouts, retries, idempotent steps, step budgets, and traces.
  • Default choice: a single agent or a short pipeline. Add a more complex pattern only after measuring a failure that it fixes.

Workflow or agent? The question to ask first

Design guides for AI systems commonly draw one line, and it is the most useful one on this page. In a workflow, the path through the steps is written in your code: step one, then step two, with a branch here and a loop there. The model fills in each step, but your code decides what runs next. In an agent, the model decides what to do next, within the tools and limits you give it.

A workflow is predictable, cheaper, and easier to test. An agent is flexible and can handle tasks you did not anticipate, at the cost of variable behaviour and cost. Every pattern below sits somewhere on that line. Choose the point on the line by asking how well you know the steps in advance. If you can write them down, write them down.

What orchestration actually does

Whatever the pattern, the orchestrator has five jobs. It keeps state, meaning the goal, the intermediate results, and where the run is. It routes work to the next step or agent. It passes data between steps in a form each step can use. It handles failure: a timeout, a bad output, a missing tool. And it records what happened so you can debug and evaluate it. A pattern is a particular way to arrange those five jobs.

Four of the patterns, drawn side by side.

A guide to each type

Every type on this page has its own in-depth guide with a diagram, a worked example, code, design decisions, metrics, and notes for your role.

The patterns

1. Single agent with tools

One model, one loop, a set of tools. This is the baseline and it is more capable than people expect. Before adding a second agent, check whether a better tool description, a clearer prompt, or a smaller tool set fixes the problem. Many multi-agent systems exist because a single agent was given too many tools and a vague prompt, not because the task needed more than one agent. The loop itself is shown on the agent types page.

  • Use when: the task fits one role and fewer than about ten well-described tools.
  • Strength: least moving parts, easiest to trace.
  • Limit: one long context carries everything, so very long tasks degrade.

Read the full guide to the single agent: how it works, a worked example, code, design decisions, and how to measure it.

2. Sequential pipeline (prompt chaining)

A pipeline splits a task into fixed stages. The output of each stage is the input to the next. The stages may use different prompts, different models, and different tools. Because each stage does one narrow thing, each is easier to write, test, and replace. You can also add a gate between stages: check the output of stage two before spending money on stage three.

A pipeline with a quality gate between stages (illustrative) (python)
# Illustrative: your code decides the order; the model fills in each step.
# call_model() is a placeholder for a model call with a stage-specific prompt.

def support_pipeline(ticket):
    summary = call_model('summarise', ticket.text)
    category = call_model('classify', summary)
    if category not in {'billing', 'technical', 'general'}:
        return escalate_to_human(ticket, reason='unknown category')  # gate: stop early
    draft = call_model('draft_reply', summary, category)
    checked = call_model('check_tone_and_facts', draft, ticket.text)
    return checked
  • Use when: the steps are known and always the same.
  • Strength: predictable cost and behaviour; each stage can be tested alone.
  • Limit: cannot adapt if a task needs a different order.

Read the full guide to the pipeline: how it works, a worked example, code, design decisions, and how to measure it.

3. Router (dispatcher)

A router looks at the request and chooses one path. The classifier can be rules, a small cheap model, or an embedding match. The chosen path may be a different prompt, a specialist agent, or a different model sized to the difficulty. Routing is the cheapest way to handle mixed traffic, because the easy majority of requests never reach the expensive path.

A router with a safe default (illustrative) (python)
# Illustrative: classify first, then hand off to one specialist.

ROUTES = {
    'billing': billing_agent,
    'technical': technical_agent,
    'general': faq_agent,
}

def route(message):
    label, confidence = classifier(message)  # a small model, or rules
    if confidence < 0.7:
        return faq_agent(message)  # a safe default when the router is unsure
    return ROUTES.get(label, faq_agent)(message)
  • Use when: requests fall into distinct categories handled by different logic.
  • Strength: low cost and clear ownership of each path.
  • Limit: a wrong route gives a weak answer, so log the route and review mistakes.

Read the full guide to the router: how it works, a worked example, code, design decisions, and how to measure it.

4. Parallel fan-out and merge

When parts of a task do not depend on each other, run them at the same time and combine the results. This cuts the waiting time to that of the slowest branch. It is also used for voting: run the same question several times, or through several prompts, and take the majority or the best-scoring answer. The hard part is the merge step. It must handle a branch that failed, and it must say so when branches disagree.

Fan-out with partial failure handling (illustrative) (python)
# Illustrative: run independent branches together, keep the ones that worked.
import asyncio

async def research(question, topic):
    return await call_model_async('research', question, topic)

async def fan_out(question):
    topics = ['pricing', 'security', 'integrations']
    results = await asyncio.gather(
        *(asyncio.wait_for(research(question, t), timeout=30) for t in topics),
        return_exceptions=True,
    )
    good = {t: r for t, r in zip(topics, results) if not isinstance(r, Exception)}
    failed = [t for t in topics if t not in good]
    return merge(question, good, note=f'No result for: {failed}' if failed else None)
  • Use when: sub-tasks are independent, or you want several attempts to compare.
  • Strength: lower latency; wider coverage.
  • Limit: cost multiplies with the number of branches, and merging conflicting results needs care.

Read the full guide to the parallel fan-out: how it works, a worked example, code, design decisions, and how to measure it.

5. Supervisor with workers (orchestrator-worker)

A supervisor agent receives the goal, breaks it into sub-tasks, assigns each to a specialist worker, and combines the results. Unlike a pipeline, the sub-tasks are chosen at run time, because the supervisor decides them from the goal. This suits tasks whose shape varies, such as a research request that may need three searches or ten. The supervisor is also the single place where the whole run is visible, which helps tracing. It is a bottleneck and a single point of failure, so give it a step budget and a clear output format for workers.

A supervisor that plans and delegates (illustrative) (python)
# Illustrative: the supervisor plans; workers do the narrow jobs.

WORKERS = {'search': search_worker, 'analyse': analysis_worker, 'write': writing_worker}

def supervisor(goal, max_tasks=8):
    plan = planner_model(goal)[:max_tasks]  # list of tasks with an owner and dependencies
    results = {}
    for task in plan:
        worker = WORKERS.get(task.owner)
        if worker is None:
            results[task.id] = 'No worker for this task.'
            continue
        inputs = {dep: results[dep] for dep in task.depends_on if dep in results}
        results[task.id] = worker(task.description, inputs)
    return synthesiser_model(goal, results)
  • Use when: the number and kind of sub-tasks are not known in advance.
  • Strength: flexible, with one place to observe and limit the run.
  • Limit: the supervisor's plan can be wrong, and its context fills up with worker output.

Read the full guide to the supervisor and workers: how it works, a worked example, code, design decisions, and how to measure it.

6. Graph or state machine

A graph describes the steps as nodes and the possible moves as edges. Each node reads and updates shared state, and an edge may depend on that state: after grading, go to generation if the results are good, back to retrieval if they are weak and tries remain, or to a fallback if tries have run out. The graph makes loops, branches, and retries explicit, so the allowed paths are visible in one place and can be tested. Many frameworks offer this style, and it is also easy to write by hand.

A small state graph with a step limit (illustrative) (python)
# Illustrative: nodes update state; edges choose the next node.

def run_graph(nodes, edges, state, start='retrieve', max_steps=12):
    node = start
    for _ in range(max_steps):
        if node == 'done':
            return state
        state = nodes[node](state)
        node = edges[node](state)
    raise RuntimeError('Step limit reached; return a partial result instead.')

nodes = {'retrieve': retrieve, 'grade': grade, 'generate': generate, 'fallback': fallback}
edges = {
    'retrieve': lambda s: 'grade',
    'grade': lambda s: 'generate' if s['good'] else ('retrieve' if s['tries'] < 2 else 'fallback'),
    'generate': lambda s: 'done',
    'fallback': lambda s: 'done',
}
  • Use when: the flow has loops, branches, and retries that need to be explicit and testable.
  • Strength: the allowed paths are visible and can be checked before running.
  • Limit: the graph can become large; keep each node small.

Read the full guide to the state graph: how it works, a worked example, code, design decisions, and how to measure it.

7. Peer handoff (swarm)

In a handoff pattern, an agent that reaches the edge of its role passes the conversation, with its state, directly to another agent. There is no central supervisor. A support assistant hands a billing question to the billing agent, which may hand a fraud concern to the security agent. It feels natural to users, because the conversation continues. It is harder to trace and to cap, so every handoff should be logged and the total number of handoffs limited.

  • Use when: roles are clearly separated and the conversation, not a task list, is the unit of work.
  • Strength: no central bottleneck; natural for conversations.
  • Limit: ping-pong loops between agents, and a harder path to debug.

Read the full guide to the peer handoff: how it works, a worked example, code, design decisions, and how to measure it.

8. Critic and reviewer loops

One agent produces, another reviews against a rubric, and the producer revises with the feedback. This works well for writing and code, where quality is easy to describe and mistakes are easy to spot with fresh eyes. Cap the number of rounds, use an objective check where one exists (a test suite, a schema, a link checker), and decide what happens if the cap is reached: usually, return the best draft with a flag for human review.

A reviewer loop with a round cap (illustrative) (python)
# Illustrative: revise until approved, or stop and flag for a human.

def write_with_review(task, max_rounds=3):
    draft = writer(task)
    for round_number in range(max_rounds):
        review = reviewer(task, draft)  # returns approved plus comments
        if review.approved:
            return {'text': draft, 'needs_human': False}
        draft = writer(task, feedback=review.comments, previous=draft)
    return {'text': draft, 'needs_human': True}  # cap reached: do not loop forever
  • Use when: quality can be described in a rubric, and a first draft is rarely enough.
  • Strength: catches errors a single pass misses.
  • Limit: extra cost per task; a reviewer built on the same model can share the writer's blind spots.

Read the full guide to the critic loop: how it works, a worked example, code, design decisions, and how to measure it.

Human checkpoints (an addition to any pattern)

A human checkpoint pauses the run until a person approves, edits, or rejects something. It belongs before any irreversible step: sending a message to a customer, moving money, deleting data, or publishing. Design the pause as part of the state: the run is saved, a task appears for a reviewer, and the run resumes from the saved state when they decide. A run that waits in memory for a person is a bug waiting for a server restart.

Read the full guide to the human checkpoint: how it works, a worked example, code, design decisions, and how to measure it.

The reliability basics

The patterns above describe the happy path. Production systems spend most of their effort on everything else. The checklist below applies to every pattern.

  • Timeouts on every call. A model or tool call that hangs should not hold the whole run.
  • Retries with backoff, and only for safe steps. Retry reads freely. Retry writes only if they are idempotent, meaning running them twice has the same effect as once.
  • A step budget and a cost budget for the whole run, with a useful partial result when a budget ends.
  • Saved state at each step, so a crashed run can resume and a human checkpoint can wait safely.
  • Structured outputs between steps. Ask for a defined format and validate it, so one step's mistake does not silently corrupt the next.
  • Traces. Record each step's input, output, duration, cost, and the decision that led to the next step.
A step wrapper with timeout, retry, and an idempotency key (illustrative) (python)
# Illustrative: run one step safely. Writes carry an idempotency key so a retry cannot double-apply.
import time, uuid

def run_step(name, fn, args, *, is_write=False, retries=2, timeout=30):
    key = str(uuid.uuid4()) if is_write else None  # generate once per logical step
    for attempt in range(retries + 1):
        try:
            result = call_with_timeout(fn, args, timeout=timeout, idempotency_key=key)
            trace.record(name, args, result, attempt=attempt)
            return result
        except TimeoutError:
            if attempt == retries:
                raise
            time.sleep(2 ** attempt)  # backoff: 1s, 2s, 4s

Where protocols fit

Two kinds of standard are emerging, and they solve different problems. A tool protocol such as the Model Context Protocol (MCP) standardises how a model-based application connects to tools and data sources, so a tool written once can be used by many applications. An agent-to-agent protocol such as A2A is aimed at letting agents built by different teams or vendors discover each other and exchange tasks. Neither replaces orchestration: you still need to decide who calls whom, with what limits. These protocols are young and still changing, so check the current specifications before you depend on them.

The patterns compared

PatternWho decides the pathBest forMain risk
Single agentThe model, in one loopMost tasks, to start withLong context on long tasks
PipelineYour code, fixed orderKnown, repeatable stepsCannot adapt to a different shape
RouterA classifier, then a fixed pathMixed traffic with distinct categoriesWrong route
Parallel fan-outYour code splits and mergesIndependent sub-tasks, votingCost, and merging conflicts
Supervisor and workersA supervisor model plansTasks whose shape variesBottleneck and bad plans
Graph or state machineYour edges, using stateLoops, retries, branchesLarge, hard-to-read graphs
Peer handoffEach agent hands overConversational supportPing-pong loops, hard tracing
Critic loopReviewer decides to continueWriting and codeShared blind spots, extra cost

How to choose

  • Write the steps down. If you can, use a pipeline or a graph, and keep the model out of the control flow.
  • Start with one agent if the task fits a single role. Improve tools and prompts before adding agents.
  • Add a router when traffic splits into categories with different needs.
  • Add parallel branches only for independent work where latency matters.
  • Add a supervisor when the shape of the work is decided at run time.
  • Add critic loops where quality is checkable, and cap the rounds.
  • Add human checkpoints before anything irreversible.

What this means for your role

Common mistakes

Further reading

Orchestration is where the engineering of an AI product lives. The model is one part of it. The rest is ordinary reliability work, applied carefully.

Search topics

↑↓ to move · Enter to open · Esc to close