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

# Heavy Swarm

> Multi-phase orchestration that decomposes a task into specialized questions, runs them through expert agents in parallel, and synthesizes a final answer

The `HeavySwarm` is a multi-agent orchestration system inspired by X.AI's Grok Heavy implementation. It decomposes a task into role-specific questions, runs those questions through specialized expert agents in parallel, and then synthesizes the outputs into a single comprehensive answer. The exact set of experts is controlled by the `variant` parameter.

## When to Use

* **Complex research tasks** — in-depth investigation across multiple angles
* **Financial analysis** — investment decisions requiring multiple viewpoints
* **Strategic planning** — comprehensive evaluation of options and trade-offs
* **Due diligence** — thorough verification and risk assessment
* **Multi-faceted problems** — issues that need research, analysis, and synthesis combined

## Key Features

* Intelligent question generation tailored to each agent role
* Three preset variants — `default` (5 agents), `medium` (4 Grok-style agents), `heavy` (16 agents)
* True parallel execution via a `ThreadPoolExecutor`
* Synthesis agent that integrates expert outputs into a final answer
* Optional real-time `rich` dashboard
* Multi-loop iterative refinement (each loop builds on the previous result)
* Tool integration through `worker_tools`
* Inherits `SerializableMixin` — `to_dict()` is available for telemetry / persistence

## Architecture

```
1. Question Generation
   - Director model analyzes the task
   - Emits a JSON schema with one question per expert role

2. Parallel Expert Execution (variant-dependent)
   - default : Research, Analysis, Alternatives, Verification
   - medium  : Captain + Harper, Benjamin, Lucas
   - heavy   : Grok captain + 15 domain specialists

3. Synthesis
   - Synthesis agent integrates all expert outputs
   - Produces the final report

4. Optional Multi-Loop Refinement
   - Each subsequent loop receives the previous synthesis as context
```

## Basic Example

```python theme={null}
from swarms import HeavySwarm

swarm = HeavySwarm(
    name="Investment-Research-Team",
    description="Comprehensive investment analysis",
    question_agent_model_name="gpt-5.4",
    worker_model_name="gpt-5.4",
    show_dashboard=True,
    max_loops=1,
)

result = swarm.run(
    "Should we invest in NVIDIA stock? Provide detailed analysis."
)
print(result)
```

## With Tool Integration

```python theme={null}
from swarms import HeavySwarm
from swarms_tools import exa_search

swarm = HeavySwarm(
    name="Market-Research-Team",
    description="Research team with web search capabilities",
    question_agent_model_name="gpt-5.4",
    worker_model_name="claude-sonnet-4-6",
    worker_tools=[exa_search],   # tools available to every worker
    show_dashboard=True,
    max_loops=2,                 # iterative refinement
)

result = swarm.run(
    "Find the best 3 gold ETFs with current data from the web"
)
```

## Selecting a Variant

The `variant` parameter controls which agents are instantiated.

```python theme={null}
# Five-agent default (Research / Analysis / Alternatives / Verification + Synthesis)
swarm = HeavySwarm(variant="default")

# Four-agent Grok-style team (Captain + Harper, Benjamin, Lucas)
swarm = HeavySwarm(variant="medium")

# Sixteen-agent deep team (Grok captain + 15 domain specialists)
swarm = HeavySwarm(variant="heavy")
```

`SwarmVariant` is exported from `swarms.agents.heavy_swarm_agents`. Passing an unknown variant raises `ValueError` during initialization.

## Specialized Agents (default variant)

### Research Agent

* Comprehensive information gathering
* Data collection and validation
* Source verification
* Literature review
* Statistical data interpretation

### Analysis Agent

* Pattern recognition
* Statistical analysis
* Predictive modeling
* Data interpretation
* Performance metrics

### Alternatives Agent

* Strategic thinking
* Creative problem-solving
* Option generation
* Trade-off evaluation
* Scenario planning

### Verification Agent

* Fact-checking
* Feasibility assessment
* Risk analysis
* Compliance verification
* Quality assurance

### Synthesis Agent

* Multi-perspective integration
* Comprehensive analysis
* Executive summary creation
* Strategic alignment
* Actionable recommendations

## Key Parameters

<ParamField path="name" type="str" default="HeavySwarm">
  Identifier for the swarm instance.
</ParamField>

<ParamField path="description" type="str">
  Description of the swarm's purpose.
</ParamField>

<ParamField path="timeout" type="int" default="900">
  Maximum execution time per agent in seconds.
</ParamField>

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

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

<ParamField path="verbose" type="bool" default="False">
  Enable detailed logging output.
</ParamField>

<ParamField path="show_dashboard" type="bool" default="False">
  Enable the real-time `rich` progress dashboard.
</ParamField>

<ParamField path="agent_prints_on" type="bool" default="False">
  Print each agent's individual output.
</ParamField>

<ParamField path="output_type" type="str" default="dict-all-except-first">
  Format of the returned conversation history.
</ParamField>

<ParamField path="worker_tools" type="Optional[tool_type]">
  Tools made available to all worker agents.
</ParamField>

<ParamField path="max_loops" type="int" default="1">
  Number of full swarm iterations. Each loop refines the previous synthesis.
</ParamField>

<ParamField path="variant" type="Literal[&#x22;default&#x22;, &#x22;medium&#x22;, &#x22;heavy&#x22;]" default="&#x22;default&#x22;">
  Which agent line-up to instantiate. See **Selecting a Variant** above.
</ParamField>

## Methods

### `run(task, img=None)`

Execute the full multi-phase workflow.

```python theme={null}
result = swarm.run(
    task="Analyze cryptocurrency market trends",
    img=None,   # optional image input
)
```

### `to_dict()`

Inherited from `SerializableMixin`. Returns a JSON-friendly snapshot of the swarm's config. The `agents`, `conversation`, `dashboard`, and `worker_tools` attributes are excluded via `_to_dict_exclude` to keep the snapshot lightweight.

```python theme={null}
snapshot = swarm.to_dict()
```

## Question Generation

The question agent emits a JSON object whose schema depends on the variant. For the default variant it looks like:

```python theme={null}
{
    "thinking": "Reasoning for how to break down the task",
    "research_question": "Question for Research Agent",
    "analysis_question": "Question for Analysis Agent",
    "alternatives_question": "Question for Alternatives Agent",
    "verification_question": "Question for Verification Agent"
}
```

Example generated questions for *"Invest in NVIDIA?"*:

```json theme={null}
{
    "thinking": "Need to evaluate financials, market position, alternatives, and risks",
    "research_question": "Research NVIDIA's financial performance, product pipeline, and market position in AI chips",
    "analysis_question": "Analyze NVIDIA's revenue growth, profit margins, and competitive advantages in the AI accelerator market",
    "alternatives_question": "What are alternative semiconductor investments with similar growth potential?",
    "verification_question": "Verify NVIDIA's claimed AI leadership and assess risks to their market dominance"
}
```

## Multi-Loop Refinement

With `max_loops > 1` the swarm iterates, each loop feeding the previous synthesis back as context:

```python theme={null}
swarm = HeavySwarm(
    name="Deep-Analysis-Team",
    worker_model_name="claude-sonnet-4-6",
    max_loops=3,
)

result = swarm.run("Complex strategic decision")
```

Per-loop semantics:

1. Loop 1: original task only
2. Loop 2: `"Previous loop results: <output> | Original task: <task>"`
3. Loop 3: same shape — refine, fill gaps, deepen the analysis

## Dashboard Features

When `show_dashboard=True`, the `HeavySwarmDashboard` renders rich progress panels:

**Configuration Panel:**

* Swarm name and description
* Model configuration (question + worker)
* Timeout and worker counts

**Reliability Check Phase:**

* Animated progress bars
* Per-component validation status

**Question Generation Phase:**

* Real-time generation progress

**Agent Execution Phase:**

* Per-agent progress bars
* Status (INITIALIZING, PROCESSING, GENERATING, COMPLETE)
* Variant-aware agent labels

**Synthesis Phase:**

* Integration progress
* Final report generation
* Completion confirmation

## Use Cases

### Investment Analysis

```python theme={null}
swarm = HeavySwarm(
    name="Investment-Committee",
    description="Comprehensive investment evaluation team",
    worker_model_name="claude-sonnet-4-6",
    show_dashboard=True,
)

analysis = swarm.run(
    "Evaluate Tesla as a long-term investment. Consider financials, "
    "market position, competition, risks, and alternatives."
)
```

### Market Research with Live Web Data

```python theme={null}
from swarms_tools import exa_search

swarm = HeavySwarm(
    name="Market-Intel-Team",
    worker_model_name="gpt-5.4",
    worker_tools=[exa_search],
    max_loops=2,
)

research = swarm.run(
    "Research the enterprise AI market: size, growth, key players, "
    "trends, and opportunities. Use current web data."
)
```

### Strategic Planning

```python theme={null}
swarm = HeavySwarm(
    name="Strategy-Team",
    description="Strategic planning and analysis",
    worker_model_name="claude-sonnet-4-6",
    max_loops=2,
    show_dashboard=True,
)

strategy = swarm.run(
    "Should our company enter the AI agent services market? "
    "Analyze market, competition, requirements, risks, and alternatives."
)
```

### Heavy Variant for Deep Research

```python theme={null}
swarm = HeavySwarm(
    name="Deep-Research-Team",
    worker_model_name="gpt-5.4",
    variant="heavy",       # 16 agents
    max_loops=2,
)

report = swarm.run(
    "Build a long-form briefing on the global AI compute supply chain, "
    "covering geopolitics, fabrication capacity, chip design, and downstream demand."
)
```

## Performance Notes

### Parallel Execution

All workers fan out via `concurrent.futures.ThreadPoolExecutor`. `max_workers` defaults to roughly `0.9 * os.cpu_count()`.

```python theme={null}
with concurrent.futures.ThreadPoolExecutor(
    max_workers=max_workers,
) as executor:
    futures = [executor.submit(execute_agent, task) for task in agent_tasks]
```

### Timeout Management

```python theme={null}
swarm = HeavySwarm(
    timeout=900,   # 15 minutes per agent (default)
)
```

### Verbose Logging

```python theme={null}
swarm = HeavySwarm(
    verbose=True,
    agent_prints_on=True,
)
```

## Output Structure

The swarm returns the conversation history formatted by `output_type`. With the default `"dict-all-except-first"`:

```python theme={null}
{
    "Question Generator Agent": "<generated questions>",
    "Research-Agent": "<research findings>",
    "Analysis-Agent": "<analysis insights>",
    "Alternatives-Agent": "<alternative options>",
    "Verification-Agent": "<verification results>",
    "Synthesis Agent": "<comprehensive synthesis>"
}
```

## Best Practices

<Note>
  **Model Selection:** use stronger models (Claude Sonnet, GPT-5.4) for worker agents on complex tasks.
</Note>

1. **Question Quality** — a stronger question-generation model produces tighter, less overlapping expert questions.
2. **Worker Models** — balance cost vs quality for the worker pool; mixing providers via LiteLLM works out of the box.
3. **Loop Count** — start at `max_loops=1`. Add more only when the synthesis clearly needs refinement.
4. **Variant Choice** — `default` covers most tasks; reach for `heavy` only when you genuinely benefit from 15+ specialist perspectives.
5. **Dashboard** — leave on for demos and debugging; off for production.
6. **Tools** — supply `worker_tools` when the task requires real-time data (search, web fetch, etc.).

<Warning>
  HeavySwarm is resource-intensive. Each loop runs N expert agents + a question generator + a synthesizer. Token costs scale roughly linearly with both `variant` and `max_loops`.
</Warning>

## Reliability Checks

`reliability_check()` runs automatically during `__init__`:

```python theme={null}
# Validation:
# - worker_model_name must be set
# - question_agent_model_name must be set
# - variant must be one of {default, medium, heavy}

try:
    swarm = HeavySwarm(worker_model_name=None)
except ValueError as e:
    print(e)
```

When `show_dashboard=True`, the validation steps animate through the dashboard. Otherwise a single confirmation panel prints.

## Conversation History

Access the full transcript through the conversation object:

```python theme={null}
result = swarm.run("Task")
history = swarm.conversation.conversation_history

# Format:
# [{"role": "User", "content": "Task"},
#  {"role": "Question Generator Agent", "content": {...}},
#  {"role": "Research-Agent", "content": "..."},
#  {"role": "Analysis-Agent", "content": "..."},
#  {"role": "Alternatives-Agent", "content": "..."},
#  {"role": "Verification-Agent", "content": "..."},
#  {"role": "Synthesis Agent", "content": "..."}]
```

## Error Handling

```python theme={null}
try:
    result = swarm.run("Task")
except TimeoutError:
    print("Agent execution exceeded timeout")
except Exception as e:
    print(f"Swarm execution failed: {e}")
    # Individual agent errors are logged but do not abort the entire swarm
```

## Related Architectures

* [Mixture of Agents](/architectures/mixture-of-agents) — parallel experts + aggregator (lighter weight)
* [Hierarchical Swarm](/architectures/hierarchical-swarm) — director-worker delegation pattern
* [Concurrent Workflow](/architectures/concurrent-workflow) — simpler parallel execution
* [Agent Rearrange](/architectures/agent-rearrange) — custom flow patterns
* [Structures Catalog](/architectures/structures-catalog) — full enumeration of every multi-agent structure
