Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.swarms.world/llms.txt

Use this file to discover all available pages before exploring further.

Overview

The SwarmRouter class dynamically routes tasks to different swarm architectures based on user selection or automatic matching. It provides a unified interface for managing multiple swarm types and enables flexible task execution with logging, type validation, and metadata capture.

Class Definition

from swarms.structs.swarm_router import SwarmRouter

Parameters

id
str
default:"generate_api_key(prefix='swarm-router')"
Unique identifier for the SwarmRouter instance
name
str
default:"swarm-router"
Name identifier for the SwarmRouter instance
description
str
default:"Routes your task to the desired swarm"
Description of the SwarmRouter’s purpose
max_loops
int
default:"1"
Maximum number of execution loops
agents
List[Union[Agent, Callable]]
default:"[]"
List of Agent objects or callables to use in the swarm
swarm_type
SwarmType
default:"SequentialWorkflow"
Type of swarm to use. Options: “AgentRearrange”, “MixtureOfAgents”, “SequentialWorkflow”, “ConcurrentWorkflow”, “GroupChat”, “MultiAgentRouter”, “HierarchicalSwarm”, “HeavySwarm”, “MajorityVoting”, “CouncilAsAJudge”, “BatchedGridWorkflow”, “LLMCouncil”, “DebateWithJudge”, “RoundRobin”
autosave
bool
default:"False"
Whether to enable autosaving of swarm configuration, state, and metadata to workspace_dir/swarms/SwarmRouter/-/
autosave_use_timestamp
bool
default:"True"
If True, use timestamp in directory name; if False, use UUID
rearrange_flow
str
Flow configuration string for AgentRearrange swarm type
return_json
bool
default:"False"
Whether to return results as JSON
auto_generate_prompts
bool
default:"False"
Whether to auto-generate agent prompts
shared_memory_system
Any
Shared memory system for agents
rules
str
Rules to inject into every agent’s system prompt
documents
List[str]
default:"[]"
List of document file paths to use
output_type
OutputType
default:"dict-all-except-first"
Output format type. Supported: ‘str’, ‘string’, ‘list’, ‘json’, ‘dict’, ‘yaml’, ‘xml’
multi_agent_collab_prompt
bool
default:"True"
Whether to enable multi-agent collaboration prompts
verbose
bool
default:"False"
Enable verbose logging output

Available Swarm Types

  • AgentRearrange: Optimizes agent arrangement for task execution with custom flow configuration
  • MixtureOfAgents: Combines multiple agent types for diverse task perspectives
  • SequentialWorkflow: Executes tasks sequentially through agents in order
  • ConcurrentWorkflow: Executes tasks in parallel across agents
  • GroupChat: Enables collaborative discussion and consensus-building
  • MultiAgentRouter: Intelligent routing and load balancing across agents
  • HierarchicalSwarm: Layered decision-making with director and worker agents
  • HeavySwarm: High-capacity processing with specialized question generation and synthesis
  • MajorityVoting: Democratic decision-making with voting mechanisms
  • CouncilAsAJudge: Deliberative decision-making with expert evaluation
  • BatchedGridWorkflow: Batched task processing across agent grids
  • LLMCouncil: Council-based deliberation with chairman coordination
  • DebateWithJudge: Structured debate with pro, con, and judge agents
  • RoundRobin: Cycles through agents in round-robin fashion

Methods

reliability_check()

def reliability_check(self) -> None
Performs reliability checks on swarm configuration to validate essential parameters. Raises:
  • SwarmRouterConfigError: If swarm configuration is invalid

run()

def run(
    self,
    task: Optional[str] = None,
    img: Optional[str] = None,
    tasks: Optional[List[str]] = None,
    *args,
    **kwargs,
) -> Any
Executes a task on the selected swarm type. Parameters:
task
str
The task to be executed by the swarm
img
str
Optional image input for the task
tasks
List[str]
Optional list of tasks for batch processing (used by BatchedGridWorkflow)
Returns:
result
Any
The result of the swarm’s execution, format depends on output_type setting
Raises:
  • SwarmRouterRunError: If task execution fails

batch_run()

def batch_run(
    self,
    tasks: List[str],
    img: Optional[str] = None,
    imgs: Optional[List[str]] = None,
    *args,
    **kwargs,
) -> List[Any]
Executes multiple tasks in sequence. Parameters:
tasks
List[str]
required
A list of tasks to be executed by the swarm
img
str
Optional image input for all tasks
imgs
List[str]
Optional list of images corresponding to each task
Returns:
results
List[Any]
A list of results from the swarm’s execution for each task

concurrent_run()

def concurrent_run(
    self,
    task: str,
    img: Optional[str] = None,
    imgs: Optional[List[str]] = None,
    *args,
    **kwargs,
) -> Any
Executes a task using concurrent execution with ThreadPoolExecutor. Parameters:
task
str
required
The task to be executed by the swarm
img
str
Optional image input for the task
Returns:
result
Any
The result of the swarm’s concurrent execution

to_dict()

def to_dict(self) -> Dict[str, Any]
Converts all attributes of the SwarmRouter to a dictionary for serialization. Returns:
config
Dict[str, Any]
A dictionary representation of the SwarmRouter’s configuration and state

Usage Example

from swarms.structs.agent import Agent
from swarms.structs.swarm_router import SwarmRouter

# Create agents
agent1 = Agent(
    agent_name="Research-Agent",
    system_prompt="Research specialist",
    model_name="claude-sonnet-4-6"
)

agent2 = Agent(
    agent_name="Analysis-Agent",
    system_prompt="Analysis specialist",
    model_name="claude-sonnet-4-6"
)

# Create SwarmRouter with SequentialWorkflow
router = SwarmRouter(
    name="research-analysis-swarm",
    description="A swarm for research and analysis tasks",
    agents=[agent1, agent2],
    swarm_type="SequentialWorkflow",
    max_loops=1,
    autosave=True,
    verbose=True
)

# Execute a task
result = router.run(
    task="Research the latest trends in AI and provide analysis"
)

print(result)

Autosave Configuration

When autosave=True, the SwarmRouter automatically saves:
  1. config.json: Initial configuration on initialization
  2. state.json: Current state after each run
  3. metadata.json: Execution metadata including results
Files are saved to: workspace_dir/swarms/SwarmRouter/{swarm-name}-{timestamp}/

Source Code

View the source code on GitHub