> ## 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.

# SwarmRouter

> Universal router that dispatches a task to any supported swarm architecture through a single, uniform interface

## 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

```python theme={null}
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.

```python theme={null}
SwarmType = Literal[
    "AgentRearrange",
    "MixtureOfAgents",
    "SequentialWorkflow",
    "ConcurrentWorkflow",
    "GroupChat",
    "MultiAgentRouter",
    "HierarchicalSwarm",
    "MajorityVoting",
    "CouncilAsAJudge",
    "HeavySwarm",
    "LLMCouncil",
    "DebateWithJudge",
    "RoundRobin",
    "PlannerWorkerSwarm",
]
```

<Note>
  `"AutoSwarmBuilder"` is **not** in the `SwarmType` Literal — passing it raises `SwarmRouterConfigError` at construction. Neither `"auto"` nor `"BatchedGridWorkflow"` is a member either (14 values total) — passing either raises `SwarmRouterConfigError` at construction time, the same as any other invalid value.
</Note>

## Constructor

```python theme={null}
SwarmRouter(
    id: Optional[str] = None,  # resolves to generate_id("swarm-router") when not set
    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,
    output_type: OutputType = "dict",
    multi_agent_collab_prompt: bool = False,
    list_all_agents: bool = False,
    conversation: Any = None,
    agents_config: Optional[Dict[Any, Any]] = None,
    heavy_swarm_question_agent_model_name: str = "gpt-5.4",
    heavy_swarm_worker_model_name: str = "gpt-5.4",
    heavy_swarm_swarm_show_output: bool = True,
    heavy_swarm_variant: SwarmVariant = "default",
    heavy_swarm_max_loops: int = 1,
    heavy_swarm_timeout: int = 900,
    council_judge_model_name: str = "gpt-5.4",
    verbose: bool = False,
    worker_tools: Optional[List[Callable]] = None,
    chairman_model: str = "gpt-5.1",
    autosave_use_timestamp: bool = True,
    director_model_name: str = "gpt-5.4",
    director_settings: Optional[Dict[str, Any]] = None,
    *args,
    **kwargs,
)
```

### Core parameters

<ParamField path="id" type="Optional[str]" default="None">
  Unique identifier for the router instance. When left as `None`, resolves to `generate_id("swarm-router")`. Used for autosave directory naming and telemetry.
</ParamField>

<ParamField path="name" type="str" default="swarm-router">
  Human-readable name. Used for autosave directory naming.
</ParamField>

<ParamField path="description" type="str" default="Routes your task to the desired swarm">
  Free-form description of the router's purpose.
</ParamField>

<ParamField path="agents" type="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).
</ParamField>

<ParamField path="swarm_type" type="SwarmType" default="SequentialWorkflow">
  Which architecture to instantiate. See the `SwarmType` Literal above.
</ParamField>

<ParamField path="max_loops" type="int" default="1">
  Maximum execution loops where supported by the underlying swarm (e.g. `HierarchicalSwarm`, `GroupChat`).
</ParamField>

<ParamField path="output_type" type="OutputType" default="dict">
  Output formatter applied to the conversation. One of `'list'`, `'dict'`, `'dictionary'`, `'string'`, `'str'`, `'final'`, `'last'`, `'json'`, `'all'`, `'yaml'`, `'xml'`, `'dict-all-except-first'`, `'str-all-except-first'`, `'basemodel'`, `'dict-final'`, `'list-final'`.
</ParamField>

### Behavior modifiers

<ParamField path="multi_agent_collab_prompt" type="bool" default="False">
  Deliver the built-in collaboration prompt to each agent so they understand they are part of a multi-agent team. It is passed to the swarm at construction and reaches the agents as a **system turn** at run time; the caller's `Agent` objects are never modified.

  Only `SequentialWorkflow` and `AgentRearrange` can deliver it. For any other `swarm_type` a warning is logged and the flag has no effect.
</ParamField>

<ParamField path="list_all_agents" type="bool" default="False">
  When `True`, every agent receives a manifest of its peers (name + description) in the same system turn as the collaboration prompt.
</ParamField>

<ParamField path="conversation" type="Any" optional>
  Pre-existing `Conversation` instance to reuse instead of starting fresh.
</ParamField>

<ParamField path="agents_config" type="Optional[Dict[Any, Any]]" optional>
  Per-agent configuration overrides applied during swarm setup.
</ParamField>

<ParamField path="verbose" type="bool" default="False">
  Emit detailed logs during construction and execution.
</ParamField>

### Autosave

<ParamField path="autosave" type="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}/`.
</ParamField>

<ParamField path="autosave_use_timestamp" type="bool" default="True">
  Use an ISO timestamp in the directory name when `True`; use a UUID when `False`.
</ParamField>

### Per-architecture parameters

These are only consulted when the corresponding `swarm_type` is selected.

#### AgentRearrange

<ParamField path="rearrange_flow" type="str" required>
  Flow DSL string, e.g. `"researcher -> writer, editor"`. Required for `swarm_type="AgentRearrange"`.
</ParamField>

#### GroupChat

`GroupChat` is asynchronous and self-selecting — there are **no speaker-selection functions**. The router passes `agents`, `max_loops`, `output_type`, and `verbose` through to it; agents decide on their own whether to speak. See the [GroupChat API reference](/api/group-chat) for `threshold` / `idle_timeout` tuning (configure those by constructing the `GroupChat` directly).

#### HeavySwarm

<ParamField path="heavy_swarm_question_agent_model_name" type="str" default="gpt-5.4">
  Model used by the question-generation agent.
</ParamField>

<ParamField path="heavy_swarm_worker_model_name" type="str" default="gpt-5.4">
  Model used by every worker agent.
</ParamField>

<ParamField path="heavy_swarm_swarm_show_output" type="bool" default="True">
  Print per-agent output during execution (`agent_prints_on`). The live dashboard is forced off when `HeavySwarm` is created through the router.
</ParamField>

<ParamField path="heavy_swarm_variant" type="SwarmVariant (&#x22;default&#x22; | &#x22;medium&#x22; | &#x22;heavy&#x22;)" default="&#x22;default&#x22;">
  Which agent line-up to instantiate: `"default"` → 5 agents, `"medium"` → 4 agents (Captain + Harper / Benjamin / Lucas), `"heavy"` → 16 agents (Grok captain + 15 specialists). `SwarmVariant` is exported from `swarms.agents.heavy_swarm_agents`.
</ParamField>

<ParamField path="heavy_swarm_max_loops" type="int" default="1">
  Number of iterative-refinement loops for `HeavySwarm`.
</ParamField>

<ParamField path="heavy_swarm_timeout" type="int" default="900">
  Per-worker wall-clock cap, in seconds, for `HeavySwarm`.
</ParamField>

<ParamField path="worker_tools" type="List[Callable]" optional>
  Tools made available to every worker agent in `HeavySwarm`.
</ParamField>

#### HierarchicalSwarm

<ParamField path="director_model_name" type="str" default="gpt-5.4">
  Model used by the auto-created director agent. Forwarded to `HierarchicalSwarm` by `_create_hierarchical_swarm()`.
</ParamField>

<ParamField path="director_settings" type="Dict[str, Any]" optional>
  Extra `Agent` keyword arguments for the auto-created director. `HierarchicalSwarm` reads the keys `agent_name`, `model_name`, `system_prompt`, `temperature`, and `top_p` from this dict, and each one overrides the corresponding default — including `director_model_name`.
</ParamField>

#### CouncilAsAJudge

<ParamField path="council_judge_model_name" type="str" default="gpt-5.4">
  Model used by the judge agent.
</ParamField>

#### LLMCouncil

<ParamField path="chairman_model" type="str" default="gpt-5.1">
  Model used by the chairman that synthesizes the council members' responses.
</ParamField>

### 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:

```python theme={null}
router = SwarmRouter(
    swarm_type="MixtureOfAgents",
    agents=[worker_1, worker_2, aggregator],  # aggregator = agents[-1]
)
```

## Exceptions

<ResponseField name="SwarmRouterConfigError" type="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.
</ResponseField>

<ResponseField name="SwarmRouterRunError" type="Exception">
  Raised by `run()` / `batch_run()` / `concurrent_run()` when task execution fails inside the underlying swarm. Wraps the original traceback.
</ResponseField>

## Methods

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

Execute a single task using the configured swarm.

<ParamField path="task" type="str" optional>
  The task to be executed. Required for most `swarm_type` values.
</ParamField>

<ParamField path="img" type="str" optional>
  Optional image input forwarded to vision-capable agents.
</ParamField>

<ParamField path="tasks" type="List[str]" optional>
  Batch-style task list, forwarded as `tasks=` to the underlying swarm's `run()` in place of `task` when provided. Only meaningful for swarm types whose `run()` accepts a `tasks` argument.
</ParamField>

**Returns:** `Any` — shape depends on `output_type` and the underlying swarm.

**Raises:** `SwarmRouterRunError` on execution failure.

```python theme={null}
result = router.run("Analyse Q1 market trends.")
```

***

### `__call__(task, *args, **kwargs)`

Alias for `run`. Lets you treat a router as a callable.

```python theme={null}
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.

<ParamField path="tasks" type="List[str]" required>
  Tasks to process.
</ParamField>

<ParamField path="img" type="str" optional>
  Single image applied to every task.
</ParamField>

<ParamField path="imgs" type="List[str]" optional>
  Per-task images aligned to `tasks` by index.
</ParamField>

**Returns:** `List[Any]` — results in the same order as `tasks`.

```python theme={null}
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.

```python theme={null}
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: the multi-agent collaboration prompt (`multi_agent_collab_prompt`) and the agent roster (`list_all_agents`). 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]`.

```python theme={null}
config = router.to_dict()
```

***

### `fetch_message_history_as_string()`

Return the underlying conversation as a single formatted string.

***

### `list_agents_to_eachother()`

Internal helper. Points `self.conversation` at the underlying swarm's conversation. Called after each run, because the swarm is built lazily on the first `run()` and several structures replace their conversation object per task. Rarely called directly.

<Note>
  `update_system_prompt_for_agent_in_swarm()` was removed. It appended the collaboration prompt to each agent's `system_prompt` **after** the LLM had been built, so the text never reached the model, while accumulating on the caller's live agents on every construction. The preamble is now passed through the swarm constructor and delivered as a system turn instead.
</Note>

## Required parameters by `swarm_type`

| `swarm_type`         | Additional required parameters                                                                  |
| -------------------- | ----------------------------------------------------------------------------------------------- |
| `SequentialWorkflow` | `agents` (≥1)                                                                                   |
| `ConcurrentWorkflow` | `agents` (≥1)                                                                                   |
| `AgentRearrange`     | `agents`, `rearrange_flow`                                                                      |
| `MixtureOfAgents`    | `agents` (workers + aggregator as the **last** element)                                         |
| `HierarchicalSwarm`  | `agents` (workers); director is created automatically                                           |
| `GroupChat`          | `agents` (≥2; asynchronous, self-selecting — no speaker function)                               |
| `MajorityVoting`     | `agents` (≥3 recommended)                                                                       |
| `CouncilAsAJudge`    | `council_judge_model_name` (builds its own agents)                                              |
| `LLMCouncil`         | `agents` (council members), `chairman_model`                                                    |
| `DebateWithJudge`    | `agents` (≥3: pro, con, judge)                                                                  |
| `HeavySwarm`         | `heavy_swarm_worker_model_name`, `heavy_swarm_question_agent_model_name`, `heavy_swarm_variant` |
| `RoundRobin`         | `agents` (≥2)                                                                                   |
| `MultiAgentRouter`   | `agents`                                                                                        |
| `PlannerWorkerSwarm` | `agents` (workers); planner is created automatically                                            |

<Note>
  `"AutoSwarmBuilder"`, `"auto"`, and `"BatchedGridWorkflow"` are **not** members of the `SwarmType` Literal — passing any of them raises `SwarmRouterConfigError` at construction time, before `run()` is ever reached.
</Note>

## 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

```python theme={null}
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)
```

## Related Pages

* [SwarmRouter architecture overview](/architectures/swarm-router)
* [SwarmRouter example walkthrough](/examples/swarm-router-example)
* [MultiAgentRouter API reference](/api/multi-agent-router) — task-aware routing to one of N agents
* [AutoSwarmBuilder API reference](/api/auto-swarm-builder) — LLM-driven swarm construction

## Source

[`swarms/structs/swarm_router.py` on GitHub](https://github.com/kyegomez/swarms/blob/master/swarms/structs/swarm_router.py)
