Back to paths

Orchestrating multiple agents

Choose sequential, parallel, loop, graph or LLM-routed orchestration for a task, keep parallel branches from overwriting each other's state, and give every loop an exit condition and a cap.

advanced~30 min#agentic-ai#adk#multi-agent#workflows
Chapter 4Custom agentsLesson 7 of 8Show

Prerequisites: Building agents with ADK


More agents is not the goal

Splitting a task across several agents helps when the parts are distinct: each agent gets a short instruction and only the tools it needs, independent parts can run at once, and one part can check another. It hurts when the split adds model calls, latency and places for results to get lost.

The question to answer first is: do you know the order of the steps?

  • If you do, wire it up deterministically: the workflow runs the steps in the order you wrote, with no model deciding what comes next. That is cheaper, faster, testable and repeatable.
  • If you do not, because the next step depends on what the user says, let a model route: a coordinator agent delegates to specialist sub-agents by their descriptions (see the ADK lesson).

A common failure is an LLM router in front of steps that always run in the same order. Each request then pays for routing calls and sometimes takes the wrong path.

When should a model route between agents, and when should a fixed workflow?

The patterns

All the agents in one run share the session state, a key-value store for the conversation: one agent writes a key (in ADK, an LlmAgent with an output_key saves its final response under that key) and later agents read it, for example through a {key} placeholder in their instruction.

PatternShapeUse it when
A, then B, then CEach step needs the previous step's result
A, B and C at once (a fan-out), then a join that waits for all of themThe steps are independent and latency matters
Repeat A and B until done or cappedWork improves by iteration, such as draft and review
Nodes and edges, with routed branches, joins and back-edgesThe paths are known but branch or loop
LLM-routedA coordinator's model picks the next agentThe order cannot be known in advance

Graphs: branches and back-edges

A graph workflow is a set of nodes (agents or plain functions) joined by edges. A plain edge always runs the next node. A router is a node whose code returns a route name, such as BUG or BILLING, and a routed edge is taken only when that name is returned, so one router can send work down different branches. A back-edge is a routed edge that points to an earlier node, which is how a graph loops: the router returns RETRY to go round again and DONE to leave.

Sequential, parallel and loop are special cases of a graph. In ADK 2.0 you express all of them as graph workflows; the older SequentialAgent, ParallelAgent and LoopAgent classes still run in Python but are deprecated and scheduled for removal.

Agent design patterns

The table above says how agents are wired. A design pattern says what job each agent does inside that wiring. Google's exam guide asks you to apply agent design patterns without naming any, so the three below are this path's framing. Google's architecture guide to agent design patterns uses its own names: it calls generator–critic review and critique (or iterative refinement), and has no planning pattern; its nearest are hierarchical task decomposition and human-in-the-loop, which together cover plan-then-execute.

Design patternHow it worksBuilt withUse it when
(The agent loop)One agent decides, acts, observes the result and decides againA single LlmAgent with toolsThe steps depend on what each tool returns
(reflection)A generator drafts; a critic checks the draft against criteria and either approves it or sends back what to fixA loop: a LoopAgent with a writer, a critic and an exit (exit_loop), or a graph back-edge, plus a capQuality can be checked against stated criteria, and a second pass is worth the extra calls
A planner writes the whole plan first; a gate approves it; then executors carry out the stepsA planner agent, an approval gate (a person or a policy check), then a workflow or executor agents. ADK has no plan-approval feature as such: put tool confirmation (see Guardrails) on the tool that starts execution, so the run pauses with the plan until someone approvesThe work is long or costly, or takes actions that are hard to undo, so the plan is worth checking before anything runs

Generator–critic is the loop in this lesson's last section, so it needs the same exit and cap. In plan-then-execute the gate sits between planning and acting: an approval that comes after the steps have run approves nothing.

Name three agent design patterns and when each fits.

Run the refund task three ways

The simulation prepares a refund decision. An order agent loads the order; a fraud check and a policy check assess it; a summary agent decides. Run it as a sequential workflow, then as a parallel one, then try the parallel run with both checks writing the same state key. Finally switch to a loop, where a writer drafts the refund note and a reviewer approves or rejects it, and turn the reviewer's ability to end the loop off.

Simulation: orchestration-patterns

What you should see:

  • Parallel is faster. The two checks do not depend on each other, so running them at once cuts the run from 8 to 6 seconds.
  • A shared key loses a result. When both checks write check_result, the policy check finishes first and the fraud check overwrites it a second later. The summary sees only "low risk", cannot confirm the return window and hands the refund to a person: the run finished faster, without the result it needed.
  • A loop without an exit runs to its cap. With the reviewer unable to end the loop, the writer keeps drafting after approval until the cap stops it. With the exit on but a cap of 1 or 2, the loop stops before the note is approved.

In the simulation's shared-key run, why did the summary agent hand the refund to a person instead of approving it?

Parallel branches and shared state

Parallel branches run against the same session state. Two rules keep them safe:

  1. Each branch writes its own key, such as fraud_result and policy_result, or returns its output to a join node, which passes the collected outputs to the next step keyed by the name of each node that feeds it.
  2. No branch reads a key another branch is writing. If B needs A's result, B depends on A, and they belong in sequence.

Here is the refund workflow as an ADK 2.0 graph, with the two checks fanned out and joined:

from google.adk import Agent, Workflow
from google.adk.workflow import JoinNode
 
fraud_check = Agent(
    name="fraud_check",
    model="gemini-flash-latest",
    instruction="Assess the fraud risk of this refund: {order}",
    output_key="fraud_result",   # its own key
)
policy_check = Agent(
    name="policy_check",
    model="gemini-flash-latest",
    instruction="Check this refund against the 30-day return policy: {order}",
    output_key="policy_result",  # a different key
)
summary_agent = Agent(
    name="summary_agent",
    model="gemini-flash-latest",
    instruction="Decide on the refund. Fraud: {fraud_result}. Policy: {policy_result}.",
)
 
join_checks = JoinNode(name="join_checks")
 
root_agent = Workflow(
    name="refund_workflow",
    edges=[
        ("START", fraud_check, join_checks),
        ("START", policy_check, join_checks),
        (join_checks, summary_agent),
    ],
)

The two rows that start at START fan out, so the checks run at once; join_checks waits for both before summary_agent runs. (Here the order is assumed to be in state already as order.)

Every loop needs an exit and a cap

A loop repeats work until it is good enough, such as a writer and a reviewer taking turns. It needs two ways to stop:

  • An exit condition for success. In a LoopAgent, a sub-agent ends the loop by escalating, which signals the parent workflow to stop: a tool sets tool_context.actions.escalate = True, and the built-in exit_loop tool does exactly that. In a graph, a router returns a DONE route instead of the back-edge's RETRY route.
  • A cap for failure. In Python, a LoopAgent's max_iterations defaults to none, so without an escalation it never stops on its own. A graph cycle is not bounded automatically either: count attempts in state and route out at the cap.

Here is the review loop as a graph, with both stops in the router. The router accepts only an exact verdict: a substring test such as "APPROVED" in node_input would also match "NOT APPROVED" and send a rejected note. Treat anything that is not exactly APPROVED, including a malformed reply, as a rejection.

from google.adk import Context, Event, Workflow
 
MAX_ATTEMPTS = 3
 
# The reviewer's instruction says: reply with exactly APPROVED, or REJECTED: <reason>.
def review_router(ctx: Context, node_input: str):
    attempts = ctx.state.get("attempts", 0) + 1
    verdict = node_input.strip().upper()
    if verdict == "APPROVED":                  # exact match; anything else is a rejection
        return Event(route="DONE", state={"attempts": attempts})      # exit condition
    if attempts >= MAX_ATTEMPTS:
        return Event(route="GIVE_UP", state={"attempts": attempts})   # cap
    return Event(route="RETRY", state={"attempts": attempts})
 
root_agent = Workflow(
    name="refund_note_loop",
    edges=[
        ("START", draft_writer, reviewer, review_router),
        (review_router, {"RETRY": draft_writer, "DONE": send_note, "GIVE_UP": hand_to_person}),
    ],
)

ADK's run-level limit on model calls (max_llm_calls in the run configuration, The agent loop) is a last-resort backstop, not a loop design: by the time it fires, the loop has already spent its budget.

Sources

Show 10 sourcesHide sources
SourcePublisherWhat it supports
Workflow agents (opens in a new tab)github.comGoogle, Agent Development Kit documentationtemplate workflows deprecated in favour of graph-based and dynamic workflows; deterministic execution without consulting a model
Workflow patterns (opens in a new tab)github.comGoogle, Agent Development Kit documentationin Python and TypeScript, SequentialAgent, ParallelAgent and LoopAgent are deprecated and scheduled for removal; sub-agents write results to distinct keys in shared session state
Parallel agents (opens in a new tab)github.comGoogle, Agent Development Kit documentationsession state is shared across branches; give each sub-agent an output_key; do not rely on reading a key another branch is still writing
Loop agents (opens in a new tab)github.comGoogle, Agent Development Kit documentationmax_iterations defaults to None in Python; escalate via tool_context.actions.escalate; the exit_loop tool
"Graph workflows" and "Routes" (opens in a new tab)and docs/graphs/routes.mdgithub.comGoogle, Agent Development Kit documentationWorkflow with edges; routed edges; JoinNode fan-out and join; loops as back-edges, a cycle must contain a routed edge and is not bounded automatically
Data handling (opens in a new tab)github.comGoogle, Agent Development Kit documentationstate across nodes; instruction placeholders read session state; output_key
Choose a design pattern for your agentic AI system (opens in a new tab)docs.cloud.google.comGoogle CloudReAct, loop, review and critique, iterative refinement, coordinator, hierarchical task decomposition, human-in-the-loop
Professional Cloud Agentic AI Architect exam guideGoogle Cloudasks candidates to apply agent design patterns; it names none, so the three in this lesson are the path's framing
Tool confirmation (opens in a new tab)github.comGoogle, Agent Development Kit documentationrequire_confirmation pauses a tool until a person or system responds
Agent Development Kit, adk-python source, src/google/adk/agents/sequential_agent.pyGoogleSequentialAgent is deprecated in favour of Workflow

Suggested videos

Show 3 videosHide videos

Review

Flashcards1 / 3

Name the orchestration patterns and when each fits.

Check yourself

Quick exam1 / 9 · 0 correct

An invoice agent always extracts the fields, then validates them against the purchase order, then posts the invoice. Which orchestration fits?

Go deeper

Your notes on this lesson