SwarmAgent
A peer-to-peer multi-agent pattern where agents hand off control to each other directly — no central coordinator.
Import path: agentflow.prebuilt.agent
Concept
In a supervisor pattern a single coordinator routes all work. In a swarm, any agent can decide to hand off to any other agent it knows about. This produces a flexible, decentralized flow with no bottleneck at the center.
Full graph — three-member example
Per-member routing logic
Each member node gets its own routing function. After every LLM call it inspects state.context[-1].tools_calls and picks a branch in priority order:
for tc in last.tools_calls:
is_handoff, target = is_handoff_tool(tc["name"]) # "transfer_to_X" → target = "x"
if is_handoff and target.upper() in allowed_set:
return target.upper() # route to that member
if tool_node_name is not None:
return tool_node_name # run regular tools
return END
Handoff tools are never executed
SwarmAgent auto-generates transfer_to_<name> functions and injects them into each member's ToolNode. When the LLM calls one, the routing function intercepts it and navigates the graph — the tool body never runs. No spurious tool role messages appear in the conversation history.
Mini ReAct loop per member
A member with regular tools gets a dedicated <NAME>_TOOL node and a <NAME>_TOOL → NAME edge. This gives each member its own tool loop before it decides to hand off or stop.
can_handoff_to semantics
| Value | Behaviour |
|---|---|
None | Can hand off to all other members |
["A", "B"] | Can hand off only to A and B |
[] | Terminal — no handoffs; always routes to END |