Swarm Intelligence
Multi-agent coordination with 5 execution strategies and AI-powered coordination.
Overviewβ
Swarm Intelligence enables multiple specialized agents to work together as a collective, making decisions through coordination and emergent behaviors.
Swarm Strategiesβ
- PARALLEL - Execute all agents simultaneously (best for independent analyses)
- SEQUENTIAL - Execute agents in sequence, passing results forward (best for pipelines)
- CONSENSUS - Build consensus through multi-round discussion (best for decision-making)
- COMPETITION - Select best result from competing agents (best for creative tasks)
- HIERARCHICAL - Hierarchical delegation with levels (best for complex tasks)
Creating a Swarmβ
Basic Swarmβ
val swarm = buildSwarmAgent {
name = "Research Swarm"
description = "Multi-agent research and analysis"
// Add member agents
quickSwarm {
researchAgent("researcher", "Lead Researcher")
analysisAgent("analyst", "Data Analyst")
specialist("expert", "Domain Expert", "Expert analysis")
}
// Configure behavior
config {
debug(true)
timeout(45000)
maxOperations(5)
}
// Set execution strategy
defaultStrategy(SwarmStrategyType.PARALLEL)
}
// Execute
val result = swarm.processComm(Comm(
content = "Analyze the impact of AI on healthcare",
from = "user",
type = CommType.TEXT
))
AI-Powered Coordinatorβ
Use an LLM to make intelligent coordination decisions:
// Create LLM coordinator agent
val llmCoordinator = buildAgent {
name = "GPT-4 Coordinator"
description = "Meta-coordination agent"
// Configure your GPT-4 or Claude agent here
}
// Create AI-powered swarm
val aiSwarm = buildSwarmAgent {
name = "AI Research Swarm"
// Use AI for intelligent coordination
aiCoordinator(llmCoordinator)
quickSwarm {
researchAgent("researcher")
analysisAgent("analyst")
specialist("expert", "Expert", "analysis")
}
config {
debug(true)
timeout(60000)
}
}
The AI coordinator will:
- Analyze tasks and select optimal strategies
- Intelligently aggregate agent results
- Build sophisticated consensus
- Select best results with reasoning
Quick Swarm Creationβ
Pre-configured swarm templates:
// Research swarm
val research = researchSwarm(
name = "Research Team",
debugEnabled = true
)
// Creative swarm
val creative = creativeSwarm(
name = "Creative Team"
)
// Decision-making swarm
val decision = decisionSwarm(
name = "Decision Team"
)
// AI powerhouse (with real API keys)
val powerhouse = aiPowerhouseSwarm(
name = "AI Powerhouse",
claudeApiKey = System.getenv("CLAUDE_API_KEY"),
gptApiKey = System.getenv("OPENAI_API_KEY")
)
Strategy Examplesβ
Parallel Executionβ
val parallelSwarm = buildSwarmAgent {
name = "Parallel Analysis Swarm"
defaultStrategy(SwarmStrategyType.PARALLEL)
quickSwarm {
analysisAgent("agent1")
analysisAgent("agent2")
analysisAgent("agent3")
}
}
// All agents execute simultaneously
val result = parallelSwarm.processComm(comm)
Sequential Pipelineβ
val pipelineSwarm = buildSwarmAgent {
name = "Processing Pipeline"
defaultStrategy(SwarmStrategyType.SEQUENTIAL)
quickSwarm {
specialist("extractor", "Extractor", "Extract data")
specialist("cleaner", "Cleaner", "Clean data")
specialist("analyzer", "Analyzer", "Analyze data")
}
}
// Results pass through each agent
val result = pipelineSwarm.processComm(comm)
Consensus Buildingβ
val consensusSwarm = buildSwarmAgent {
name = "Consensus Swarm"
defaultStrategy(SwarmStrategyType.CONSENSUS)
quickSwarm {
researchAgent("researcher1")
researchAgent("researcher2")
specialist("expert", "Expert", "expert view")
}
config {
timeout(60000) // Consensus takes time
}
}
// Multi-round discussion to reach agreement
val result = consensusSwarm.processComm(comm)
Coordinator Typesβ
Smart Coordinator (Default)β
Intelligent coordination with task classification:
buildSwarmAgent {
coordinator(CoordinatorType.SMART) // Default
}
Simple Coordinatorβ
Lightweight coordination:
buildSwarmAgent {
coordinator(CoordinatorType.SIMPLE)
}
AI-Powered Coordinatorβ
LLM-enhanced coordination:
buildSwarmAgent {
coordinator(CoordinatorType.AI_POWERED)
llmCoordinator(myLLMAgent)
}
Swarm Toolsβ
Add custom tools that all swarm members can use:
Inline Tool Definitionβ
val swarm = buildSwarmAgent {
name = "Tool-Enabled Swarm"
swarmTools {
// Simple inline tool
tool("calculate", "Calculator tool") {
parameter("a", "number", "First number", required = true)
parameter("b", "number", "Second number", required = true)
parameter("operation", "string", "Operation", required = true)
execute(fun(params: Map<String, Any>): String {
val a = (params["a"] as Number).toDouble()
val b = (params["b"] as Number).toDouble()
val op = params["operation"] as String
return when (op) {
"+" -> (a + b).toString()
"-" -> (a - b).toString()
"*" -> (a * b).toString()
"/" -> (a / b).toString()
else -> "Unknown operation"
}
})
}
}
quickSwarm {
specialist("agent1", "Agent 1", "math")
specialist("agent2", "Agent 2", "analysis")
}
}
Adding Pre-built Toolsβ
swarmTools {
// Add existing tools
tool(myExistingTool)
tools(tool1, tool2, tool3)
}
Coordination Toolsβ
Spice provides built-in coordination tools:
swarmTools {
// AI-powered consensus building
aiConsensus(scoringAgent = myLLM)
// Conflict resolution
conflictResolver()
// Quality assessment
qualityAssessor(scoringAgent = myLLM)
// Result aggregation
resultAggregator()
// Strategy optimization
strategyOptimizer()
}
Benefits:
- Tools are shared across all swarm members
- Automatic parameter validation
- Deduplication by tool name
- Error handling built-in
Observabilityβ
Track swarm performance:
val swarm = buildSwarmAgent {
name = "Observable Swarm"
quickSwarm {
val agent1 = buildAgent { ... }.traced()
val agent2 = buildAgent { ... }.traced()
addAgent("agent1", agent1)
addAgent("agent2", agent2)
}
config {
debug(true)
}
}
// View traces in Jaeger
// Track metrics in Grafana
Best Practicesβ
- Choose the right strategy for your task
- Use AI coordinator for complex decision-making
- Enable tracing for production debugging
- Set appropriate timeouts for your use case
- Monitor costs when using multiple LLM agents
- Start with PARALLEL for independent tasks
- Use SEQUENTIAL for pipelines
- Use CONSENSUS for decisions
- Use COMPETITION for creativity