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
- 17 swarm types supported (plus
"auto"for automatic routing) - Factory pattern with O(1) lookup and per-instance swarm cache
- Pre-flight reliability checks
- Optional autosave of
config.json/state.json/metadata.json - Shared memory injection across agents
- Multi-agent collaboration prompt injection
- 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-all-except-first\""
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".Memory backend injected into every agent’s
long_term_memory.bool
default:"True"
Append the multi-agent collaboration preamble to every agent’s system prompt.
bool
default:"False"
When
True, every agent is told about every other agent at the start of a run.Any
Pre-existing conversation object to seed the swarm with.
Dict[Any, Any]
Optional per-agent config overrides.
bool
default:"False"
When
True, snapshot each agent’s config into self.agent_config.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
CouncilAsAJudge
str
default:"\"gpt-5.4\""
Model used as the council judge.
LLMCouncil
str
default:"\"gpt-5.1\""
Chairman model for
LLMCouncil.Advanced Features
Shared Memory
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(...)
Run multiple tasks concurrently.
to_dict()
Inherited from SerializableMixin. Returns a JSON-friendly snapshot of the router configuration.
Use Cases
Strategy Comparison
Dynamic Swarm Selection
Production Pipeline with Fallback
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
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. - Wrap
run()in try/except — catchSwarmRouterRunErrorandSwarmRouterConfigErrorexplicitly in production. - 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
- Structures Catalog — full enumeration of every multi-agent structure
- All Architectures Overview