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
- Parallel Execution: Workers run their orders at the same time
- Resource Coordination: Efficient allocation and management of agent resources
Architecture
The supervisor plans the task and hands an order to each worker it picks. The workers run their orders in parallel, and the swarm returns their outputs. There is no review or synthesis step: the API doesn’t enable the director’s feedback pass, so no agent reads the others’ work within a loop. Withmax_loops above 1, each later loop gives the director the
previous loop’s results to plan from.
The “Supervisor” in the diagram is a director agent that
HierarchicalSwarm creates for you automatically — it is not one of the entries in agents. Every agent you list in agents runs as a worker the director can delegate to, even if you name one of them “coordinator” or set its role. To have one agent merge the others’ work, use AgentRearrange with a flow that ends at that agent (e.g. "a, b, c -> synthesizer"), SequentialWorkflow, or a Graph Workflow. Tune the director itself with the top-level director_model_name and director_settings fields (see Configuring the Director below).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
- Shell (curl)
- Python (requests)
- JavaScript (fetch)
- Go
- Rust
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": "Worker agent that writes the report's overview section",
"system_prompt": "You are the lead researcher on the team. Write a concise overview of AI's impact on healthcare that frames the specialists' sections.",
"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
}'
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": "Worker agent that writes the report's overview section",
"system_prompt": "You are the lead researcher on the team. Write a concise overview of AI's impact on healthcare that frames the specialists' sections.",
"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}")
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: "Worker agent that writes the report's overview section",
system_prompt: "You are the lead researcher on the team. Write a concise overview of AI's impact on healthcare that frames the specialists' sections.",
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));
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: "Worker agent that writes the report's overview section",
SystemPrompt: "You are the lead researcher on the team. Write a concise overview of AI's impact on healthcare that frames the specialists' sections.",
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))
}
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": "Worker agent that writes the report's overview section",
"system_prompt": "You are the lead researcher on the team. Write a concise overview of AI's impact on healthcare that frames the specialists' sections.",
"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(())
}
{
"job_id": "swarms-H17nZFDesmLHxCRoeyF3NVYvPaXk",
"status": "success",
"swarm_name": "Research Project Coordinator",
"description": "Hierarchical research coordination with supervisor oversight",
"swarm_type": "HierarchicalSwarm",
"output": [
{
"role": "System",
"content": "These are the agents in your team. Each agent has a specific role and expertise to contribute to the team's objectives.\nTotal Agents: 5\n..."
},
{
"role": "Director",
"content": "[function: arguments: \"{\"orders\":[{\"agent_name\":\"Research Coordinator\",\"task\":\"...\"}, ...]}\"\nname: \"OrderBatch\" ...]"
},
{
"role": "Research Coordinator",
"content": "Overview: AI is reshaping healthcare across diagnostics, operations, and patient care. The sections below cover technology, economics, ethics, and future trends..."
},
{
"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..."
},
{
"role": "System",
"content": "--- Loop 1/1 completed ---"
}
],
"number_of_agents": 5,
"execution_time": 45.8,
"usage": {
"input_tokens": 55,
"output_tokens": 3200,
"total_tokens": 3255,
"total_cost": 0.079779,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.05,
"input_token_cost": 0.000179,
"output_token_cost": 0.0296,
"token_counts": {
"total_input_tokens": 55,
"total_output_tokens": 3200,
"total_tokens": 3255
},
"num_agents": 5,
"night_time_discount_applied": true,
"flash_sale_applied": false
},
"total_cost": 0.079779,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 50
}
},
"tasks": null,
"messages": null
}
output always starts with a System turn listing the team and a Director turn holding the director’s orders, and each loop ends with a System turn such as --- Loop 1/1 completed ---. The worker turns in between are the actual answers. The director’s turn is named after director_settings.agent_name when you set it.
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 | {} | Settings for the director. Accepts only the keys below; any other key returns a 422. |
director_settings keys:
| Key | Type | Description |
|---|---|---|
agent_name | string | The director’s name, used as the role of its turn in output. |
system_prompt | string | Replaces the director’s system prompt for writing orders. |
planning_system_prompt | string | The system prompt for the director’s planning pass. Accepted, but the API doesn’t turn the planning pass on, so it currently has no effect. |
temperature | number | 0 to 2. |
top_p | number | The director’s top_p. |
max_tokens | integer | 1 to 128000. |
director_model_name; model_name is not accepted inside director_settings:
{
"detail": [
{
"type": "extra_forbidden",
"loc": ["body", "director_settings", "model_name"],
"msg": "Extra inputs are not permitted"
}
]
}
- Shell (curl)
- Python
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"
}
]
}'
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())
A lower
temperature on the director produces more consistent task decomposition and delegation, while worker agents can keep a higher temperature for creative output.Errors
Besides the errors every swarm can return (see the Swarm Completions Reference), aHierarchicalSwarm returns 502 when the director doesn’t produce valid orders, for example because its max_tokens is too small for the order list. No worker runs and nothing is charged:
{
"detail": "The director of swarm 'Research Project Coordinator' did not return valid orders, so no agent ran. Nothing was charged. Check director_model_name and director_settings and try again."
}
Best Practices
- Design clear supervisor-worker relationships
- Give each worker a self-contained responsibility, since workers don’t see each other’s output
- Use a capable
director_model_name— the director’s plan determines how well the workers perform - Lower the director’s
temperaturefor more deterministic task decomposition - Use for complex projects requiring oversight and coordination
- Ideal for research, content creation, and project management