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
- Shell (curl)
- Python (requests)
- JavaScript (fetch)
- Go
- Rust
Copy
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-4o",
"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-4o",
"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-4o",
"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-4o",
"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-4o",
"max_loops": 1,
"temperature": 0.3
}
],
"max_loops": 1
}'
Copy
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-4o",
"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-4o",
"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-4o",
"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-4o",
"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-4o",
"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['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
print(f"Hierarchical results: {result['output']}")
else:
print(f"Error: {response.status_code} - {response.text}")
Copy
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-4o",
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-4o",
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-4o",
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-4o",
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-4o",
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.metadata.billing_info.total_cost}`);
console.log(`Execution time: ${result.metadata.execution_time_seconds} seconds`);
console.log("Hierarchical results:", result.output);
}
})
.catch(error => console.error("Error:", error));
Copy
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-4o",
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-4o",
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-4o",
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-4o",
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-4o",
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))
}
Copy
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-4o",
"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-4o",
"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-4o",
"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-4o",
"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-4o",
"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(())
}
Copy
{
"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,
"service_tier": "standard",
"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,
"service_tier": "standard",
"night_time_discount_applied": true
},
"total_cost": 0.098165,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 75
}
}
}
Best Practices
- Design clear supervisor-worker relationships
- Ensure supervisors can effectively coordinate and synthesize results
- Use for complex projects requiring oversight and coordination
- Ideal for research, content creation, and project management