> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# HierarchicalSwarm

> Multi-level swarm architecture with supervisor agents coordinating specialized worker agents in a hierarchical structure

**Swarm Type**: `HierarchicalSwarm`

## Overview

The HierarchicalSwarm implements a multi-level organizational structure where supervisor agents coordinate and manage specialized worker agents. This architecture mirrors real-world organizational hierarchies, allowing for complex task decomposition, quality control, and efficient resource allocation across multiple levels of responsibility.

Key features:

* **Multi-Level Structure**: Supervisor and worker agent hierarchy
* **Task Decomposition**: Complex tasks broken down into manageable subtasks
* **Quality Control**: Supervisors oversee and validate worker outputs
* **Resource Coordination**: Efficient allocation and management of agent resources

## Use Cases

* Complex project management and coordination
* Multi-stage research and analysis workflows
* Content creation with editorial oversight
* Quality assurance and validation processes

## API Usage

### Basic HierarchicalSwarm Example

<Tabs>
  <Tab title="Shell (curl)">
    ```bash theme={null}
    curl -X POST "https://api.swarms.world/v1/swarm/completions" \
      -H "x-api-key: $SWARMS_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Research Project Coordinator",
        "description": "Hierarchical research coordination with supervisor oversight",
        "swarm_type": "HierarchicalSwarm",
        "task": "Conduct comprehensive research on the impact of AI on healthcare, including technological advances, economic implications, ethical considerations, and future trends",
        "agents": [
          {
            "agent_name": "Research Coordinator",
            "description": "Supervisor agent coordinating research efforts and synthesizing results",
            "system_prompt": "You are a research coordinator supervising a team of specialized researchers. Delegate tasks, coordinate efforts, and synthesize final results into a comprehensive report.",
            "model_name": "gpt-4.1",
            "max_loops": 1,
            "temperature": 0.3
          },
          {
            "agent_name": "Technology Researcher",
            "description": "Worker agent researching AI technological advances in healthcare",
            "system_prompt": "You are a technology researcher specializing in AI healthcare applications. Research and analyze current technological advances, breakthroughs, and implementation challenges.",
            "model_name": "gpt-4.1",
            "max_loops": 1,
            "temperature": 0.3
          },
          {
            "agent_name": "Economic Analyst",
            "description": "Worker agent analyzing economic implications of AI in healthcare",
            "system_prompt": "You are an economic analyst specializing in healthcare economics. Research and analyze the economic implications, cost-benefit analysis, and market impact of AI in healthcare.",
            "model_name": "gpt-4.1",
            "max_loops": 1,
            "temperature": 0.3
          },
          {
            "agent_name": "Ethics Specialist",
            "description": "Worker agent examining ethical considerations of AI in healthcare",
            "system_prompt": "You are an ethics specialist focusing on AI and healthcare ethics. Research and analyze ethical considerations, privacy concerns, bias issues, and regulatory implications.",
            "model_name": "gpt-4.1",
            "max_loops": 1,
            "temperature": 0.3
          },
          {
            "agent_name": "Future Trends Analyst",
            "description": "Worker agent predicting future trends in AI healthcare",
            "system_prompt": "You are a future trends analyst specializing in healthcare technology. Research and analyze future trends, predictions, and long-term implications of AI in healthcare.",
            "model_name": "gpt-4.1",
            "max_loops": 1,
            "temperature": 0.3
          }
        ],
        "max_loops": 1
      }'
    ```
  </Tab>

  <Tab title="Python (requests)">
    ```python theme={null}
    import requests
    import json

    API_BASE_URL = "https://api.swarms.world"
    API_KEY = "your_api_key_here"

    headers = {
        "x-api-key": API_KEY,
        "Content-Type": "application/json"
    }

    swarm_config = {
        "name": "Research Project Coordinator",
        "description": "Hierarchical research coordination with supervisor oversight",
        "swarm_type": "HierarchicalSwarm",
        "task": "Conduct comprehensive research on the impact of AI on healthcare, including technological advances, economic implications, ethical considerations, and future trends",
        "agents": [
            {
                "agent_name": "Research Coordinator",
                "description": "Supervisor agent coordinating research efforts and synthesizing results",
                "system_prompt": "You are a research coordinator supervising a team of specialized researchers. Delegate tasks, coordinate efforts, and synthesize final results into a comprehensive report.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            },
            {
                "agent_name": "Technology Researcher",
                "description": "Worker agent researching AI technological advances in healthcare",
                "system_prompt": "You are a technology researcher specializing in AI healthcare applications. Research and analyze current technological advances, breakthroughs, and implementation challenges.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            },
            {
                "agent_name": "Economic Analyst",
                "description": "Worker agent analyzing economic implications of AI in healthcare",
                "system_prompt": "You are an economic analyst specializing in healthcare economics. Research and analyze the economic implications, cost-benefit analysis, and market impact of AI in healthcare.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            },
            {
                "agent_name": "Ethics Specialist",
                "description": "Worker agent examining ethical considerations of AI in healthcare",
                "system_prompt": "You are an ethics specialist focusing on AI and healthcare ethics. Research and analyze ethical considerations, privacy concerns, bias issues, and regulatory implications.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            },
            {
                "agent_name": "Future Trends Analyst",
                "description": "Worker agent predicting future trends in AI healthcare",
                "system_prompt": "You are a future trends analyst specializing in healthcare technology. Research and analyze future trends, predictions, and long-term implications of AI in healthcare.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            }
        ],
        "max_loops": 1
    }

    response = requests.post(
        f"{API_BASE_URL}/v1/swarm/completions",
        headers=headers,
        json=swarm_config
    )

    if response.status_code == 200:
        result = response.json()
        print("HierarchicalSwarm swarm completed successfully!")
        print(f"Cost: ${result['usage']['billing_info']['total_cost']}")
        print(f"Execution time: {result['execution_time']} seconds")
        print(f"Hierarchical results: {result['output']}")
    else:
        print(f"Error: {response.status_code} - {response.text}")
    ```
  </Tab>

  <Tab title="JavaScript (fetch)">
    ```javascript theme={null}
    const API_BASE_URL = "https://api.swarms.world";
    const API_KEY = "your_api_key_here";

    const headers = {
        "x-api-key": API_KEY,
        "Content-Type": "application/json"
    };

    const swarmConfig = {
        name: "Research Project Coordinator",
        description: "Hierarchical research coordination with supervisor oversight",
        swarm_type: "HierarchicalSwarm",
        task: "Conduct comprehensive research on the impact of AI on healthcare, including technological advances, economic implications, ethical considerations, and future trends",
        agents: [
            {
                agent_name: "Research Coordinator",
                description: "Supervisor agent coordinating research efforts and synthesizing results",
                system_prompt: "You are a research coordinator supervising a team of specialized researchers. Delegate tasks, coordinate efforts, and synthesize final results into a comprehensive report.",
                model_name: "gpt-4.1",
                max_loops: 1,
                temperature: 0.3
            },
            {
                agent_name: "Technology Researcher",
                description: "Worker agent researching AI technological advances in healthcare",
                system_prompt: "You are a technology researcher specializing in AI healthcare applications. Research and analyze current technological advances, breakthroughs, and implementation challenges.",
                model_name: "gpt-4.1",
                max_loops: 1,
                temperature: 0.3
            },
            {
                agent_name: "Economic Analyst",
                description: "Worker agent analyzing economic implications of AI in healthcare",
                system_prompt: "You are an economic analyst specializing in healthcare economics. Research and analyze the economic implications, cost-benefit analysis, and market impact of AI in healthcare.",
                model_name: "gpt-4.1",
                max_loops: 1,
                temperature: 0.3
            },
            {
                agent_name: "Ethics Specialist",
                description: "Worker agent examining ethical considerations of AI in healthcare",
                system_prompt: "You are an ethics specialist focusing on AI and healthcare ethics. Research and analyze ethical considerations, privacy concerns, bias issues, and regulatory implications.",
                model_name: "gpt-4.1",
                max_loops: 1,
                temperature: 0.3
            },
            {
                agent_name: "Future Trends Analyst",
                description: "Worker agent predicting future trends in AI healthcare",
                system_prompt: "You are a future trends analyst specializing in healthcare technology. Research and analyze future trends, predictions, and long-term implications of AI in healthcare.",
                model_name: "gpt-4.1",
                max_loops: 1,
                temperature: 0.3
            }
        ],
        max_loops: 1
    };

    fetch(`${API_BASE_URL}/v1/swarm/completions`, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(swarmConfig)
    })
    .then(response => response.json())
    .then(result => {
        if (result.status === "success") {
            console.log("HierarchicalSwarm swarm completed successfully!");
            console.log(`Cost: $${result.usage.billing_info.total_cost}`);
            console.log(`Execution time: ${result.execution_time} seconds`);
            console.log("Hierarchical results:", result.output);
        }
    })
    .catch(error => console.error("Error:", error));
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
    )

    type Agent struct {
        AgentName    string  `json:"agent_name"`
        Description  string  `json:"description"`
        SystemPrompt string  `json:"system_prompt"`
        ModelName    string  `json:"model_name"`
        MaxLoops     int     `json:"max_loops"`
        Temperature  float64 `json:"temperature"`
    }

    type SwarmConfig struct {
        Name        string   `json:"name"`
        Description string   `json:"description"`
        SwarmType   string   `json:"swarm_type"`
        Task        string   `json:"task"`
        Agents      []Agent  `json:"agents"`
        MaxLoops    int      `json:"max_loops"`
    }

    func main() {
        API_BASE_URL := "https://api.swarms.world"
        API_KEY := "your_api_key_here"

        swarmConfig := SwarmConfig{
            Name:        "Research Project Coordinator",
            Description: "Hierarchical research coordination with supervisor oversight",
            SwarmType:   "HierarchicalSwarm",
            Task:        "Conduct comprehensive research on the impact of AI on healthcare, including technological advances, economic implications, ethical considerations, and future trends",
            Agents: []Agent{
                {
                    AgentName:    "Research Coordinator",
                    Description:  "Supervisor agent coordinating research efforts and synthesizing results",
                    SystemPrompt: "You are a research coordinator supervising a team of specialized researchers. Delegate tasks, coordinate efforts, and synthesize final results into a comprehensive report.",
                    ModelName:    "gpt-4.1",
                    MaxLoops:     1,
                    Temperature:  0.3,
                },
                {
                    AgentName:    "Technology Researcher",
                    Description:  "Worker agent researching AI technological advances in healthcare",
                    SystemPrompt: "You are a technology researcher specializing in AI healthcare applications. Research and analyze current technological advances, breakthroughs, and implementation challenges.",
                    ModelName:    "gpt-4.1",
                    MaxLoops:     1,
                    Temperature:  0.3,
                },
                {
                    AgentName:    "Economic Analyst",
                    Description:  "Worker agent analyzing economic implications of AI in healthcare",
                    SystemPrompt: "You are an economic analyst specializing in healthcare economics. Research and analyze the economic implications, cost-benefit analysis, and market impact of AI in healthcare.",
                    ModelName:    "gpt-4.1",
                    MaxLoops:     1,
                    Temperature:  0.3,
                },
                {
                    AgentName:    "Ethics Specialist",
                    Description:  "Worker agent examining ethical considerations of AI in healthcare",
                    SystemPrompt: "You are an ethics specialist focusing on AI and healthcare ethics. Research and analyze ethical considerations, privacy concerns, bias issues, and regulatory implications.",
                    ModelName:    "gpt-4.1",
                    MaxLoops:     1,
                    Temperature:  0.3,
                },
                {
                    AgentName:    "Future Trends Analyst",
                    Description:  "Worker agent predicting future trends in AI healthcare",
                    SystemPrompt: "You are a future trends analyst specializing in healthcare technology. Research and analyze future trends, predictions, and long-term implications of AI in healthcare.",
                    ModelName:    "gpt-4.1",
                    MaxLoops:     1,
                    Temperature:  0.3,
                },
            },
            MaxLoops: 1,
        }

        jsonData, _ := json.Marshal(swarmConfig)
        
        req, _ := http.NewRequest("POST", API_BASE_URL+"/v1/swarm/completions", bytes.NewBuffer(jsonData))
        req.Header.Set("x-api-key", API_KEY)
        req.Header.Set("Content-Type", "application/json")

        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            fmt.Printf("Error: %v\n", err)
            return
        }
        defer resp.Body.Close()

        body, _ := ioutil.ReadAll(resp.Body)
        fmt.Printf("Response: %s\n", string(body))
    }
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest::Client;
    use serde_json::{json, Value};
    use std::error::Error;

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn Error>> {
        let api_base_url = "https://api.swarms.world";
        let api_key = "your_api_key_here";

        let swarm_config = json!({
            "name": "Research Project Coordinator",
            "description": "Hierarchical research coordination with supervisor oversight",
            "swarm_type": "HierarchicalSwarm",
            "task": "Conduct comprehensive research on the impact of AI on healthcare, including technological advances, economic implications, ethical considerations, and future trends",
            "agents": [
                {
                    "agent_name": "Research Coordinator",
                    "description": "Supervisor agent coordinating research efforts and synthesizing results",
                    "system_prompt": "You are a research coordinator supervising a team of specialized researchers. Delegate tasks, coordinate efforts, and synthesize final results into a comprehensive report.",
                    "model_name": "gpt-4.1",
                    "max_loops": 1,
                    "temperature": 0.3
                },
                {
                    "agent_name": "Technology Researcher",
                    "description": "Worker agent researching AI technological advances in healthcare",
                    "system_prompt": "You are a technology researcher specializing in AI healthcare applications. Research and analyze current technological advances, breakthroughs, and implementation challenges.",
                    "model_name": "gpt-4.1",
                    "max_loops": 1,
                    "temperature": 0.3
                },
                {
                    "agent_name": "Economic Analyst",
                    "description": "Worker agent analyzing economic implications of AI in healthcare",
                    "system_prompt": "You are an economic analyst specializing in healthcare economics. Research and analyze the economic implications, cost-benefit analysis, and market impact of AI in healthcare.",
                    "model_name": "gpt-4.1",
                    "max_loops": 1,
                    "temperature": 0.3
                },
                {
                    "agent_name": "Ethics Specialist",
                    "description": "Worker agent examining ethical considerations of AI in healthcare",
                    "system_prompt": "You are an ethics specialist focusing on AI and healthcare ethics. Research and analyze ethical considerations, privacy concerns, bias issues, and regulatory implications.",
                    "model_name": "gpt-4.1",
                    "max_loops": 1,
                    "temperature": 0.3
                },
                {
                    "agent_name": "Future Trends Analyst",
                    "description": "Worker agent predicting future trends in AI healthcare",
                    "system_prompt": "You are a future trends analyst specializing in healthcare technology. Research and analyze future trends, predictions, and long-term implications of AI in healthcare.",
                    "model_name": "gpt-4.1",
                    "max_loops": 1,
                    "temperature": 0.3
                }
            ],
            "max_loops": 1
        });

        let client = Client::new();
        let response = client
            .post(&format!("{}/v1/swarm/completions", api_base_url))
            .header("x-api-key", api_key)
            .header("Content-Type", "application/json")
            .json(&swarm_config)
            .send()
            .await?;

        if response.status().is_success() {
            let result: Value = response.json().await?;
            println!("HierarchicalSwarm swarm completed successfully!");
            println!("Response: {:?}", result);
        } else {
            println!("Error: {}", response.status());
        }

        Ok(())
    }
    ```
  </Tab>
</Tabs>

**Example Response**:

```json theme={null}
{
    "job_id": "swarms-H17nZFDesmLHxCRoeyF3NVYvPaXk",
    "status": "success",
    "swarm_name": "Research Project Coordinator",
    "description": "Hierarchical research coordination with supervisor oversight",
    "swarm_type": "HierarchicalSwarm",
    "output": [
        {
            "role": "Research Coordinator",
            "content": "As the Research Coordinator, I have synthesized the findings from our specialized research team into a comprehensive report on AI's impact on healthcare..."
        },
        {
            "role": "Technology Researcher",
            "content": "My research on AI technological advances in healthcare reveals significant breakthroughs in diagnostic imaging, drug discovery, and personalized medicine..."
        },
        {
            "role": "Economic Analyst",
            "content": "The economic analysis shows that AI in healthcare could reduce costs by 15-20% while improving outcomes, though initial implementation costs are substantial..."
        },
        {
            "role": "Ethics Specialist",
            "content": "Ethical considerations include data privacy, algorithmic bias, transparency in decision-making, and ensuring human oversight in critical healthcare decisions..."
        },
        {
            "role": "Future Trends Analyst",
            "content": "Future trends indicate rapid adoption of AI in preventive care, remote monitoring, and personalized treatment plans, with full integration expected within 5-10 years..."
        }
    ],
    "number_of_agents": 5,
    "execution_time": 45.8,
    "usage": {
        "input_tokens": 55,
        "output_tokens": 3200,
        "total_tokens": 3255,
        "billing_info": {
            "cost_breakdown": {
                "agent_cost": 0.05,
                "input_token_cost": 0.000165,
                "output_token_cost": 0.048,
                "token_counts": {
                    "total_input_tokens": 55,
                    "total_output_tokens": 3200,
                    "total_tokens": 3255
                },
                "num_agents": 5,
                "night_time_discount_applied": true
            },
            "total_cost": 0.098165,
            "discount_active": true,
            "discount_type": "night_time",
            "discount_percentage": 50
        }
    }
}
```

## Configuring the Director

`HierarchicalSwarm` runs a director agent that decomposes the task and delegates it to your worker agents. The director is created by the swarm itself rather than supplied in the `agents` array, so it is configured through two top-level `SwarmSpec` fields.

| Parameter             | Type     | Default     | Description                                                                                          |
| --------------------- | -------- | ----------- | ---------------------------------------------------------------------------------------------------- |
| `director_model_name` | `string` | `"gpt-5.4"` | The model the director uses to plan and delegate.                                                    |
| `director_settings`   | `object` | `{}`        | Sampling and generation settings for the director, such as `temperature`, `top_p`, and `max_tokens`. |

<Tabs>
  <Tab title="Shell (curl)">
    ```bash theme={null}
    curl -X POST "https://api.swarms.world/v1/swarm/completions" \
      -H "x-api-key: $SWARMS_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Research Project Coordinator",
        "swarm_type": "HierarchicalSwarm",
        "task": "Research the impact of AI on healthcare",
        "director_model_name": "gpt-5.4",
        "director_settings": {
          "temperature": 0.2,
          "max_tokens": 4000
        },
        "agents": [
          {
            "agent_name": "Technology Researcher",
            "system_prompt": "You research AI technology in healthcare.",
            "model_name": "gpt-4.1"
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import os
    import requests

    response = requests.post(
        "https://api.swarms.world/v1/swarm/completions",
        headers={"x-api-key": os.getenv("SWARMS_API_KEY")},
        json={
            "name": "Research Project Coordinator",
            "swarm_type": "HierarchicalSwarm",
            "task": "Research the impact of AI on healthcare",
            "director_model_name": "gpt-5.4",
            "director_settings": {
                "temperature": 0.2,
                "max_tokens": 4000,
            },
            "agents": [
                {
                    "agent_name": "Technology Researcher",
                    "system_prompt": "You research AI technology in healthcare.",
                    "model_name": "gpt-4.1",
                }
            ],
        },
    )

    print(response.json())
    ```
  </Tab>
</Tabs>

<Tip>
  A lower `temperature` on the director produces more consistent task decomposition and delegation, while worker agents can keep a higher temperature for creative output.
</Tip>

## Best Practices

* Design clear supervisor-worker relationships
* Ensure supervisors can effectively coordinate and synthesize results
* Use a capable `director_model_name` — the director's plan determines how well the workers perform
* Lower the director's `temperature` for more deterministic task decomposition
* Use for complex projects requiring oversight and coordination
* Ideal for research, content creation, and project management
