SwarmRouter is the highest-level multi-agent abstraction in the framework. Pass it a list of agents and a swarm_type — it builds the matching orchestrator (SequentialWorkflow, ConcurrentWorkflow, HierarchicalSwarm, MixtureOfAgents, HeavySwarm, etc.) and forwards run() calls to it. To switch architectures, change one string.
The underlying swarm is built lazily on the first run() call and cached on the instance — repeated calls reuse it (keyed by swarm_type, agent identities, and construction-time config).
When to Use
- Flexible orchestration — switch between swarm types without rewriting code
- Strategy comparison — A/B different architectures on the same task
- Unified interface — one API for every supported swarm
- Dynamic selection — choose
swarm_typeat runtime - Production deployments — standardized swarm management with optional autosave
Key Features
- 14 concrete swarm types (see the note below on
"auto") - Factory pattern with O(1) lookup and per-instance swarm cache
- Pre-flight reliability checks
- Ordered fallback to other swarm types when one fails (
fallback_swarms) - Token usage summed across the whole swarm (
router.usage) - Optional autosave of
config.json/state.json/metadata.json - Multi-agent collaboration prompt injection (
SequentialWorkflowandAgentRearrange) - Per-swarm-type specialized parameters (HeavySwarm, AgentRearrange, GroupChat, etc.)
- Inherits
SerializableMixin—to_dict()is available for telemetry / persistence
Supported Swarm Types
Basic Example
Key Parameters
SwarmType
default:"\"SequentialWorkflow\""
Which orchestrator to instantiate. See the list above.
List[Union[Agent, Callable]]
required
The agent roster the swarm will use. The role of each agent depends on
swarm_type (e.g. for DebateWithJudge the first two are debaters and the third is the judge; for MixtureOfAgents the last agent is the aggregator).str
Stable identifier for this router instance. Auto-generated if omitted.
str
default:"\"swarm-router\""
Human-readable name. Used for log lines and autosave directory naming.
str
default:"\"Routes your task to the desired swarm\""
Free-text description of what this router is for.
int
default:"1"
Iteration count for the underlying swarm. Semantics depend on
swarm_type (e.g. for MixtureOfAgents this is the number of layers).OutputType
default:"\"dict\""
How the final swarm output is formatted.
bool
default:"False"
When
True, save config.json at init and state.json + metadata.json after each run.bool
default:"True"
If
True, use a timestamp in the autosave directory name; otherwise use a UUID.str
Required when
swarm_type="AgentRearrange". Flow DSL like "A -> B, C -> D".List[SwarmType]
Swarm types to try, in order, when the primary
swarm_type fails. See Fallback swarms.bool
default:"False"
Deliver the multi-agent collaboration preamble to every agent as a system turn at run time. Your
Agent objects are not modified. Only SequentialWorkflow and AgentRearrange deliver it; other swarm types log a warning and ignore it.bool
default:"False"
When
True, every agent is told about every other agent at the start of a run. Delivered the same way as the collaboration preamble, so only SequentialWorkflow and AgentRearrange honor it.Any
Stored on the router but not passed to the swarm. After each run,
router.conversation points at the swarm’s own conversation.Dict[Any, Any]
Stored on the router. No swarm factory reads it.
bool
default:"False"
Emit info / debug logs (reliability check, cache hits, swarm creation).
Swarm-Specific Parameters
AgentRearrange
str
required
Flow DSL (e.g.
"researcher -> writer, editor").HeavySwarm
str
default:"\"gpt-5.4\""
Model for the HeavySwarm question agent.
str
default:"\"gpt-5.4\""
Model for HeavySwarm workers.
bool
default:"True"
Print per-agent output for HeavySwarm.
Literal["default", "medium", "heavy"]
default:"\"default\""
HeavySwarm architecture variant. See the Heavy Swarm docs.
int
default:"1"
Iteration count for HeavySwarm multi-loop refinement.
int
default:"900"
Per-worker wall-clock cap (seconds) for HeavySwarm.
List[Callable]
Tools passed to HeavySwarm workers.
HierarchicalSwarm
str
default:"\"gpt-5.4\""
Model used by the auto-created director agent.
Dict[str, Any]
Extra
Agent keyword arguments for the auto-created director. Every key is forwarded
to the director’s Agent; agent_name, model_name, system_prompt, temperature,
and top_p override the corresponding HierarchicalSwarm defaults (including
director_model_name).Both parameters are forwarded only when
swarm_type="HierarchicalSwarm"; other swarm
types ignore them.CouncilAsAJudge
str
default:"\"gpt-5.4\""
Passed to
CouncilAsAJudge as model_name, so it sets the model for every dimension judge. The aggregator keeps its own aggregation_model_name default ("gpt-5.4").LLMCouncil
str
default:"\"gpt-5.1\""
Chairman model for
LLMCouncil.Advanced Features
Autosave
Tell Every Agent About Every Other Agent
Methods
run(task=None, img=None, tasks=None, ...)
Execute the configured swarm with a single task (or a list of tasks, when the underlying swarm accepts one).
__call__(task, img=None, imgs=None, ...)
The router is directly callable as a shortcut for run().
batch_run(tasks, img=None, imgs=None, ...)
Process multiple tasks sequentially. Re-uses the cached underlying swarm.
concurrent_run(tasks, imgs=None, ...)
Run multiple tasks through run() in parallel. Results come back in task order. imgs, if given, pairs one image with each task.
usage
Read-only property. Sums Agent.usage over every agent the router’s swarms have run, including agents a swarm builds for itself, such as a HierarchicalSwarm director. Keys: input_tokens, output_tokens, cached_tokens, reasoning_tokens, total_tokens. See Token usage.
to_dict()
Inherited from SerializableMixin. Returns a JSON-friendly snapshot of the router configuration.
Use Cases
Strategy Comparison
Dynamic Swarm Selection
Fallback Swarms
Passfallback_swarms instead of writing your own retry. When the primary swarm raises, while being built or while running, the router builds the next type from the same agents and gives it the same task. The first swarm to complete wins.
fallback_swarms is validated at construction like swarm_type. If it includes "AgentRearrange", rearrange_flow must be set. With autosave on, metadata.json records which swarm served the run and every failed attempt.
Factory Pattern
The router maintains a per-instance factory dispatch table and a swarm cache:Reliability Checks
reliability_check() runs automatically during construction:
Error Handling
SwarmRouterConfigError is raised at construction. At run time, a router without fallback_swarms re-raises the underlying swarm’s own exception unchanged. With fallback_swarms, SwarmRouterRunError is raised only after every swarm in the chain has failed; its message names each attempt and its __cause__ is the last error.
Best Practices
Start simple: begin with
SequentialWorkflow, then escalate to a heavier topology only when you can name the failure mode it fixes.- Match
swarm_typeto the task — pipelines for known shapes, ensembles for quality, hierarchies for decomposition. - Validate required params — e.g.
AgentRearrangeneedsrearrange_flow;HeavySwarmhonors theheavy_swarm_*knobs. - Plan for failure — set
fallback_swarmsfor a cheaper backup architecture, and catchSwarmRouterRunErroraroundrun()andSwarmRouterConfigErroraround construction. - Test with simple types first — confirm agents and tools work, then swap in heavier swarms.
- Enable autosave for production — durable
config.json/state.json/metadata.jsonmake incident analysis far cheaper.
Configuration Reference
Complete example with the most common options:Related Architectures
- Sequential Workflow
- Concurrent Workflow
- Agent Rearrange
- Heavy Swarm
- Hierarchical Swarm
- SwarmRouter API reference
- Token usage
- Structures Catalog — full enumeration of every multi-agent structure
- All Architectures Overview