fixes and cleanup !

pull/1001/head
harshalmore31 1 month ago
parent 117f49c3b2
commit cfc7c11d2c

@ -449,16 +449,16 @@ nav:
- Swarm Types:
- AgentRearrange: "swarms_cloud/agent_rearrange.md"
- MixtureOfAgents: "swarms_cloud/mixture_of_agents.md"
- SpreadSheetSwarm: "swarms_cloud/spreadsheet_swarm.md"
# - SpreadSheetSwarm: "swarms_cloud/spreadsheet_swarm.md"
- SequentialWorkflow: "swarms_cloud/sequential_workflow.md"
- ConcurrentWorkflow: "swarms_cloud/concurrent_workflow.md"
- GroupChat: "swarms_cloud/group_chat.md"
# - GroupChat: "swarms_cloud/group_chat.md"
- MultiAgentRouter: "swarms_cloud/multi_agent_router.md"
- AutoSwarmBuilder: "swarms_cloud/auto_swarm_builder.md"
- HierarchicalSwarm: "swarms_cloud/hierarchical_swarm.md"
- Auto: "swarms_cloud/auto.md"
# - AutoSwarmBuilder: "swarms_cloud/auto_swarm_builder.md"
# - HierarchicalSwarm: "swarms_cloud/hierarchical_swarm.md"
# - Auto: "swarms_cloud/auto.md"
- MajorityVoting: "swarms_cloud/majority_voting.md"
- MALT: "swarms_cloud/malt.md"
# - MALT: "swarms_cloud/malt.md"
- Examples:
- Medical Swarm: "swarms/examples/swarms_api_medical.md"
- Finance Swarm: "swarms/examples/swarms_api_finance.md"

@ -61,7 +61,7 @@ Key features:
"temperature": 0.4
}
],
"rearrange_flow": "Optimize agent sequence based on document complexity and required output quality",
"rearrange_flow": "Summarizer -> Legal Expert -> Document Analyzer",
"max_loops": 1
}'
```
@ -110,7 +110,7 @@ Key features:
"temperature": 0.4
}
],
"rearrange_flow": "Optimize agent sequence based on document complexity and required output quality",
"rearrange_flow": "Summarizer -> Legal Expert -> Document Analyzer",
"max_loops": 1
}
@ -133,24 +133,52 @@ Key features:
**Example Response**:
```json
{
"status": "success",
"swarm_name": "document-processing-rearrange",
"swarm_type": "AgentRearrange",
"task": "Analyze this legal document and extract key insights, then summarize findings and identify action items",
"output": {
"analysis": "Document analysis results...",
"legal_insights": "Legal implications and risks...",
"summary": "Concise summary of findings...",
"action_items": ["Action 1", "Action 2", "Action 3"]
},
"metadata": {
"agent_sequence": ["Legal Expert", "Document Analyzer", "Summarizer"],
"rearrangement_reason": "Optimized for legal document analysis workflow",
"execution_time_seconds": 18.2,
"billing_info": {
"total_cost": 0.045
"job_id": "swarms-Uc8R7UcepLmNNPwcU7JC6YPy5wiI",
"status": "success",
"swarm_name": "Document Processing Rearrange",
"description": "Process documents with dynamic agent reorganization",
"swarm_type": "AgentRearrange",
"output": [
{
"role": "Summarizer",
"content": "\"Of course! Please provide the legal document you would like me to analyze, and I'll help extract key insights, summarize findings, and identify any action items.\""
},
{
"role": "Legal Expert",
"content": "\"\"Absolutely! Please upload or describe the legal document you need assistance with, and I'll provide an analysis that highlights key insights, summarizes the findings, and identifies any action items that may be necessary.\"\""
},
{
"role": "Document Analyzer",
"content": "\"Of course! Please provide the legal document you would like me to analyze, and I'll help extract key insights, summarize findings, and identify any action items.\""
}
],
"number_of_agents": 3,
"service_tier": "standard",
"execution_time": 7.898931264877319,
"usage": {
"input_tokens": 22,
"output_tokens": 144,
"total_tokens": 166,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.03,
"input_token_cost": 0.000066,
"output_token_cost": 0.00216,
"token_counts": {
"total_input_tokens": 22,
"total_output_tokens": 144,
"total_tokens": 166
},
"num_agents": 3,
"service_tier": "standard",
"night_time_discount_applied": true
},
"total_cost": 0.032226,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 75
}
}
}
}
```

@ -23,155 +23,7 @@ Key features:
## API Usage
### Basic Auto Example
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Auto Content Creation",
"description": "Let the system choose the best approach for content creation",
"swarm_type": "auto",
"task": "Create a comprehensive blog post about sustainable investing, including research, writing, editing, and SEO optimization",
"max_loops": 1
}'
```
=== "Python (requests)"
```python
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": "Auto Content Creation",
"description": "Let the system choose the best approach for content creation",
"swarm_type": "auto",
"task": "Create a comprehensive blog post about sustainable investing, including research, writing, editing, and SEO optimization",
"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("Auto swarm completed successfully!")
print(f"Selected architecture: {result['metadata']['selected_swarm_type']}")
print(f"Cost: ${result['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
print(f"Content: {result['output']}")
else:
print(f"Error: {response.status_code} - {response.text}")
```
**Example Response**:
```json
{
"status": "success",
"swarm_name": "auto-content-creation",
"swarm_type": "SequentialWorkflow",
"task": "Create a comprehensive blog post about sustainable investing, including research, writing, editing, and SEO optimization",
"output": {
"research_phase": {
"key_findings": "Sustainable investing has grown 42% in the past two years...",
"market_trends": "ESG funds outperformed traditional funds by 3.2%...",
"statistics": "Global sustainable investment assets reached $35.3 trillion..."
},
"writing_phase": {
"title": "The Future of Sustainable Investing: A Guide to ESG Strategies",
"content": "Comprehensive blog post with introduction, main sections, and conclusion...",
"word_count": 1850
},
"editing_phase": {
"improvements": "Enhanced clarity, improved flow, corrected grammar",
"readability_score": "Grade 8 level - accessible to general audience",
"final_content": "Polished blog post ready for publication..."
},
"seo_optimization": {
"target_keywords": ["sustainable investing", "ESG funds", "green finance"],
"meta_description": "Discover the future of sustainable investing...",
"optimized_content": "SEO-optimized version with strategic keyword placement"
}
},
"metadata": {
"auto_selection": {
"selected_swarm_type": "SequentialWorkflow",
"reasoning": "Task requires step-by-step content creation process where each phase builds on the previous",
"analysis": {
"task_complexity": "Medium-High",
"sequential_dependencies": true,
"parallel_opportunities": false,
"collaboration_needs": "Low"
}
},
"generated_agents": [
"Research Specialist",
"Content Writer",
"Editor",
"SEO Optimizer"
],
"execution_time_seconds": 43.2,
"billing_info": {
"total_cost": 0.087
}
}
}
```
### Advanced Auto Usage
You can provide additional context to help the Auto selection:
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Auto Business Analysis",
"description": "Automatic swarm selection for business analysis",
"swarm_type": "auto",
"task": "Analyze market opportunities for a new AI startup in healthcare",
"rules": "Need multiple perspectives from different business functions, time-sensitive analysis required",
"max_loops": 1
}'
```
=== "Python (requests)"
```python
swarm_config = {
"name": "Auto Business Analysis",
"description": "Automatic swarm selection for business analysis",
"swarm_type": "auto",
"task": "Analyze market opportunities for a new AI startup in healthcare",
"rules": "Need multiple perspectives from different business functions, time-sensitive analysis required",
"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(f"Auto selected: {result['metadata']['auto_selection']['selected_swarm_type']}")
print(f"Reasoning: {result['metadata']['auto_selection']['reasoning']}")
```
## Selection Logic

@ -1,4 +1,4 @@
# AutoSwarmBuilder
# AutoSwarmBuilder [ Needs an Fix ]
*Automatically configures optimal swarm architectures based on task requirements*
@ -23,155 +23,6 @@ Key features:
## API Usage
### Basic AutoSwarmBuilder Example
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Auto Marketing Campaign",
"description": "Automatically build optimal swarm for marketing campaign creation",
"swarm_type": "AutoSwarmBuilder",
"task": "Create a comprehensive digital marketing campaign for a new sustainable fashion brand targeting Gen Z consumers",
"max_loops": 1
}'
```
=== "Python (requests)"
```python
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": "Auto Marketing Campaign",
"description": "Automatically build optimal swarm for marketing campaign creation",
"swarm_type": "AutoSwarmBuilder",
"task": "Create a comprehensive digital marketing campaign for a new sustainable fashion brand targeting Gen Z consumers",
"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("AutoSwarmBuilder completed successfully!")
print(f"Generated swarm architecture: {result['metadata']['generated_architecture']}")
print(f"Cost: ${result['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
print(f"Campaign output: {result['output']}")
else:
print(f"Error: {response.status_code} - {response.text}")
```
**Example Response**:
```json
{
"status": "success",
"swarm_name": "auto-marketing-campaign",
"swarm_type": "AutoSwarmBuilder",
"task": "Create a comprehensive digital marketing campaign for a new sustainable fashion brand targeting Gen Z consumers",
"output": {
"campaign_strategy": {
"brand_positioning": "Authentic, sustainable fashion for conscious Gen Z consumers",
"key_messaging": "Style that makes a difference - fashion with purpose",
"target_demographics": "Ages 18-26, environmentally conscious, social media active"
},
"content_strategy": {
"social_platforms": ["TikTok", "Instagram", "Pinterest"],
"content_pillars": ["Sustainability education", "Style inspiration", "Behind-the-scenes"],
"posting_schedule": "Daily posts across platforms with peak engagement timing"
},
"influencer_strategy": {
"tier_1": "Micro-influencers (10K-100K followers) focused on sustainability",
"tier_2": "Fashion nano-influencers (1K-10K followers) for authentic engagement",
"collaboration_types": ["Product partnerships", "Brand ambassador programs"]
},
"paid_advertising": {
"platforms": ["Instagram Ads", "TikTok Ads", "Google Ads"],
"budget_allocation": "40% social media, 30% search, 30% video content",
"targeting_strategy": "Interest-based and lookalike audiences"
},
"metrics_and_kpis": {
"awareness": "Brand mention volume, reach, impressions",
"engagement": "Comments, shares, saves, time spent",
"conversion": "Website traffic, email signups, sales"
}
},
"metadata": {
"generated_architecture": {
"selected_swarm_type": "MixtureOfAgents",
"generated_agents": [
"Brand Strategy Expert",
"Gen Z Marketing Specialist",
"Social Media Content Creator",
"Influencer Marketing Manager",
"Digital Advertising Strategist"
],
"reasoning": "Complex marketing campaign requires diverse expertise working collaboratively"
},
"auto_optimization": {
"task_complexity": "High",
"required_expertise_areas": 5,
"optimal_architecture": "Collaborative with specialized agents"
},
"execution_time_seconds": 28.6,
"billing_info": {
"total_cost": 0.071
}
}
}
```
### Advanced Configuration
You can provide additional guidance to the AutoSwarmBuilder:
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Auto Research Project",
"description": "Auto-build research swarm with specific constraints",
"swarm_type": "AutoSwarmBuilder",
"task": "Conduct comprehensive research on the impact of AI on healthcare outcomes",
"rules": "Focus on peer-reviewed sources, include cost-benefit analysis, ensure balanced perspective on risks and benefits",
"max_loops": 1
}'
```
=== "Python (requests)"
```python
swarm_config = {
"name": "Auto Research Project",
"description": "Auto-build research swarm with specific constraints",
"swarm_type": "AutoSwarmBuilder",
"task": "Conduct comprehensive research on the impact of AI on healthcare outcomes",
"rules": "Focus on peer-reviewed sources, include cost-benefit analysis, ensure balanced perspective on risks and benefits",
"max_loops": 1
}
response = requests.post(
f"{API_BASE_URL}/v1/swarm/completions",
headers=headers,
json=swarm_config
)
```
## Configuration Options

@ -147,40 +147,56 @@ Key features:
**Example Response**:
```json
{
"status": "success",
"swarm_name": "market-research-concurrent",
"swarm_type": "ConcurrentWorkflow",
"task": "Research and analyze market opportunities in AI, healthcare, fintech, and e-commerce sectors",
"output": {
"ai_market_analysis": {
"market_size": "$150B by 2025",
"growth_rate": "25% CAGR",
"key_opportunities": ["Generative AI", "Edge AI", "AI Infrastructure"]
},
"healthcare_analysis": {
"market_size": "$350B by 2025",
"growth_rate": "12% CAGR",
"key_opportunities": ["Telemedicine", "AI Diagnostics", "Digital Therapeutics"]
},
"fintech_analysis": {
"market_size": "$200B by 2025",
"growth_rate": "18% CAGR",
"key_opportunities": ["DeFi", "Digital Banking", "Payment Infrastructure"]
},
"ecommerce_analysis": {
"market_size": "$8T by 2025",
"growth_rate": "14% CAGR",
"key_opportunities": ["Social Commerce", "B2B Marketplaces", "Sustainable Commerce"]
}
},
"metadata": {
"parallel_execution": true,
"agents_completed_simultaneously": 4,
"execution_time_seconds": 12.8,
"billing_info": {
"total_cost": 0.052
"job_id": "swarms-S17nZFDesmLHxCRoeyF3NVYvPaXk",
"status": "success",
"swarm_name": "Market Research Concurrent",
"description": "Parallel market research across different sectors",
"swarm_type": "ConcurrentWorkflow",
"output": [
{
"role": "E-commerce Market Analyst",
"content": "To analyze market opportunities in the AI, healthcare, fintech, and e-commerce sectors, we can break down each sector's current trends, consumer behavior, and emerging platforms. Here's an overview of each sector with a focus on e-commerce....."
},
{
"role": "AI Market Analyst",
"content": "The artificial intelligence (AI) landscape presents numerous opportunities across various sectors, particularly in healthcare, fintech, and e-commerce. Here's a detailed analysis of each sector:\n\n### Healthcare....."
},
{
"role": "Healthcare Market Analyst",
"content": "As a Healthcare Market Analyst, I will focus on analyzing market opportunities within the healthcare sector, particularly in the realm of AI and digital health. The intersection of healthcare with fintech and e-commerce also presents unique opportunities. Here's an overview of key trends and growth areas:...."
},
{
"role": "Fintech Market Analyst",
"content": "Certainly! Let's break down the market opportunities in the fintech sector, focusing on financial technology trends, digital payment systems, blockchain opportunities, and regulatory developments:\n\n### 1. Financial Technology Trends....."
}
],
"number_of_agents": 4,
"service_tier": "standard",
"execution_time": 23.360230922698975,
"usage": {
"input_tokens": 35,
"output_tokens": 2787,
"total_tokens": 2822,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.04,
"input_token_cost": 0.000105,
"output_token_cost": 0.041805,
"token_counts": {
"total_input_tokens": 35,
"total_output_tokens": 2787,
"total_tokens": 2822
},
"num_agents": 4,
"service_tier": "standard",
"night_time_discount_applied": true
},
"total_cost": 0.08191,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 75
}
}
}
}
```

@ -23,172 +23,6 @@ Key features:
## API Usage
### Basic GroupChat Example
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Product Strategy Discussion",
"description": "Collaborative chat to develop product strategy",
"swarm_type": "GroupChat",
"task": "Discuss and develop a go-to-market strategy for a new AI-powered productivity tool targeting small businesses",
"agents": [
{
"agent_name": "Product Manager",
"description": "Leads product strategy and development",
"system_prompt": "You are a senior product manager. Focus on product positioning, features, user needs, and market fit. Ask probing questions and build on others ideas.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.6
},
{
"agent_name": "Marketing Strategist",
"description": "Develops marketing and positioning strategy",
"system_prompt": "You are a marketing strategist. Focus on target audience, messaging, channels, and competitive positioning. Contribute marketing insights to the discussion.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.7
},
{
"agent_name": "Sales Director",
"description": "Provides sales and customer perspective",
"system_prompt": "You are a sales director with small business experience. Focus on pricing, sales process, customer objections, and market adoption. Share practical sales insights.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.5
},
{
"agent_name": "UX Researcher",
"description": "Represents user experience and research insights",
"system_prompt": "You are a UX researcher specializing in small business tools. Focus on user behavior, usability, adoption barriers, and design considerations.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.4
}
],
"max_loops": 3
}'
```
=== "Python (requests)"
```python
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": "Product Strategy Discussion",
"description": "Collaborative chat to develop product strategy",
"swarm_type": "GroupChat",
"task": "Discuss and develop a go-to-market strategy for a new AI-powered productivity tool targeting small businesses",
"agents": [
{
"agent_name": "Product Manager",
"description": "Leads product strategy and development",
"system_prompt": "You are a senior product manager. Focus on product positioning, features, user needs, and market fit. Ask probing questions and build on others ideas.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.6
},
{
"agent_name": "Marketing Strategist",
"description": "Develops marketing and positioning strategy",
"system_prompt": "You are a marketing strategist. Focus on target audience, messaging, channels, and competitive positioning. Contribute marketing insights to the discussion.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.7
},
{
"agent_name": "Sales Director",
"description": "Provides sales and customer perspective",
"system_prompt": "You are a sales director with small business experience. Focus on pricing, sales process, customer objections, and market adoption. Share practical sales insights.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.5
},
{
"agent_name": "UX Researcher",
"description": "Represents user experience and research insights",
"system_prompt": "You are a UX researcher specializing in small business tools. Focus on user behavior, usability, adoption barriers, and design considerations.",
"model_name": "gpt-4o",
"max_loops": 3,
"temperature": 0.4
}
],
"max_loops": 3
}
response = requests.post(
f"{API_BASE_URL}/v1/swarm/completions",
headers=headers,
json=swarm_config
)
if response.status_code == 200:
result = response.json()
print("GroupChat swarm completed successfully!")
print(f"Cost: ${result['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
print(f"Chat discussion: {result['output']}")
else:
print(f"Error: {response.status_code} - {response.text}")
```
**Example Response**:
```json
{
"status": "success",
"swarm_name": "product-strategy-discussion",
"swarm_type": "GroupChat",
"task": "Discuss and develop a go-to-market strategy for a new AI-powered productivity tool targeting small businesses",
"output": {
"chat_transcript": [
{
"agent": "Product Manager",
"message": "Let's start by defining our target user. What specific pain points do small businesses have with productivity tools?"
},
{
"agent": "UX Researcher",
"message": "From our research, small businesses struggle with tool complexity and time to value. They need something that works immediately without extensive setup."
},
{
"agent": "Sales Director",
"message": "I agree. SMBs have limited time and resources. They typically abandon tools that require more than a week to see value. Pricing is also critical - they're very cost-conscious."
},
{
"agent": "Marketing Strategist",
"message": "This suggests we should focus on 'instant productivity gains' messaging. We could position against complex enterprise tools that overwhelm small teams."
}
],
"key_decisions": [
"Target: Small businesses with 5-50 employees",
"Positioning: Simple, immediate productivity gains",
"Pricing: Freemium model with low-cost paid tiers",
"GTM: Self-serve with strong onboarding"
],
"final_strategy": "Launch with freemium model targeting productivity-focused small businesses through content marketing and self-serve channels..."
},
"metadata": {
"conversation_rounds": 3,
"total_messages": 12,
"consensus_reached": true,
"execution_time_seconds": 38.7,
"billing_info": {
"total_cost": 0.095
}
}
}
```
## Best Practices

@ -23,201 +23,6 @@ Key features:
## API Usage
### Basic HierarchicalSwarm Example
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Software Development Hierarchy",
"description": "Hierarchical software development team with project manager oversight",
"swarm_type": "HierarchicalSwarm",
"task": "Design and plan a new mobile app for expense tracking targeting freelancers",
"agents": [
{
"agent_name": "Project Manager",
"description": "Oversees project planning and coordinates team efforts",
"system_prompt": "You are a senior project manager. Coordinate the team, break down tasks, ensure quality, and synthesize outputs. Delegate specific tasks to team members.",
"model_name": "gpt-4o",
"role": "manager",
"max_loops": 2,
"temperature": 0.4
},
{
"agent_name": "UX Designer",
"description": "Designs user experience and interface",
"system_prompt": "You are a UX designer specializing in mobile apps. Focus on user flows, wireframes, and interface design. Report findings to the project manager.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.6
},
{
"agent_name": "Technical Architect",
"description": "Designs technical architecture and system requirements",
"system_prompt": "You are a technical architect. Focus on system design, technology stack, database design, and technical requirements. Provide technical guidance.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Business Analyst",
"description": "Analyzes business requirements and market fit",
"system_prompt": "You are a business analyst. Focus on requirements gathering, market analysis, feature prioritization, and business logic.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.4
},
{
"agent_name": "QA Specialist",
"description": "Ensures quality and validates deliverables",
"system_prompt": "You are a QA specialist. Review all outputs for quality, completeness, and consistency. Identify gaps and suggest improvements.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.2
}
],
"max_loops": 2
}'
```
=== "Python (requests)"
```python
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": "Software Development Hierarchy",
"description": "Hierarchical software development team with project manager oversight",
"swarm_type": "HierarchicalSwarm",
"task": "Design and plan a new mobile app for expense tracking targeting freelancers",
"agents": [
{
"agent_name": "Project Manager",
"description": "Oversees project planning and coordinates team efforts",
"system_prompt": "You are a senior project manager. Coordinate the team, break down tasks, ensure quality, and synthesize outputs. Delegate specific tasks to team members.",
"model_name": "gpt-4o",
"role": "manager",
"max_loops": 2,
"temperature": 0.4
},
{
"agent_name": "UX Designer",
"description": "Designs user experience and interface",
"system_prompt": "You are a UX designer specializing in mobile apps. Focus on user flows, wireframes, and interface design. Report findings to the project manager.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.6
},
{
"agent_name": "Technical Architect",
"description": "Designs technical architecture and system requirements",
"system_prompt": "You are a technical architect. Focus on system design, technology stack, database design, and technical requirements. Provide technical guidance.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Business Analyst",
"description": "Analyzes business requirements and market fit",
"system_prompt": "You are a business analyst. Focus on requirements gathering, market analysis, feature prioritization, and business logic.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.4
},
{
"agent_name": "QA Specialist",
"description": "Ensures quality and validates deliverables",
"system_prompt": "You are a QA specialist. Review all outputs for quality, completeness, and consistency. Identify gaps and suggest improvements.",
"model_name": "gpt-4o",
"role": "worker",
"max_loops": 1,
"temperature": 0.2
}
],
"max_loops": 2
}
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 completed successfully!")
print(f"Cost: ${result['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
print(f"Project plan: {result['output']}")
else:
print(f"Error: {response.status_code} - {response.text}")
```
**Example Response**:
```json
{
"status": "success",
"swarm_name": "software-development-hierarchy",
"swarm_type": "HierarchicalSwarm",
"task": "Design and plan a new mobile app for expense tracking targeting freelancers",
"output": {
"project_overview": {
"manager_synthesis": "Comprehensive project plan for freelancer expense tracking app...",
"timeline": "16-week development cycle",
"key_deliverables": ["UX Design", "Technical Architecture", "Business Requirements", "QA Framework"]
},
"ux_design": {
"user_flows": "Streamlined expense entry and categorization flows...",
"wireframes": "Mobile-first design with dashboard and reporting views...",
"usability_considerations": "One-tap expense entry, photo receipt capture..."
},
"technical_architecture": {
"tech_stack": "React Native, Node.js, PostgreSQL, AWS",
"system_design": "Microservices architecture with offline capability...",
"security_requirements": "End-to-end encryption, secure authentication..."
},
"business_requirements": {
"target_market": "Freelancers and independent contractors",
"core_features": ["Expense tracking", "Receipt scanning", "Tax reporting"],
"monetization": "Freemium model with premium reporting features"
},
"qa_framework": {
"testing_strategy": "Automated testing for core functions...",
"quality_metrics": "Performance, usability, and security benchmarks...",
"validation_checkpoints": "Weekly reviews and milestone validations"
}
},
"metadata": {
"hierarchy_structure": {
"managers": ["Project Manager"],
"workers": ["UX Designer", "Technical Architect", "Business Analyst", "QA Specialist"]
},
"coordination_rounds": 2,
"task_delegation": "Manager coordinated 4 specialized work streams",
"execution_time_seconds": 52.4,
"billing_info": {
"total_cost": 0.128
}
}
}
```
## Configuration Options

@ -164,65 +164,74 @@ Key features:
**Example Response**:
```json
{
"status": "success",
"swarm_name": "investment-decision-voting",
"swarm_type": "MajorityVoting",
"task": "Evaluate whether to invest $1M in a renewable energy startup. Consider market potential, financial projections, team strength, and competitive landscape.",
"output": {
"individual_recommendations": [
{
"agent": "Growth Investor",
"recommendation": "INVEST",
"confidence": 0.8,
"reasoning": "Strong market growth potential in renewable energy sector, scalable technology platform"
},
{
"agent": "Financial Analyst",
"recommendation": "INVEST",
"confidence": 0.7,
"reasoning": "Solid financial projections, reasonable burn rate, clear path to profitability"
},
{
"agent": "Technical Due Diligence",
"recommendation": "INVEST",
"confidence": 0.75,
"reasoning": "Innovative technology with strong IP portfolio, experienced technical team"
},
{
"agent": "Market Analyst",
"recommendation": "WAIT",
"confidence": 0.6,
"reasoning": "Highly competitive market, regulatory uncertainties may impact timeline"
},
{
"agent": "Risk Assessor",
"recommendation": "INVEST",
"confidence": 0.65,
"reasoning": "Manageable risks with strong mitigation strategies, experienced leadership team"
}
"job_id": "swarms-1WFsSJU2KcvY11lxRMjdQNWFHArI",
"status": "success",
"swarm_name": "Investment Decision Voting",
"description": "Multiple financial experts vote on investment recommendations",
"swarm_type": "MajorityVoting",
"output": [
{
"role": "Financial Analyst",
"content": [
"To evaluate the potential investment in a renewable energy startup, we will assess the technology viability, intellectual property, product-market fit, and technical risks, along with the additional factors of market ....."
]
},
{
"role": "Technical Due Diligence",
"content": [
"To evaluate the potential investment in a renewable energy startup, we will analyze the relevant market dynamics, competitive landscape, regulatory environment, and market timing. Here's the breakdown of the assessment......."
]
},
{
"role": "Market Analyst",
"content": [
"To evaluate the potential investment in a renewable energy startup, let's break down the key factors:\n\n1. **Market Potential........"
]
},
{
"role": "Growth Investor",
"content": [
"To evaluate the potential investment in a renewable energy startup, we need to assess various risk factors and mitigation strategies across several key areas: market potential, financial projections, team strength, and competitive landscape.\n\n### 1. Market Potential\n**Risks:**\n- **Regulatory Changes................"
]
},
{
"role": "Risk Assessor",
"content": [
"To provide a comprehensive evaluation of whether to invest $1M in the renewable energy startup, let's break down the key areas.........."
]
},
{
"role": "Risk Assessor",
"content": "To evaluate the potential investment in a renewable energy startup, we need to assess various risk factors and mitigation strategies across several key areas....."
}
],
"consensus_decision": "INVEST",
"consensus_confidence": 0.72,
"consensus_reasoning": "4 out of 5 experts recommend investment with strong market potential and solid fundamentals, despite some market uncertainties"
},
"metadata": {
"vote_breakdown": {
"INVEST": 4,
"WAIT": 1,
"REJECT": 0
},
"vote_percentage": {
"INVEST": "80%",
"WAIT": "20%",
"REJECT": "0%"
},
"average_confidence": 0.70,
"consensus_threshold": "Simple majority (50%+)",
"execution_time_seconds": 25.8,
"billing_info": {
"total_cost": 0.063
"number_of_agents": 5,
"service_tier": "standard",
"execution_time": 61.74853563308716,
"usage": {
"input_tokens": 39,
"output_tokens": 8468,
"total_tokens": 8507,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.05,
"input_token_cost": 0.000117,
"output_token_cost": 0.12702,
"token_counts": {
"total_input_tokens": 39,
"total_output_tokens": 8468,
"total_tokens": 8507
},
"num_agents": 5,
"service_tier": "standard",
"night_time_discount_applied": false
},
"total_cost": 0.177137,
"discount_active": false,
"discount_type": "none",
"discount_percentage": 0
}
}
}
}
```

@ -23,215 +23,7 @@ Key features:
## API Usage
### Basic MALT Example
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Legal Document Analysis MALT",
"description": "Advanced linguistic analysis of legal documents using MALT framework",
"swarm_type": "MALT",
"task": "Perform comprehensive linguistic analysis of a complex legal contract including sentiment analysis, risk identification, clause categorization, and language complexity assessment",
"agents": [
{
"agent_name": "Syntactic Analyzer",
"description": "Analyzes sentence structure and grammar",
"system_prompt": "You are a syntactic analysis expert. Analyze sentence structure, grammatical patterns, and linguistic complexity in legal texts.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.2
},
{
"agent_name": "Semantic Analyzer",
"description": "Analyzes meaning and semantic relationships",
"system_prompt": "You are a semantic analysis expert. Extract meaning, identify semantic relationships, and analyze conceptual content in legal documents.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Pragmatic Analyzer",
"description": "Analyzes context and implied meanings",
"system_prompt": "You are a pragmatic analysis expert. Analyze contextual meaning, implied obligations, and pragmatic implications in legal language.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.4
},
{
"agent_name": "Discourse Analyzer",
"description": "Analyzes document structure and flow",
"system_prompt": "You are a discourse analysis expert. Analyze document structure, logical flow, and coherence in legal texts.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Risk Language Detector",
"description": "Identifies risk-related language patterns",
"system_prompt": "You are a legal risk language expert. Identify risk indicators, liability language, and potential legal concerns in contract language.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.2
}
],
"max_loops": 1
}'
```
=== "Python (requests)"
```python
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": "Legal Document Analysis MALT",
"description": "Advanced linguistic analysis of legal documents using MALT framework",
"swarm_type": "MALT",
"task": "Perform comprehensive linguistic analysis of a complex legal contract including sentiment analysis, risk identification, clause categorization, and language complexity assessment",
"agents": [
{
"agent_name": "Syntactic Analyzer",
"description": "Analyzes sentence structure and grammar",
"system_prompt": "You are a syntactic analysis expert. Analyze sentence structure, grammatical patterns, and linguistic complexity in legal texts.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.2
},
{
"agent_name": "Semantic Analyzer",
"description": "Analyzes meaning and semantic relationships",
"system_prompt": "You are a semantic analysis expert. Extract meaning, identify semantic relationships, and analyze conceptual content in legal documents.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Pragmatic Analyzer",
"description": "Analyzes context and implied meanings",
"system_prompt": "You are a pragmatic analysis expert. Analyze contextual meaning, implied obligations, and pragmatic implications in legal language.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.4
},
{
"agent_name": "Discourse Analyzer",
"description": "Analyzes document structure and flow",
"system_prompt": "You are a discourse analysis expert. Analyze document structure, logical flow, and coherence in legal texts.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Risk Language Detector",
"description": "Identifies risk-related language patterns",
"system_prompt": "You are a legal risk language expert. Identify risk indicators, liability language, and potential legal concerns in contract language.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.2
}
],
"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("MALT framework completed successfully!")
print(f"Linguistic analysis: {result['output']['linguistic_analysis']}")
print(f"Cost: ${result['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
else:
print(f"Error: {response.status_code} - {response.text}")
```
**Example Response**:
```json
{
"status": "success",
"swarm_name": "legal-document-analysis-malt",
"swarm_type": "MALT",
"task": "Perform comprehensive linguistic analysis of a complex legal contract including sentiment analysis, risk identification, clause categorization, and language complexity assessment",
"output": {
"linguistic_analysis": {
"syntactic_analysis": {
"complexity_score": 8.2,
"sentence_structure": "Predominantly complex and compound-complex sentences",
"grammatical_patterns": "Heavy use of passive voice, subordinate clauses, and technical terminology",
"readability": "Graduate level (16+ years of education required)"
},
"semantic_analysis": {
"key_concepts": ["liability", "indemnification", "force majeure", "intellectual property"],
"semantic_relationships": "Strong hierarchical concept relationships with clear definitional structures",
"conceptual_density": "High - 3.2 legal concepts per sentence average",
"ambiguity_indicators": ["potentially", "reasonable efforts", "material adverse effect"]
},
"pragmatic_analysis": {
"implied_obligations": [
"Good faith performance expected",
"Timely notice requirements implied",
"Mutual cooperation assumed"
],
"power_dynamics": "Balanced with slight advantage to service provider",
"speech_acts": "Predominantly commissives (commitments) and directives (obligations)"
},
"discourse_analysis": {
"document_structure": "Well-organized with clear section hierarchy",
"logical_flow": "Sequential with appropriate cross-references",
"coherence_score": 8.5,
"transition_patterns": "Formal legal transitions with clause numbering"
},
"risk_language": {
"high_risk_terms": ["unlimited liability", "personal guarantee", "joint and several"],
"risk_mitigation_language": ["subject to", "limited to", "except as provided"],
"liability_indicators": 23,
"risk_level": "Medium-High"
}
},
"comprehensive_summary": {
"language_complexity": "High complexity legal document requiring specialized knowledge",
"risk_assessment": "Medium-high risk with standard legal protections",
"readability_concerns": "Requires legal expertise for full comprehension",
"recommendations": [
"Consider plain language summary for key terms",
"Review unlimited liability clauses",
"Clarify ambiguous terms identified"
]
}
},
"metadata": {
"malt_framework": {
"linguistic_layers_analyzed": 5,
"language_processing_depth": "Advanced multi-layer analysis",
"specialized_nlp_operations": [
"Syntactic parsing",
"Semantic role labeling",
"Pragmatic inference",
"Discourse segmentation",
"Risk pattern recognition"
]
},
"execution_time_seconds": 35.7,
"billing_info": {
"total_cost": 0.089
}
}
}
```
## Best Practices

@ -147,29 +147,64 @@ Key features:
**Example Response**:
```json
{
"status": "success",
"swarm_name": "business-strategy-mixture",
"swarm_type": "MixtureOfAgents",
"task": "Develop a comprehensive market entry strategy for a new AI product in the healthcare sector",
"output": {
"market_analysis": "Detailed market research findings...",
"financial_assessment": "Financial projections and ROI analysis...",
"regulatory_compliance": "Regulatory requirements and pathways...",
"technology_strategy": "Technical implementation roadmap...",
"integrated_strategy": "Comprehensive market entry strategy combining all perspectives..."
},
"metadata": {
"agent_contributions": {
"Market Research Analyst": "Market size: $2.3B, Growth rate: 15% CAGR",
"Financial Analyst": "Break-even: 18 months, ROI: 35%",
"Regulatory Expert": "FDA pathway: 510(k), Timeline: 8-12 months",
"Technology Strategist": "MVP timeline: 6 months, Scalability: High"
},
"execution_time_seconds": 22.1,
"billing_info": {
"total_cost": 0.067
"job_id": "swarms-kBZaJg1uGTkRbLCAsGztL2jrp5Mj",
"status": "success",
"swarm_name": "Business Strategy Mixture",
"description": "Diverse team analyzing business strategy from multiple perspectives",
"swarm_type": "MixtureOfAgents",
"output": [
{
"role": "System",
"content": "Team Name: Business Strategy Mixture\nTeam Description: Diverse team analyzing business strategy from multiple perspectives\nThese are the agents in your team. Each agent has a specific role and expertise to contribute to the team's objectives.\nTotal Agents: 4\n\nBelow is a summary of your team members and their primary responsibilities:\n| Agent Name | Description |\n|------------|-------------|\n| Market Research Analyst | Analyzes market trends and opportunities |\n| Financial Analyst | Evaluates financial viability and projections |\n| Regulatory Expert | Analyzes compliance and regulatory requirements |\n| Technology Strategist | Evaluates technical feasibility and strategy |\n\nEach agent is designed to handle tasks within their area of expertise. Collaborate effectively by assigning tasks according to these roles."
},
{
"role": "Market Research Analyst",
"content": "To develop a comprehensive market entry strategy for a new AI product in the healthcare sector, we will leverage the expertise of each team member to cover all critical aspects of the strategy. Here's how each agent will contribute......."
},
{
"role": "Technology Strategist",
"content": "To develop a comprehensive market entry strategy for a new AI product in the healthcare sector, we'll need to collaborate effectively with the team, leveraging each member's expertise. Here's how each agent can contribute to the strategy, along with a focus on the technical requirements, implementation challenges, and scalability from the technology strategist's perspective....."
},
{
"role": "Financial Analyst",
"content": "Developing a comprehensive market entry strategy for a new AI product in the healthcare sector involves a multidisciplinary approach. Each agent in the Business Strategy Mixture team will play a crucial role in ensuring a successful market entry. Here's how the team can collaborate........"
},
{
"role": "Regulatory Expert",
"content": "To develop a comprehensive market entry strategy for a new AI product in the healthcare sector, we need to leverage the expertise of each agent in the Business Strategy Mixture team. Below is an outline of how each team member can contribute to this strategy......"
},
{
"role": "Aggregator Agent",
"content": "As the Aggregator Agent, I've observed and analyzed the responses from the Business Strategy Mixture team regarding the development of a comprehensive market entry strategy for a new AI product in the healthcare sector. Here's a summary of the key points ......"
}
],
"number_of_agents": 4,
"service_tier": "standard",
"execution_time": 30.230480670928955,
"usage": {
"input_tokens": 30,
"output_tokens": 3401,
"total_tokens": 3431,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.04,
"input_token_cost": 0.00009,
"output_token_cost": 0.051015,
"token_counts": {
"total_input_tokens": 30,
"total_output_tokens": 3401,
"total_tokens": 3431
},
"num_agents": 4,
"service_tier": "standard",
"night_time_discount_applied": true
},
"total_cost": 0.091105,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 75
}
}
}
}
```

@ -148,65 +148,52 @@ Key features:
**Example Response**:
```json
{
"status": "success",
"swarm_name": "customer-support-router",
"swarm_type": "MultiAgentRouter",
"task": "Handle multiple customer inquiries: 1) Billing question about overcharge, 2) Technical issue with mobile app login, 3) Product recommendation for enterprise client, 4) Return policy question",
"output": {
"inquiry_1_billing": {
"routed_to": "Billing Specialist",
"response": "I understand your concern about the overcharge. Let me review your account and identify the issue. I can see the duplicate charge and will process a refund within 3-5 business days...",
"resolution_status": "Resolved - Refund processed"
},
"inquiry_2_technical": {
"routed_to": "Technical Support",
"response": "Let's troubleshoot the mobile app login issue. Please try these steps: 1) Clear app cache, 2) Update to latest version, 3) Reset password if needed...",
"resolution_status": "In Progress - Troubleshooting steps provided"
},
"inquiry_3_sales": {
"routed_to": "Sales Consultant",
"response": "For enterprise clients, I recommend our Professional tier with advanced analytics, dedicated support, and custom integrations. This includes...",
"resolution_status": "Proposal sent - Follow-up scheduled"
},
"inquiry_4_policy": {
"routed_to": "Policy Advisor",
"response": "Our return policy allows returns within 30 days of purchase for full refund. Items must be in original condition. Here's the complete process...",
"resolution_status": "Information provided - Customer satisfied"
}
},
"metadata": {
"routing_decisions": [
{
"inquiry": "Billing question about overcharge",
"routed_to": "Billing Specialist",
"confidence": 0.95,
"reasoning": "Billing-related inquiry requires specialized financial expertise"
},
{
"inquiry": "Technical issue with mobile app login",
"routed_to": "Technical Support",
"confidence": 0.98,
"reasoning": "Technical troubleshooting requires technical specialist"
},
{
"inquiry": "Product recommendation for enterprise client",
"routed_to": "Sales Consultant",
"confidence": 0.92,
"reasoning": "Enterprise sales requires specialized sales expertise"
},
{
"inquiry": "Return policy question",
"routed_to": "Policy Advisor",
"confidence": 0.97,
"reasoning": "Policy questions require policy specialist knowledge"
}
"job_id": "swarms-OvOZHubprE3thzLmRdNBZAxA6om4",
"status": "success",
"swarm_name": "Customer Support Router",
"description": "Route customer inquiries to specialized support agents",
"swarm_type": "MultiAgentRouter",
"output": [
{
"role": "user",
"content": "Handle multiple customer inquiries: 1) Billing question about overcharge, 2) Technical issue with mobile app login, 3) Product recommendation for enterprise client, 4) Return policy question"
},
{
"role": "Agent Router",
"content": "selected_agent='Billing Specialist' reasoning='The task involves multiple inquiries, but the first one is about a billing question regarding an overcharge. Billing issues often require immediate attention to ensure customer satisfaction and prevent further complications. Therefore, the Billing Specialist is the most appropriate agent to handle this task. They can address the billing question directly and potentially coordinate with other agents for the remaining inquiries.' modified_task='Billing question about overcharge'"
},
{
"role": "Billing Specialist",
"content": "Of course, I'd be happy to help you with your billing question regarding an overcharge. Could you please provide me with more details about the charge in question, such as the date it occurred and the amount? This information will help me look into your account and resolve the issue as quickly as possible."
}
],
"routing_efficiency": "100% - All inquiries routed to optimal agents",
"execution_time_seconds": 16.4,
"billing_info": {
"total_cost": 0.042
"number_of_agents": 4,
"service_tier": "standard",
"execution_time": 7.800086975097656,
"usage": {
"input_tokens": 28,
"output_tokens": 221,
"total_tokens": 249,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.04,
"input_token_cost": 0.000084,
"output_token_cost": 0.003315,
"token_counts": {
"total_input_tokens": 28,
"total_output_tokens": 221,
"total_tokens": 249
},
"num_agents": 4,
"service_tier": "standard",
"night_time_discount_applied": true
},
"total_cost": 0.043399,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 75
}
}
}
}
```

@ -147,34 +147,56 @@ Key features:
**Example Response**:
```json
{
"status": "success",
"swarm_name": "content-creation-pipeline",
"swarm_type": "SequentialWorkflow",
"task": "Create a comprehensive blog post about the future of renewable energy",
"output": {
"research_findings": "Comprehensive research on renewable energy trends...",
"draft_content": "Initial blog post draft...",
"edited_content": "Polished and refined article...",
"final_seo_optimized": "SEO-optimized final blog post ready for publication..."
},
"metadata": {
"execution_sequence": [
"Research Specialist",
"Content Writer",
"Editor",
"SEO Optimizer"
"job_id": "swarms-pbM8wqUwxq8afGeROV2A4xAcncd1",
"status": "success",
"swarm_name": "Content Creation Pipeline",
"description": "Sequential content creation from research to final output",
"swarm_type": "SequentialWorkflow",
"output": [
{
"role": "Research Specialist",
"content": "\"**Title: The Future of Renewable Energy: Charting a Sustainable Path Forward**\n\nAs we navigate the complexities of the 21st century, the transition to renewable energy stands out as a critical endeavor to ensure a sustainable future......"
},
{
"role": "SEO Optimizer",
"content": "\"**Title: The Future of Renewable Energy: Charting a Sustainable Path Forward**\n\nThe transition to renewable energy is crucial as we face the challenges of the 21st century, including climate change and dwindling fossil fuel resources......."
},
{
"role": "Editor",
"content": "\"**Title: The Future of Renewable Energy: Charting a Sustainable Path Forward**\n\nAs we confront the challenges of the 21st century, transitioning to renewable energy is essential for a sustainable future. With climate change concerns escalating and fossil fuel reserves depleting, renewable energy is not just an option but a necessity...."
},
{
"role": "Content Writer",
"content": "\"**Title: The Future of Renewable Energy: Charting a Sustainable Path Forward**\n\nAs we face the multifaceted challenges of the 21st century, transitioning to renewable energy emerges as not just an option but an essential step toward a sustainable future...."
}
],
"step_outputs": {
"step_1": "Research findings and data",
"step_2": "Draft article content",
"step_3": "Edited and refined content",
"step_4": "SEO-optimized final version"
},
"execution_time_seconds": 45.3,
"billing_info": {
"total_cost": 0.089
"number_of_agents": 4,
"service_tier": "standard",
"execution_time": 72.23084282875061,
"usage": {
"input_tokens": 28,
"output_tokens": 3012,
"total_tokens": 3040,
"billing_info": {
"cost_breakdown": {
"agent_cost": 0.04,
"input_token_cost": 0.000084,
"output_token_cost": 0.04518,
"token_counts": {
"total_input_tokens": 28,
"total_output_tokens": 3012,
"total_tokens": 3040
},
"num_agents": 4,
"service_tier": "standard",
"night_time_discount_applied": true
},
"total_cost": 0.085264,
"discount_active": true,
"discount_type": "night_time",
"discount_percentage": 75
}
}
}
}
```

@ -25,198 +25,7 @@ Key features:
### Basic SpreadSheetSwarm Example
=== "Shell (curl)"
```bash
curl -X POST "https://api.swarms.world/v1/swarm/completions" \
-H "x-api-key: $SWARMS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Financial Analysis Spreadsheet",
"description": "Systematic financial data analysis using spreadsheet structure",
"swarm_type": "SpreadSheetSwarm",
"task": "Analyze quarterly financial performance data for a retail company with multiple product lines and create comprehensive insights",
"agents": [
{
"agent_name": "Data Validator",
"description": "Validates and cleans financial data",
"system_prompt": "You are a data validation specialist. Clean, validate, and structure financial data ensuring accuracy and consistency.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.2
},
{
"agent_name": "Revenue Analyst",
"description": "Analyzes revenue trends and patterns",
"system_prompt": "You are a revenue analyst. Focus on revenue trends, growth patterns, and seasonal variations across product lines.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Cost Analyst",
"description": "Analyzes cost structures and margins",
"system_prompt": "You are a cost analyst. Examine cost structures, margin analysis, and expense categorization.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Performance Calculator",
"description": "Calculates KPIs and financial metrics",
"system_prompt": "You are a financial metrics specialist. Calculate KPIs, ratios, and performance indicators from the analyzed data.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.1
},
{
"agent_name": "Report Generator",
"description": "Creates structured financial reports",
"system_prompt": "You are a report generator. Create comprehensive, well-structured financial reports with insights and recommendations.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.4
}
],
"max_loops": 1
}'
```
=== "Python (requests)"
```python
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": "Financial Analysis Spreadsheet",
"description": "Systematic financial data analysis using spreadsheet structure",
"swarm_type": "SpreadSheetSwarm",
"task": "Analyze quarterly financial performance data for a retail company with multiple product lines and create comprehensive insights",
"agents": [
{
"agent_name": "Data Validator",
"description": "Validates and cleans financial data",
"system_prompt": "You are a data validation specialist. Clean, validate, and structure financial data ensuring accuracy and consistency.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.2
},
{
"agent_name": "Revenue Analyst",
"description": "Analyzes revenue trends and patterns",
"system_prompt": "You are a revenue analyst. Focus on revenue trends, growth patterns, and seasonal variations across product lines.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Cost Analyst",
"description": "Analyzes cost structures and margins",
"system_prompt": "You are a cost analyst. Examine cost structures, margin analysis, and expense categorization.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.3
},
{
"agent_name": "Performance Calculator",
"description": "Calculates KPIs and financial metrics",
"system_prompt": "You are a financial metrics specialist. Calculate KPIs, ratios, and performance indicators from the analyzed data.",
"model_name": "gpt-4o",
"max_loops": 1,
"temperature": 0.1
},
{
"agent_name": "Report Generator",
"description": "Creates structured financial reports",
"system_prompt": "You are a report generator. Create comprehensive, well-structured financial reports with insights and recommendations.",
"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("SpreadSheetSwarm completed successfully!")
print(f"Cost: ${result['metadata']['billing_info']['total_cost']}")
print(f"Execution time: {result['metadata']['execution_time_seconds']} seconds")
print(f"Structured analysis: {result['output']}")
else:
print(f"Error: {response.status_code} - {response.text}")
```
**Example Response**:
```json
{
"status": "success",
"swarm_name": "financial-analysis-spreadsheet",
"swarm_type": "SpreadSheetSwarm",
"task": "Analyze quarterly financial performance data for a retail company with multiple product lines and create comprehensive insights",
"output": {
"data_validation": {
"data_quality": "95% accuracy after cleaning",
"missing_values": "Identified and filled 3% missing entries",
"data_structure": "Standardized format across all product lines"
},
"revenue_analysis": {
"q4_revenue": "$2.4M total revenue",
"growth_rate": "12% quarter-over-quarter growth",
"top_performers": ["Product Line A: +18%", "Product Line C: +15%"],
"seasonal_trends": "Strong holiday season performance"
},
"cost_analysis": {
"total_costs": "$1.8M operational costs",
"cost_breakdown": "60% COGS, 25% Marketing, 15% Operations",
"margin_analysis": "25% gross margin, 15% net margin",
"cost_optimization": "Identified 8% potential savings in supply chain"
},
"performance_metrics": {
"roi": "22% return on investment",
"customer_acquisition_cost": "$45 per customer",
"lifetime_value": "$320 average CLV",
"inventory_turnover": "6.2x annual turnover"
},
"comprehensive_report": {
"executive_summary": "Strong Q4 performance with 12% growth...",
"recommendations": ["Expand Product Line A", "Optimize supply chain", "Increase marketing for underperformers"],
"forecast": "Projected 15% growth for Q1 based on trends"
}
},
"metadata": {
"processing_structure": {
"rows_processed": 1250,
"columns_analyzed": 18,
"calculations_performed": 47
},
"data_pipeline": [
"Data Validation",
"Revenue Analysis",
"Cost Analysis",
"Performance Calculation",
"Report Generation"
],
"execution_time_seconds": 34.2,
"billing_info": {
"total_cost": 0.078
}
}
}
```
## Best Practices

@ -6,16 +6,16 @@ Each multi-agent architecture type is designed for specific use cases and can be
|----------------------|------------------------------------------------------------------------------|------------|
| AgentRearrange | Dynamically reorganizes agents to optimize task performance and efficiency. Useful when agent effectiveness depends on their sequence or arrangement. | [Learn More](agent_rearrange.md) |
| MixtureOfAgents | Builds diverse teams of specialized agents, each contributing unique skills to solve complex problems. Excels at tasks requiring multiple types of expertise. | [Learn More](mixture_of_agents.md) |
| SpreadSheetSwarm | Provides a structured approach to data management and operations, ideal for tasks involving data analysis, transformation, and systematic processing in a spreadsheet-like structure. | [Learn More](spreadsheet_swarm.md) |
<!-- | SpreadSheetSwarm | Provides a structured approach to data management and operations, ideal for tasks involving data analysis, transformation, and systematic processing in a spreadsheet-like structure. | [Learn More](spreadsheet_swarm.md) | -->
| SequentialWorkflow | Executes tasks in a strict, predefined order. Perfect for workflows where each step depends on the completion of the previous one. | [Learn More](sequential_workflow.md) |
| ConcurrentWorkflow | Runs independent tasks in parallel, significantly reducing processing time for complex operations. Ideal for tasks that can be processed simultaneously. | [Learn More](concurrent_workflow.md) |
| GroupChat | Enables dynamic collaboration between agents through a chat-based interface, facilitating real-time information sharing and decision-making. | [Learn More](group_chat.md) |
<!-- | GroupChat | Enables dynamic collaboration between agents through a chat-based interface, facilitating real-time information sharing and decision-making. | [Learn More](group_chat.md) | -->
| MultiAgentRouter | Acts as an intelligent task dispatcher, distributing work across agents based on their capabilities and current workload. | [Learn More](multi_agent_router.md) |
| AutoSwarmBuilder | Automatically configures agent architectures based on task requirements and performance metrics, simplifying swarm creation. | [Learn More](auto_swarm_builder.md) |
| HierarchicalSwarm | Implements a structured, multi-level approach to task management, with clear lines of authority and delegation. | [Learn More](hierarchical_swarm.md) |
| Auto | Intelligently selects the most effective swarm architecture for a given task based on context. | [Learn More](auto.md) |
<!-- | AutoSwarmBuilder | Automatically configures agent architectures based on task requirements and performance metrics, simplifying swarm creation. | [Learn More](auto_swarm_builder.md) |
| HierarchicalSwarm | Implements a structured, multi-level approach to task management, with clear lines of authority and delegation. | [Learn More](hierarchical_swarm.md) | -->
<!-- | Auto | Intelligently selects the most effective swarm architecture for a given task based on context. | [Learn More](auto.md) | -->
| MajorityVoting | Implements robust decision-making through consensus, ideal for tasks requiring collective intelligence or verification. | [Learn More](majority_voting.md) |
| MALT | Specialized framework for language-based tasks, optimizing agent collaboration for complex language processing operations. | [Learn More](malt.md) |
<!-- | MALT | Specialized framework for language-based tasks, optimizing agent collaboration for complex language processing operations. | [Learn More](malt.md) | -->
# Learn More

Loading…
Cancel
Save