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 dispatches tasks to any supported multi-agent architecture through a single, uniform interface. Set swarm_type to choose the architecture; pass the same agent list and call run(task) regardless of which architecture you select. It also handles:
  • Validated construction of the underlying swarm (reliability_check)
  • Optional autosave of config / state / metadata to the workspace
  • Multi-agent collaboration prompt injection
  • Optional rules / shared-memory injection
  • O(1) factory dispatch with internal caching

Import

from swarms.structs.swarm_router import (
    SwarmRouter,
    SwarmType,
    SwarmRouterConfig,
    SwarmRouterRunError,
    SwarmRouterConfigError,
)

SwarmType

SwarmType is a typing.Literal enumerating every accepted swarm_type string. Any value outside this set raises SwarmRouterConfigError at construction time.
SwarmType = Literal[
    "AgentRearrange",
    "MixtureOfAgents",
    "SequentialWorkflow",
    "ConcurrentWorkflow",
    "GroupChat",
    "MultiAgentRouter",
    "AutoSwarmBuilder",
    "HierarchicalSwarm",
    "auto",
    "MajorityVoting",
    "CouncilAsAJudge",
    "HeavySwarm",
    "BatchedGridWorkflow",
    "LLMCouncil",
    "DebateWithJudge",
    "RoundRobin",
    "PlannerWorkerSwarm",
]
"auto" and "AutoSwarmBuilder" are listed in the Literal but are not dispatched by the current factory (it handles 15 of the 17 values). Selecting either passes construction validation, then raises ValueError during run(). Use one of the other 15 values.

Constructor

SwarmRouter(
    id: str = generate_api_key(prefix="swarm-router"),
    name: str = "swarm-router",
    description: str = "Routes your task to the desired swarm",
    max_loops: int = 1,
    agents: List[Union[Agent, Callable]] = [],
    swarm_type: SwarmType = "SequentialWorkflow",
    autosave: bool = False,
    rearrange_flow: Optional[str] = None,
    return_json: bool = False,
    auto_generate_prompts: bool = False,
    shared_memory_system: Any = None,
    rules: Optional[str] = None,
    documents: List[str] = [],
    output_type: OutputType = "dict-all-except-first",
    speaker_fn: Optional[Callable] = None,
    load_agents_from_csv: bool = False,
    csv_file_path: Optional[str] = None,
    return_entire_history: bool = True,
    multi_agent_collab_prompt: bool = True,
    list_all_agents: bool = False,
    conversation: Any = None,
    agents_config: Optional[Dict[Any, Any]] = None,
    speaker_function: Optional[str] = None,
    heavy_swarm_loops_per_agent: int = 1,
    heavy_swarm_question_agent_model_name: str = "gpt-4.1",
    heavy_swarm_worker_model_name: str = "gpt-4.1",
    heavy_swarm_swarm_show_output: bool = True,
    heavy_swarm_use_grok_agents: bool = False,
    telemetry_enabled: bool = False,
    council_judge_model_name: str = "gpt-5.4",
    verbose: bool = False,
    worker_tools: Optional[List[Callable]] = None,
    aggregation_strategy: str = "synthesis",
    chairman_model: str = "gpt-5.1",
    autosave_use_timestamp: bool = True,
    *args,
    **kwargs,
)

Core parameters

id
str
default:"generate_api_key(prefix='swarm-router')"
Unique identifier for the router instance. Used for autosave directory naming and telemetry.
name
str
default:"swarm-router"
Human-readable name. Used for autosave directory naming.
description
str
default:"Routes your task to the desired swarm"
Free-form description of the router’s purpose.
agents
List[Union[Agent, Callable]]
default:"[]"
Agents the router will pass to the selected swarm. Some swarm types require a specific minimum count (e.g. DebateWithJudge needs at least three).
swarm_type
SwarmType
default:"SequentialWorkflow"
Which architecture to instantiate. See the SwarmType Literal above.
max_loops
int
default:"1"
Maximum execution loops where supported by the underlying swarm (e.g. HierarchicalSwarm, GroupChat).
output_type
OutputType
default:"dict-all-except-first"
Output formatter applied to the conversation. One of 'str', 'string', 'list', 'json', 'dict', 'dict-all-except-first', 'yaml', 'xml'.
return_json
bool
default:"False"
When True, results are returned as JSON regardless of output_type. Useful for downstream parsing.
return_entire_history
bool
default:"True"
Whether the underlying swarm returns the full conversation history or only the final step.

Behavior modifiers

rules
str
String injected into every agent’s system prompt before execution. Useful for global guardrails (citation requirements, tone, format).
multi_agent_collab_prompt
bool
default:"True"
Inject the built-in collaboration prompt into each agent so they understand they are part of a multi-agent team.
auto_generate_prompts
bool
default:"False"
Automatically generate / refine each agent’s system prompt before the first run.
shared_memory_system
Any
Shared memory backend (e.g. a vector store) made available to all agents.
documents
List[str]
default:"[]"
File paths to documents the router can attach to agent context.
list_all_agents
bool
default:"False"
When True, embed a manifest of every agent (name + description) into the conversation so each agent can see its peers.
conversation
Any
Pre-existing Conversation instance to reuse instead of starting fresh.
agents_config
Optional[Dict[Any, Any]]
Per-agent configuration overrides applied during swarm setup.
load_agents_from_csv
bool
default:"False"
When True, agents are loaded from csv_file_path instead of from the agents list.
csv_file_path
str
Path used when load_agents_from_csv=True.
verbose
bool
default:"False"
Emit detailed logs during construction and execution.
telemetry_enabled
bool
default:"False"
Forward telemetry events about this router’s runs.

Autosave

autosave
bool
default:"False"
When enabled, persist config.json on construction and state.json + metadata.json after each run to {workspace_dir}/swarms/SwarmRouter/{swarm-name}-{stamp}/.
autosave_use_timestamp
bool
default:"True"
Use an ISO timestamp in the directory name when True; use a UUID when False.

Per-architecture parameters

These are only consulted when the corresponding swarm_type is selected.

AgentRearrange

rearrange_flow
str
required
Flow DSL string, e.g. "researcher -> writer, editor". Required for swarm_type="AgentRearrange".

GroupChat

speaker_fn
Callable
Speaker-selection function for GroupChat. Receives state and returns the next speaker’s name.
speaker_function
str
Named speaker function (e.g. "round_robin", "expertise_based").

HeavySwarm

heavy_swarm_loops_per_agent
int
default:"1"
Number of reasoning loops per worker agent.
heavy_swarm_question_agent_model_name
str
default:"gpt-4.1"
Model used by the question-generation captain.
heavy_swarm_worker_model_name
str
default:"gpt-4.1"
Model used by every worker agent.
heavy_swarm_swarm_show_output
bool
default:"True"
Whether to render the live dashboard during execution.
heavy_swarm_use_grok_agents
bool
default:"False"
When True, instantiate the 4-agent Grok variant (Captain / Harper / Benjamin / Lucas) instead of the default 5-agent set.
worker_tools
List[Callable]
Tools made available to every worker agent in HeavySwarm.

CouncilAsAJudge

council_judge_model_name
str
default:"gpt-5.4"
Model used by the judge agent.

LLMCouncil

aggregation_strategy
str
default:"synthesis"
How council member responses are combined into the chairman’s final decision.
chairman_model
str
default:"gpt-5.1"
Model used by the chairman.

Additional kwargs

The constructor accepts arbitrary *args / **kwargs for forward-compatibility, but they are not stored on the router or forwarded to the underlying swarm — extra constructor kwargs are effectively ignored. Configure the underlying swarm through the router’s explicit parameters listed above. For MixtureOfAgents, the aggregator is not passed as a kwarg; the last agent in agents is used as the aggregator automatically:
router = SwarmRouter(
    swarm_type="MixtureOfAgents",
    agents=[worker_1, worker_2, aggregator],  # aggregator = agents[-1]
)

Exceptions

SwarmRouterConfigError
Exception
Raised by reliability_check() when construction inputs are invalid: unknown swarm_type, missing required parameter for the chosen type (e.g. rearrange_flow for AgentRearrange), max_loops <= 0, etc.
SwarmRouterRunError
Exception
Raised by run() / batch_run() / concurrent_run() when task execution fails inside the underlying swarm. Wraps the original traceback.

Methods

run(task=None, img=None, tasks=None, *args, **kwargs)

Execute a single task using the configured swarm.
task
str
The task to be executed. Required for most swarm_type values.
img
str
Optional image input forwarded to vision-capable agents.
tasks
List[str]
List of tasks. Consumed by BatchedGridWorkflow.
Returns: Any — shape depends on output_type and the underlying swarm. Raises: SwarmRouterRunError on execution failure.
result = router.run("Analyse Q1 market trends.")

__call__(task, *args, **kwargs)

Alias for run. Lets you treat a router as a callable.
result = router("Analyse Q1 market trends.")

batch_run(tasks, img=None, imgs=None, *args, **kwargs)

Execute many tasks sequentially. Each task gets a fresh execution against the same router instance.
tasks
List[str]
required
Tasks to process.
img
str
Single image applied to every task.
imgs
List[str]
Per-task images aligned to tasks by index.
Returns: List[Any] — results in the same order as tasks.
results = router.batch_run([
    "Summarize Q1.",
    "Summarize Q2.",
    "Summarize Q3.",
])

concurrent_run(task, img=None, imgs=None, *args, **kwargs)

Execute one task in a separate thread using a ThreadPoolExecutor. Useful when calling the router from synchronous code that should not block.
result = router.concurrent_run("Summarize Q1.")

reliability_check()

Validates the configuration (swarm type, per-type required parameters, max_loops) and then runs setup(). Called automatically at the end of __init__; you do not normally call it yourself. Raises SwarmRouterConfigError on invalid input.

setup()

Applies pre-run configuration to the agents: auto-prompt-engineering (auto_generate_prompts), shared-memory activation (shared_memory_system), rules injection (rules), and the multi-agent collaboration prompt (multi_agent_collab_prompt). Called automatically during construction via reliability_check(). The underlying swarm itself is created lazily on the first run().

to_dict()

Serialize the router’s configuration and current state to a dictionary suitable for logging or persistence. Returns: Dict[str, Any].
config = router.to_dict()

fetch_message_history_as_string()

Return the underlying conversation as a single formatted string.

activate_shared_memory() · handle_rules() · activate_ape()

Internal helpers used during setup() for shared-memory activation, rules injection, and auto-prompt-engineering. Rarely called directly.

Required parameters by swarm_type

swarm_typeAdditional required parameters
SequentialWorkflowagents (≥1)
ConcurrentWorkflowagents (≥1)
AgentRearrangeagents, rearrange_flow
MixtureOfAgentsagents (workers + aggregator as the last element)
HierarchicalSwarmagents (workers); director is created automatically
GroupChatagents, speaker_fn or speaker_function
MajorityVotingagents (≥3 recommended)
CouncilAsAJudgecouncil_judge_model_name (builds its own agents)
LLMCouncilagents, chairman_model, aggregation_strategy
DebateWithJudgeagents (≥3: pro, con, judge)
HeavySwarmheavy_swarm_worker_model_name, heavy_swarm_question_agent_model_name
BatchedGridWorkflowagents, tasks passed to run
RoundRobinagents (≥2)
MultiAgentRouteragents
PlannerWorkerSwarmagents (workers); planner is created automatically
AutoSwarmBuilderReserved — not dispatched by the current factory (raises ValueError at run)
autoReserved — not dispatched by the current factory (raises ValueError at run)

Autosave layout

When autosave=True, the router writes to:
{workspace_dir}/swarms/SwarmRouter/{name}-{timestamp_or_uuid}/
├── config.json    # written on __init__
├── state.json     # rewritten after each run
└── metadata.json  # rewritten after each run
workspace_dir resolves to the SWARMS_WORKSPACE_DIR env var if set, otherwise to the configured Swarms workspace.

Usage Example

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

researcher = Agent(
    agent_name="Research-Agent",
    system_prompt="You are a research specialist.",
    model_name="claude-sonnet-4-6",
)

analyst = Agent(
    agent_name="Analysis-Agent",
    system_prompt="You analyze research findings into actionable insights.",
    model_name="claude-sonnet-4-6",
)

router = SwarmRouter(
    name="research-analysis-swarm",
    description="A swarm for research + analysis tasks",
    agents=[researcher, analyst],
    swarm_type="SequentialWorkflow",
    max_loops=1,
    autosave=True,
    verbose=True,
)

result = router.run("Research recent trends in AI hardware and analyze them.")
print(result)

Source

swarms/structs/swarm_router.py on GitHub