AgentRearrange
Overview
The AgentRearrange swarm type runs your agents in the order you define withrearrange_flow. You can reorganize how agents pass work to one another, mixing sequential handoffs and parallel steps, without changing the agents themselves. The flow is fixed for the request: nothing reassigns roles or adapts the order while the swarm runs.
Key features:
- Explicit Flow Control:
rearrange_flowsets exactly which agents run, in which order - Sequential and Parallel Steps:
->hands work to the next step, and a comma runs agents in parallel within a step - Reorganize Without Rewriting: Change the pipeline by editing the flow string, not the agents
- Real Synthesis Steps: An agent at the end of the flow receives the earlier agents’ outputs
Architecture
The shape comes fromrearrange_flow. Above is "Researcher -> Writer, Editor": -> is a
handoff to the next step, and a comma runs agents in parallel within the same step.
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
The
AgentRearrange swarm type requires the rearrange_flow parameter. It is a string that defines how tasks flow between agents by agent_name: use -> for sequential handoffs and commas for agents that run in parallel within the same step (e.g. "Researcher -> Writer, Editor"). Requests without rearrange_flow are rejected with a 400 error, and so is a flow that names an agent that isn’t in agents: every name in the flow must be the exact agent_name of one of the agents (e.g. 400 “rearrange_flow names [‘Reviewer’], which match no agent_name in ‘agents’”).Basic AgentRearrange 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": "Adaptive Content Creation",
"description": "Dynamic content creation with flexible agent role assignment",
"swarm_type": "AgentRearrange",
"rearrange_flow": "Research Specialist -> Technical Writer -> Finance Expert -> Editor",
"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-4.1",
"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-4.1",
"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-4.1",
"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-4.1",
"max_loops": 1,
"temperature": 0.4
}
],
"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": "Adaptive Content Creation",
"description": "Dynamic content creation with flexible agent role assignment",
"swarm_type": "AgentRearrange",
"rearrange_flow": "Research Specialist -> Technical Writer -> Finance Expert -> Editor",
"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-4.1",
"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-4.1",
"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-4.1",
"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-4.1",
"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['usage']['billing_info']['total_cost']}")
print(f"Execution time: {result['execution_time']} seconds")
print(f"Dynamic 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: "Adaptive Content Creation",
description: "Dynamic content creation with flexible agent role assignment",
swarm_type: "AgentRearrange",
rearrange_flow: "Research Specialist -> Technical Writer -> Finance Expert -> Editor",
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-4.1",
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-4.1",
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-4.1",
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-4.1",
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.usage.billing_info.total_cost}`);
console.log(`Execution time: ${result.execution_time} seconds`);
console.log("Dynamic 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"`
RearrangeFlow string `json:"rearrange_flow"`
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",
RearrangeFlow: "Research Specialist -> Technical Writer -> Finance Expert -> Editor",
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-4.1",
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-4.1",
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-4.1",
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-4.1",
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))
}
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",
"rearrange_flow": "Research Specialist -> Technical Writer -> Finance Expert -> Editor",
"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-4.1",
"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-4.1",
"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-4.1",
"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-4.1",
"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(())
}
{
"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..."
}
],
"number_of_agents": 4,
"execution_time": 38.2,
"usage": {
"input_tokens": 45,
"output_tokens": 2800,
"total_tokens": 2845,
"total_cost": 0.066046,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.04,
"input_token_cost": 0.000146,
"output_token_cost": 0.0259,
"token_counts": {
"total_input_tokens": 45,
"total_output_tokens": 2800,
"total_tokens": 2845
},
"num_agents": 4,
"night_time_discount_applied": true,
"flash_sale_applied": false
},
"total_cost": 0.066046,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 50
}
}
}
Best Practices
- Spell every name in
rearrange_flowexactly as the agent’sagent_name - Put agents that can work independently in the same step, separated by commas
- End the flow at a synthesizer agent when you want one combined answer
- Ideal for custom pipelines mixing sequential and parallel stages