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

# Swarm Router Example

> Use a single SwarmRouter to switch between any multi-agent architecture by changing one parameter

The `SwarmRouter` is the universal entry point for multi-agent orchestration in Swarms. Instead of importing and configuring different swarm classes, you keep the same `agents` list and just change the `swarm_type` to switch between Sequential, Concurrent, AgentRearrange, MixtureOfAgents, HierarchicalSwarm, and more.

This page walks through one runnable example per common `swarm_type`, plus strategy comparison, fallback, token-usage, and production-ready patterns.

## How SwarmRouter Works

1. **Single interface** — one class, one `run(task)` method, regardless of which architecture you select.
2. **Strategy via parameter** — set `swarm_type="SequentialWorkflow"`, `"ConcurrentWorkflow"`, `"MixtureOfAgents"`, etc.
3. **Per-architecture options** — some swarm types use dedicated router parameters (e.g. `rearrange_flow` for `AgentRearrange`, the `heavy_swarm_*` settings for `HeavySwarm`). For `MixtureOfAgents`, the **last agent in `agents`** is used as the aggregator automatically.
4. **Same agents everywhere** — define your `Agent` instances once and reuse them across architectures.

## Basic Example: Switching Architectures Without Rewriting Code

Define your agents once, then run the same task through three different architectures by changing only `swarm_type`.

```python theme={null}
from swarms import Agent, SwarmRouter

# Define your agents once
researcher = Agent(
    agent_name="Researcher",
    system_prompt="You research the topic and produce a detailed factual summary.",
    model_name="gpt-5.4",
    max_loops=1,
)

writer = Agent(
    agent_name="Writer",
    system_prompt="You turn research into a clear, engaging blog post.",
    model_name="gpt-5.4",
    max_loops=1,
)

editor = Agent(
    agent_name="Editor",
    system_prompt="You sharpen prose, fix errors, and tighten arguments.",
    model_name="gpt-5.4",
    max_loops=1,
)

agents = [researcher, writer, editor]
task = "The state of open-source LLMs in 2026"

# Run as a sequential pipeline (researcher -> writer -> editor)
sequential = SwarmRouter(swarm_type="SequentialWorkflow", agents=agents)
print(sequential.run(task))

# Run all three in parallel on the same task
concurrent = SwarmRouter(swarm_type="ConcurrentWorkflow", agents=agents)
print(concurrent.run(task))
```

## Example: Sequential Workflow via SwarmRouter

Each agent's output flows into the next. Ideal for ordered pipelines like research → write → edit.

```python theme={null}
from swarms import Agent, SwarmRouter

researcher = Agent(
    agent_name="Researcher",
    system_prompt="Research the topic thoroughly with citations.",
    model_name="gpt-5.4",
)
writer = Agent(
    agent_name="Writer",
    system_prompt="Convert research into a coherent narrative.",
    model_name="gpt-5.4",
)
editor = Agent(
    agent_name="Editor",
    system_prompt="Polish for clarity and grammar.",
    model_name="gpt-5.4",
)

router = SwarmRouter(
    name="content-pipeline",
    swarm_type="SequentialWorkflow",
    agents=[researcher, writer, editor],
    max_loops=1,
)

result = router.run("Explain transformer architectures to a software engineer.")
print(result)
```

## Example: Concurrent Workflow via SwarmRouter

All agents see the same task and run in parallel. Use for independent perspectives, redundancy, or fan-out queries.

```python theme={null}
from swarms import Agent, SwarmRouter

bull = Agent(
    agent_name="Bull",
    system_prompt="Argue why the asset is undervalued.",
    model_name="gpt-5.4",
)
bear = Agent(
    agent_name="Bear",
    system_prompt="Argue why the asset is overvalued.",
    model_name="gpt-5.4",
)
quant = Agent(
    agent_name="Quant",
    system_prompt="Analyze with risk-adjusted return frameworks.",
    model_name="gpt-5.4",
)

router = SwarmRouter(
    name="market-perspectives",
    swarm_type="ConcurrentWorkflow",
    agents=[bull, bear, quant],
)

result = router.run("Evaluate NVIDIA as a long-term investment in 2026.")
print(result)
```

## Example: AgentRearrange via SwarmRouter

Mix sequential and parallel execution in one flow using the DSL. `->` chains agents; `,` runs them in parallel.

```python theme={null}
from swarms import Agent, SwarmRouter

planner = Agent(agent_name="Planner",  model_name="gpt-5.4")
coder   = Agent(agent_name="Coder",    model_name="gpt-5.4")
reviewer = Agent(agent_name="Reviewer", model_name="gpt-5.4")
tester  = Agent(agent_name="Tester",   model_name="gpt-5.4")

router = SwarmRouter(
    name="dev-flow",
    swarm_type="AgentRearrange",
    agents=[planner, coder, reviewer, tester],
    rearrange_flow="Planner -> Coder -> Reviewer, Tester",
    #                sequential          parallel
)

result = router.run("Build a Python function that validates email addresses.")
print(result)
```

## Example: Mixture of Agents via SwarmRouter

Workers respond independently, then an aggregator agent synthesizes a final answer. With `SwarmRouter`, the aggregator is **not** a separate kwarg — it is the **last agent** in the `agents` list. The router passes the full list as workers too, so the aggregator also answers in each layer before it synthesizes.

```python theme={null}
from swarms import Agent, SwarmRouter

worker_gpt = Agent(
    agent_name="Worker-GPT",
    model_name="gpt-5.4",
    system_prompt="Answer from the perspective of an LLM specialist.",
)
worker_claude = Agent(
    agent_name="Worker-Claude",
    model_name="claude-sonnet-4-6",
    system_prompt="Answer from the perspective of a systems architect.",
)
worker_llama = Agent(
    agent_name="Worker-Llama",
    model_name="groq/llama-3.3-70b-versatile",
    system_prompt="Answer from the perspective of an open-source engineer.",
)

aggregator = Agent(
    agent_name="Aggregator",
    model_name="gpt-5.4",
    system_prompt=(
        "Combine the worker responses into one coherent answer. "
        "Highlight where they agree and where they diverge."
    ),
)

router = SwarmRouter(
    name="multi-provider-ensemble",
    swarm_type="MixtureOfAgents",
    # The last agent in the list is used as the aggregator automatically.
    agents=[worker_gpt, worker_claude, worker_llama, aggregator],
)

result = router.run(
    "What are the best practices for deploying LLMs in production?"
)
print(result)
```

## Example: Hierarchical Swarm via SwarmRouter

A director agent decomposes the task and delegates subtasks to worker agents.

```python theme={null}
from swarms import Agent, SwarmRouter

data_worker = Agent(
    agent_name="DataWorker",
    system_prompt="You gather and clean data.",
    model_name="gpt-5.4",
)
writing_worker = Agent(
    agent_name="WritingWorker",
    system_prompt="You draft reports from data summaries.",
    model_name="gpt-5.4",
)
review_worker = Agent(
    agent_name="ReviewWorker",
    system_prompt="You critique drafts for accuracy and clarity.",
    model_name="gpt-5.4",
)

router = SwarmRouter(
    name="research-org",
    swarm_type="HierarchicalSwarm",
    agents=[data_worker, writing_worker, review_worker],
    max_loops=2,  # allow one round of feedback
)

result = router.run(
    "Produce a competitive analysis of the AI chip market."
)
print(result)
```

## Pattern: Strategy Comparison

Run the same task through multiple architectures and compare outputs. Useful when you don't know which architecture suits your task best.

```python theme={null}
from swarms import Agent, SwarmRouter

analyst = Agent(agent_name="Analyst",  model_name="gpt-5.4")
writer  = Agent(agent_name="Writer",   model_name="gpt-5.4")
reviewer = Agent(agent_name="Reviewer", model_name="gpt-5.4")
agents = [analyst, writer, reviewer]

task = "Summarize the impact of generative AI on knowledge work."

strategies = ["SequentialWorkflow", "ConcurrentWorkflow", "MixtureOfAgents"]
results = {}

aggregator = Agent(agent_name="Aggregator", model_name="gpt-5.4")

for strategy in strategies:
    # For MixtureOfAgents, append the aggregator as the last agent.
    swarm_agents = agents + [aggregator] if strategy == "MixtureOfAgents" else agents
    router = SwarmRouter(swarm_type=strategy, agents=swarm_agents)
    results[strategy] = router.run(task)

for strategy, output in results.items():
    print(f"\n=== {strategy} ===\n{output}")
```

## Pattern: Dynamic Architecture Selection

Pick the architecture at runtime based on task characteristics. This is a common production pattern when one server handles tasks of varying complexity.

```python theme={null}
from swarms import Agent, SwarmRouter


def pick_swarm_type(task: str) -> str:
    """Toy classifier — in production, use embeddings or a small LLM."""
    lowered = task.lower()
    if "compare" in lowered or "perspectives" in lowered:
        return "ConcurrentWorkflow"
    if "step" in lowered or "pipeline" in lowered:
        return "SequentialWorkflow"
    if "decompose" in lowered or "delegate" in lowered:
        return "HierarchicalSwarm"
    return "MixtureOfAgents"


agents = [
    Agent(agent_name="Researcher", model_name="gpt-5.4"),
    Agent(agent_name="Writer",     model_name="gpt-5.4"),
    Agent(agent_name="Reviewer",   model_name="gpt-5.4"),
]
aggregator = Agent(agent_name="Aggregator", model_name="gpt-5.4")


def route_task(task: str) -> str:
    swarm_type = pick_swarm_type(task)
    # MixtureOfAgents uses the last agent in the list as the aggregator.
    swarm_agents = agents + [aggregator] if swarm_type == "MixtureOfAgents" else agents
    return SwarmRouter(swarm_type=swarm_type, agents=swarm_agents).run(task)


print(route_task("Compare three competing perspectives on AGI timelines."))
print(route_task("Decompose and delegate: build a fintech compliance checklist."))
```

## Pattern: Production-Ready Configuration

Combine `autosave`, the multi-agent collaboration prompt, and an explicit `output_type` for a deployable router. The router will save its config, state, and metadata after every run.

```python theme={null}
from swarms import Agent, SwarmRouter

# Apply global guardrails through each agent's system prompt.
SHARED_RULES = (
    "Always: 1) cite sources for every factual claim, "
    "2) prefer concise outputs, 3) flag any uncertainty explicitly."
)

agents = [
    Agent(agent_name="Analyst", model_name="gpt-5.4", system_prompt=SHARED_RULES),
    Agent(agent_name="Writer",  model_name="gpt-5.4", system_prompt=SHARED_RULES),
    Agent(agent_name="QA",      model_name="gpt-5.4", system_prompt=SHARED_RULES),
]

router = SwarmRouter(
    name="production-research-swarm",
    description="Cited, concise research outputs",
    swarm_type="SequentialWorkflow",
    agents=agents,
    max_loops=1,
    output_type="dict-all-except-first",
    autosave=True,
    autosave_use_timestamp=True,
    multi_agent_collab_prompt=True,
)

result = router.run("Assess the risks of deploying LLMs in regulated industries.")
print(result)
# Persisted at: {workspace_dir}/swarms/SwarmRouter/production-research-swarm-{timestamp}/
#   - config.json (on init)
#   - state.json + metadata.json (after each run)
```

## Pattern: Fallback Architectures

Give the router an ordered list of backup swarm types. If the primary swarm raises, the next one is built from the same agents and runs the same task.

```python theme={null}
from swarms import Agent, SwarmRouter

agents = [
    Agent(agent_name="Researcher", model_name="gpt-5.4", max_loops=1),
    Agent(agent_name="Analyst",    model_name="gpt-5.4", max_loops=1),
    Agent(agent_name="Writer",     model_name="gpt-5.4", max_loops=1),
]

router = SwarmRouter(
    name="resilient-router",
    agents=agents,
    swarm_type="HierarchicalSwarm",
    fallback_swarms=["SequentialWorkflow", "ConcurrentWorkflow"],
    max_loops=1,
)

result = router.run("Assess whether a mid-size SaaS company should adopt usage-based pricing.")

print(f"Served by: {router.active_swarm_type}")
for attempt in router.fallback_attempts:
    print(f"Failed first: {attempt['swarm_type']} -> {attempt['error']}")
```

If every swarm in the chain fails, `run()` raises `SwarmRouterRunError` (from `swarms.structs.swarm_router`) naming each attempt.

## Pattern: Tracking Token Usage

`router.usage` sums token usage over every agent the swarm ran, including agents the swarm builds for itself, such as the `HierarchicalSwarm` director. See [Token usage](https://docs.swarms.world/agents/token-usage.md).

```python theme={null}
from swarms import Agent, SwarmRouter

router = SwarmRouter(
    name="usage-hierarchical",
    agents=[
        Agent(agent_name="Researcher", model_name="gpt-5.4", max_loops=1),
        Agent(agent_name="Writer",     model_name="gpt-5.4", max_loops=1),
    ],
    swarm_type="HierarchicalSwarm",
    max_loops=1,
)

before = router.usage
router.run("Should a small team adopt a monorepo? Give a recommendation.")
after = router.usage

this_run = {key: after[key] - before[key] for key in after}
print(this_run)  # input_tokens, output_tokens, cached_tokens, reasoning_tokens, total_tokens
```

Agent totals are lifetime totals, so take the difference between two reads to get the cost of one run.

## Batch and Concurrent Execution

`SwarmRouter` exposes the same task-execution helpers regardless of which architecture is selected.

```python theme={null}
router = SwarmRouter(swarm_type="SequentialWorkflow", agents=agents)

# Sequential batch
tasks = [
    "Summarize the 2026 AI hardware market.",
    "Summarize the 2026 AI software market.",
    "Summarize the 2026 AI services market.",
]
sequential_results = router.batch_run(tasks)

# Tasks run concurrently, one per thread
threaded_results = router.concurrent_run(
    ["Summarize the 2026 generative-AI consumer landscape."]
)
```

## Choosing a `swarm_type`

| Situation | `swarm_type` |
| - | - |
| Linear A → B → C pipeline | `"SequentialWorkflow"` |
| Same task, many agents at once | `"ConcurrentWorkflow"` |
| Mix of sequential + parallel via DSL | `"AgentRearrange"` |
| Multiple models, one synthesized answer | `"MixtureOfAgents"` |
| Director delegates to specialists | `"HierarchicalSwarm"` |
| Deep multi-loop analysis | `"HeavySwarm"` |
| Round-table discussion / brainstorming | `"GroupChat"` |
| Discrete consensus answer | `"MajorityVoting"` |
| Adversarial debate with a judge | `"DebateWithJudge"` |
| Council deliberates, judge rules | `"CouncilAsAJudge"` |
| Round-robin task distribution | `"RoundRobin"` |
| LLM-driven council decisions | `"LLMCouncil"` |
| Task-aware routing to one agent | `"MultiAgentRouter"` |
| Planner breaks work into tasks for workers | `"PlannerWorkerSwarm"` |

## What to Avoid

* **Do put the aggregator last in `agents`** when using `MixtureOfAgents` — `SwarmRouter` uses `agents[-1]` as the aggregator. There is no `aggregator_agent` kwarg on the router.
* **Don't pass unsupported constructor kwargs** (e.g. `rules`, `aggregator_agent`, `speaker_fn`) — the router's `__init__` swallows extra `**kwargs` and silently ignores them. Apply global rules through each agent's `system_prompt` instead.
* **Don't omit `rearrange_flow`** when using `AgentRearrange` — it is required and validated at construction time.
* **Don't reuse a SwarmRouter across unrelated tasks expecting clean state** — construct a new one per logical job, or reset its internal conversation between runs.

## Related Pages

* [SwarmRouter architecture overview](https://docs.swarms.world/architectures/swarm-router.md)
* [SwarmRouter API reference](https://docs.swarms.world/api/swarm-router.md)
* [Token usage](https://docs.swarms.world/agents/token-usage.md)
* [Sequential Workflow](https://docs.swarms.world/examples/sequential-workflow-example.md)
* [Concurrent Workflow](https://docs.swarms.world/examples/concurrent-workflow-example.md)
* [Mixture of Agents](https://docs.swarms.world/examples/mixture-of-agents-example.md)
* [Hierarchical Swarm](https://docs.swarms.world/examples/hierarchical-swarm-example.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.