AgentRearrange
Overview
The AgentRearrange swarm type implements a dynamic architecture where agents can be reassigned to different roles and responsibilities based on task requirements, performance metrics, or changing circumstances. This flexibility allows the swarm to adapt to different scenarios and optimize performance through intelligent role reallocation. Key features:- Dynamic Role Assignment: Agents can switch roles based on task needs
- Performance-Based Reorganization: Roles adjusted based on agent performance
- Adaptive Architecture: Swarm structure evolves with changing requirements
- Flexible Resource Allocation: Optimal use of agent capabilities
Use Cases
- Dynamic project management with changing requirements
- Adaptive content creation workflows
- Performance optimization in multi-agent systems
- Flexible task allocation based on agent strengths
API Usage
Basic AgentRearrange 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": "Adaptive Content Creation",
"description": "Dynamic content creation with flexible agent role assignment",
"swarm_type": "AgentRearrange",
"task": "Create a comprehensive technical blog post about machine learning in finance, with the ability to reassign agent roles based on content needs",
"agents": [
{
"agent_name": "Research Specialist",
"description": "Conducts research and gathers information",
"system_prompt": "You are a research specialist. Gather comprehensive information on machine learning applications in finance, including current trends, use cases, and future prospects.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Technical Writer",
"description": "Creates technical content and explanations",
"system_prompt": "You are a technical writer specializing in machine learning and finance. Create clear, engaging technical content that explains complex concepts in accessible terms.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.5
},
{
"agent_name": "Finance Expert",
"description": "Provides financial domain expertise",
"system_prompt": "You are a finance expert with knowledge of machine learning applications. Ensure accuracy in financial concepts, market analysis, and industry insights.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Editor",
"description": "Reviews and polishes content",
"system_prompt": "You are a professional editor. Review content for clarity, flow, accuracy, and overall quality. Make improvements while maintaining technical accuracy.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.4
}
],
"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": "Adaptive Content Creation",
"description": "Dynamic content creation with flexible agent role assignment",
"swarm_type": "AgentRearrange",
"task": "Create a comprehensive technical blog post about machine learning in finance, with the ability to reassign agent roles based on content needs",
"agents": [
{
"agent_name": "Research Specialist",
"description": "Conducts research and gathers information",
"system_prompt": "You are a research specialist. Gather comprehensive information on machine learning applications in finance, including current trends, use cases, and future prospects.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Technical Writer",
"description": "Creates technical content and explanations",
"system_prompt": "You are a technical writer specializing in machine learning and finance. Create clear, engaging technical content that explains complex concepts in accessible terms.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.5
},
{
"agent_name": "Finance Expert",
"description": "Provides financial domain expertise",
"system_prompt": "You are a finance expert with knowledge of machine learning applications. Ensure accuracy in financial concepts, market analysis, and industry insights.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Editor",
"description": "Reviews and polishes content",
"system_prompt": "You are a professional editor. Review content for clarity, flow, accuracy, and overall quality. Make improvements while maintaining technical accuracy.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.4
}
],
"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("AgentRearrange swarm completed successfully!")
print(f"Cost: ${result['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
print(f"Dynamic 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: "Adaptive Content Creation",
description: "Dynamic content creation with flexible agent role assignment",
swarm_type: "AgentRearrange",
task: "Create a comprehensive technical blog post about machine learning in finance, with the ability to reassign agent roles based on content needs",
agents: [
{
agent_name: "Research Specialist",
description: "Conducts research and gathers information",
system_prompt: "You are a research specialist. Gather comprehensive information on machine learning applications in finance, including current trends, use cases, and future prospects.",
model_name: "gpt-4o",
max_loops: 1,
temperature: 0.3
},
{
agent_name: "Technical Writer",
description: "Creates technical content and explanations",
system_prompt: "You are a technical writer specializing in machine learning and finance. Create clear, engaging technical content that explains complex concepts in accessible terms.",
model_name: "gpt-4o",
max_loops: 1,
temperature: 0.5
},
{
agent_name: "Finance Expert",
description: "Provides financial domain expertise",
system_prompt: "You are a finance expert with knowledge of machine learning applications. Ensure accuracy in financial concepts, market analysis, and industry insights.",
model_name: "gpt-4o",
max_loops: 1,
temperature: 0.3
},
{
agent_name: "Editor",
description: "Reviews and polishes content",
system_prompt: "You are a professional editor. Review content for clarity, flow, accuracy, and overall quality. Make improvements while maintaining technical accuracy.",
model_name: "gpt-4o",
max_loops: 1,
temperature: 0.4
}
],
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("AgentRearrange swarm completed successfully!");
console.log(`Cost: $${result.metadata.billing_info.total_cost}`);
console.log(`Execution time: ${result.metadata.execution_time_seconds} seconds`);
console.log("Dynamic 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: "Adaptive Content Creation",
Description: "Dynamic content creation with flexible agent role assignment",
SwarmType: "AgentRearrange",
Task: "Create a comprehensive technical blog post about machine learning in finance, with the ability to reassign agent roles based on content needs",
Agents: []Agent{
{
AgentName: "Research Specialist",
Description: "Conducts research and gathers information",
SystemPrompt: "You are a research specialist. Gather comprehensive information on machine learning applications in finance, including current trends, use cases, and future prospects.",
ModelName: "gpt-4o",
MaxLoops: 1,
Temperature: 0.3,
},
{
AgentName: "Technical Writer",
Description: "Creates technical content and explanations",
SystemPrompt: "You are a technical writer specializing in machine learning and finance. Create clear, engaging technical content that explains complex concepts in accessible terms.",
ModelName: "gpt-4o",
MaxLoops: 1,
Temperature: 0.5,
},
{
AgentName: "Finance Expert",
Description: "Provides financial domain expertise",
SystemPrompt: "You are a finance expert with knowledge of machine learning applications. Ensure accuracy in financial concepts, market analysis, and industry insights.",
ModelName: "gpt-4o",
MaxLoops: 1,
Temperature: 0.3,
},
{
AgentName: "Editor",
Description: "Reviews and polishes content",
SystemPrompt: "You are a professional editor. Review content for clarity, flow, accuracy, and overall quality. Make improvements while maintaining technical accuracy.",
ModelName: "gpt-4o",
MaxLoops: 1,
Temperature: 0.4,
},
},
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": "Adaptive Content Creation",
"description": "Dynamic content creation with flexible agent role assignment",
"swarm_type": "AgentRearrange",
"task": "Create a comprehensive technical blog post about machine learning in finance, with the ability to reassign agent roles based on content needs",
"agents": [
{
"agent_name": "Research Specialist",
"description": "Conducts research and gathers information",
"system_prompt": "You are a research specialist. Gather comprehensive information on machine learning applications in finance, including current trends, use cases, and future prospects.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Technical Writer",
"description": "Creates technical content and explanations",
"system_prompt": "You are a technical writer specializing in machine learning and finance. Create clear, engaging technical content that explains complex concepts in accessible terms.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.5
},
{
"agent_name": "Finance Expert",
"description": "Provides financial domain expertise",
"system_prompt": "You are a finance expert with knowledge of machine learning applications. Ensure accuracy in financial concepts, market analysis, and industry insights.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Editor",
"description": "Reviews and polishes content",
"system_prompt": "You are a professional editor. Review content for clarity, flow, accuracy, and overall quality. Make improvements while maintaining technical accuracy.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.4
}
],
"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!("AgentRearrange swarm completed successfully!");
println!("Response: {:?}", result);
} else {
println!("Error: {}", response.status());
}
Ok(())
}
Copy
{
"job_id": "swarms-A17nZFDesmLHxCRoeyF3NVYvPaXk",
"status": "success",
"swarm_name": "Adaptive Content Creation",
"description": "Dynamic content creation with flexible agent role assignment",
"swarm_type": "AgentRearrange",
"output": [
{
"role": "Research Specialist",
"content": "My research on machine learning in finance reveals key applications in algorithmic trading, risk assessment, fraud detection, and customer service automation..."
},
{
"role": "Technical Writer",
"content": "Building on the research, I've created a comprehensive technical blog post that explains machine learning concepts in finance..."
},
{
"role": "Finance Expert",
"content": "I've reviewed the technical content to ensure financial accuracy, including proper terminology and market insights..."
},
{
"role": "Editor",
"content": "I've edited the content for clarity and flow while maintaining technical accuracy and financial precision..."
}
],
"agent_rearrangement": "Agents successfully reorganized based on content creation workflow",
"number_of_agents": 4,
"service_tier": "standard",
"execution_time": 38.2,
"usage": {
"input_tokens": 45,
"output_tokens": 2800,
"total_tokens": 2845,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.04,
"input_token_cost": 0.000135,
"output_token_cost": 0.042,
"token_counts": {
"total_input_tokens": 45,
"total_output_tokens": 2800,
"total_tokens": 2845
},
"num_agents": 4,
"service_tier": "standard",
"night_time_discount_applied": true
},
"total_cost": 0.082135,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 75
}
}
}
Best Practices
- Design agents with flexible, transferable skills
- Use for projects with evolving requirements
- Ensure agents can adapt to different roles effectively
- Ideal for dynamic workflows and adaptive systems