What Is Swarm Intelligence? From Ant Colonies to LLM Agent Swarms
Swarm intelligence explained: stigmergy, boids, ant colony and particle swarm optimization, what LLM agent swarms borrow from them, plus Swarms API code.
Swarm intelligence explained: stigmergy, boids, ant colony and particle swarm optimization, what LLM agent swarms borrow from them, plus Swarms API code.

Swarm intelligence is the problem-solving behavior that appears when many simple agents follow local rules and no central controller tells any of them what to do. An ant colony finds a short route to food, a flock turns as one body, termites build a mound, and no single insect or bird holds the plan. Computer scientists have been copying these mechanisms since the late 1980s, and the vocabulary has now reached AI: a group of cooperating LLM agents gets called an AI swarm or an agent swarm.
This guide covers where the idea came from, the four principles behind it, the three classic algorithms (boids, ant colony optimization and particle swarm optimization), and how much of that carries over to LLM agent swarms. Some of it carries over well and some of it breaks, and we will be specific about which is which. It ends with runnable code that builds a voting swarm on the Swarms API.
If you are new to agents, what is an agent and what is a multi-agent system are shorter introductions.
The term comes from robotics. Gerardo Beni and Jing Wang introduced "swarm intelligence" in 1989, in a paper on cellular robotic systems presented at a NATO workshop on robots and biological systems (Beni and Wang, published in the 1993 proceedings). Their subject was groups of simple robots that produce ordered behavior together. The word has since widened to cover any decentralized, self-organized system, natural or artificial, where the useful behavior belongs to the group.
A working definition has three parts:
Guy Theraulaz and Eric Bonabeau state the puzzle well in their history of stigmergy: in an insect society, "individuals work as if they were alone while their collective activities appear to be coordinated." Explaining that observation is what the field is about.
No ant in a colony holds a map of the foraging trails, and no starling directs the flock. Control is spread across every member, so losing any one of them changes little. That is where natural swarms get their fault tolerance: there is no single point of failure because there is no single point of control.
Each agent follows a short list of rules that refer only to what it can sense nearby. Reynolds' boids, covered below, need three.
The interesting behavior exists only at the level of the group. Shortest paths, flock shapes and nest structure come out of the interactions, and no individual computes them. Small changes to the local rules can produce large changes in what emerges, which is why swarm systems are easy to describe and hard to predict.
Pierre-Paul Grassé coined "stigmergy" in 1959 while studying how termites rebuild their nests (Grassé, Insectes Sociaux, 1959). His observation was that the workers coordinate through the thing they are building. A partly built structure stimulates more building at that spot, so the work in progress tells the next worker what to do.
Ant trails are the best-known case. Ants deposit pheromone as they walk and prefer directions that carry more of it, so a path that more ants use becomes more attractive still. Dorigo's group at IRIDIA describes how this positive feedback lets a colony find the shorter way around an obstacle: ants that happen to take the shorter side rebuild the trail faster, pheromone accumulates there sooner, and soon nearly all the traffic follows it.
Keep stigmergy in mind. It is the principle that maps most directly onto how LLM agents share work today.
Craig Reynolds built his boids model in 1986 and published it at SIGGRAPH 1987 as "Flocks, Herds, and Schools: A Distributed Behavioral Model". Each simulated bird steers by three rules, quoted from Reynolds' own page:
Nothing in those rules mentions a flock. Flocking emerges. Boids came out of computer graphics and solves no optimization problem, but it remains the cleanest demonstration that three local rules are enough for convincing group behavior.
Marco Dorigo turned pheromone trails into an optimization method. The first system, Ant System, appeared in his 1992 PhD thesis at the Politecnico di Milano (IRIDIA), and the journal version followed in 1996 (Dorigo, Maniezzo and Colorni). On the traveling salesman problem it works like this (Scholarpedia):
Evaporation matters as much as deposit. The Scholarpedia article calls it "a useful form of forgetting": without it, the first decent tour would lock in and the colony would stop exploring.
James Kennedy and Russell Eberhart introduced particle swarm optimization at the 1995 IEEE International Conference on Neural Networks. Its roots are in flocking simulations, including Reynolds' work, and in social psychology (Dorigo et al., Scholarpedia). Each particle is a candidate solution with a position and a velocity. At every step its velocity is pulled toward two points: the best position it has found itself, and the best position found among its neighbors. Which particles count as neighbors (all of them, or only the two next to it on a ring) is set by the population topology, so a good position either reaches the whole swarm at once or spreads step by step from neighbor to neighbor.
| Algorithm | Introduced | Agent | Local rule | Shared signal | What emerges |
|---|---|---|---|---|---|
| Boids | 1987 | Simulated bird | Separation, alignment, cohesion | Neighbors' positions and headings | Flocking |
| Ant colony optimization | 1992 | Artificial ant | Choose edges biased by pheromone | Pheromone on graph edges | Short paths and tours |
| Particle swarm optimization | 1995 | Particle | Move toward own best and neighbors' best | Best positions among neighbors | Convergence on good regions |
An LLM agent swarm is a group of language model agents that work on one task and combine their outputs through a defined coordination pattern. Each agent has its own system prompt, its own model and its own view of the task. The pattern decides what each agent sees, who goes when, and how the outputs merge.
Several research results give the swarm intuition some grounding:
What they share with an ant colony is the shape of the computation: many attempts in parallel, then a step that combines them and amplifies what most attempts agree on. Independent errors tend to cancel out, while agreement accumulates. Multi-agent collaboration patterns compares debate, voting, mixture of agents and councils in detail, and what is collective superintelligence, with its companion essay on why CSI will surpass AGI and ASI, makes the larger argument about where collective systems lead.
The analogy is useful, and it is also loose. Here is the comparison side by side.
| Classic swarm | LLM agent swarm | |
|---|---|---|
| Number of agents | Large: a colony, a flock, a population of particles | Usually a handful |
| Agent capability | Very simple, fixed rules | Each agent is a capable general model |
| Communication | Local: neighbors or the environment | Usually global: a shared transcript or a coordinator |
| Control | None | Often a director, router or aggregator agent |
| Source of diversity | Random noise and position | Must be designed: prompts, models, temperature |
| Cost per agent | Negligible | Every agent is a billed model call |
| Error independence | High | Low when every agent runs the same model and prompt |
Three parts of the analogy hold up well:
The Swarms API exposes 14 architectures through the swarm_type field of POST /v1/swarm/completions (full list). Sorted by how control is distributed, they fall into three groups.
swarm_type | How agents coordinate | Swarm principle it resembles | Central element |
|---|---|---|---|
| ConcurrentWorkflow | Every agent gets the same task in parallel and works independently | Independent local decisions | None; you aggregate |
| MajorityVoting | Independent answers, then a majority decision | Independent decisions plus aggregation | A consensus agent tallies the votes |
| MixtureOfAgents | Specialists answer in parallel, then an aggregator synthesizes | Diversity plus aggregation | An internal aggregator agent |
| GroupChat | Agents speak in turn into one shared transcript | Stigmergy through a shared medium | None beyond turn-taking |
| RoundRobin | Fixed rotation, each agent reads the full history | Stigmergy with a fixed schedule | The schedule itself |
| PlannerWorkerSwarm | Workers claim sub-tasks from a shared queue and never talk to each other | Stigmergy in the execution phase | A planner and a judge |
| HierarchicalSwarm | A director decomposes the task, delegates and reviews | Hierarchy | A director agent |
| MultiAgentRouter | A router sends the task to the best-suited agent or agents | Dispatch | A router agent |
A few details from the docs matter for this mapping. In MajorityVoting the agents decide independently and in parallel, then a separate Consensus-Agent tallies the votes and writes the verdict. That agent always runs gpt-5.4, and the docs note it cannot be changed through the request. MixtureOfAgents adds an internal aggregator that is not part of your agents list. In PlannerWorkerSwarm, workers only interact with the queue, which is about as close to Grassé's termites as an LLM system gets, but a planner writes the queue and a judge decides whether to run another cycle. HierarchicalSwarm creates its director automatically, and you tune it with director_model_name and director_settings.
These groups describe structure and say nothing about quality. A hierarchy is the better choice for many real tasks. Swarm architectures explained walks through all 14 with guidance on when to pick each, and what is multi-agent orchestration covers the state and failure handling that sits around them.
The first example is a voting swarm: three reviewers judge the same database migration independently, and the majority decides. It mirrors the ant colony in three ways. Each agent decides alone, each follows one simple output rule, and the result comes from aggregating local decisions. To reduce correlated errors, each reviewer runs a different model and looks at a different risk.
Get an API key from the Swarms platform, then install the dependencies and set the key:
pip install aiohttp python-dotenv
export SWARMS_API_KEY="your-api-key"import asyncio
import os
import aiohttp
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ["SWARMS_API_KEY"]
BASE_URL = "https://api.swarms.world"
HEADERS = {"x-api-key": API_KEY, "Content-Type": "application/json"}
MIGRATION = """
ALTER TABLE orders ADD COLUMN discount_code TEXT;
CREATE INDEX idx_orders_discount_code ON orders (discount_code);
UPDATE orders SET discount_code = 'NONE' WHERE discount_code IS NULL;
"""
RULES = (
"Work alone and judge only from the migration text. "
"Your first line must be exactly 'VOTE: SAFE' or 'VOTE: UNSAFE'. "
"Then give at most three short reasons."
)
def reviewer(name: str, focus: str, model: str) -> dict:
return {
"agent_name": name,
"description": f"Reviews database migrations for {focus}",
"system_prompt": f"You are a PostgreSQL reviewer focused on {focus}. {RULES}",
"model_name": model,
"max_loops": 1,
"max_tokens": 2048,
"temperature": 0.3,
}
async def main() -> None:
payload = {
"name": "Migration Safety Vote",
"description": "Independent reviewers vote and the majority decides",
"swarm_type": "MajorityVoting",
"task": (
"Is this migration safe to run on a large, busy production `orders` table "
"during business hours?\n" + MIGRATION
),
"agents": [
reviewer("Locking Reviewer", "table locks and blocked writes", "gpt-5.4"),
reviewer("Load Reviewer", "I/O load, runtime and replication lag", "claude-sonnet-5"),
reviewer("Rollback Reviewer", "reversibility and partial failure", "gpt-5.4-mini"),
],
"max_loops": 1,
}
# Multi-agent runs can take minutes, so give the whole request room.
timeout = aiohttp.ClientTimeout(total=600)
async with aiohttp.ClientSession(headers=HEADERS, timeout=timeout) as session:
async with session.post(f"{BASE_URL}/v1/swarm/completions", json=payload) as resp:
resp.raise_for_status()
result = await resp.json()
for turn in result["output"]:
if turn["role"].lower() == "user":
continue # the echoed task
content = turn["content"]
if isinstance(content, list):
content = " ".join(str(part) for part in content)
print(f"\n--- {turn['role']}")
print(str(content)[:600])
billing = result.get("usage", {}).get("billing_info", {})
print("\nAgents:", result["number_of_agents"], "| seconds:", result["execution_time"])
print("Cost (USD):", billing.get("total_cost"))
asyncio.run(main())Example output (abridged; the wording and votes will differ from run to run, and the timing and cost lines are omitted):
--- Locking Reviewer
VOTE: UNSAFE
1. CREATE INDEX without CONCURRENTLY blocks writes to orders until the build finishes.
2. The UPDATE rewrites every existing row in a single transaction.
--- Load Reviewer
VOTE: UNSAFE
1. Backfilling every row in one statement produces a large burst of I/O and WAL.
2. Replicas can fall behind while it runs.
--- Rollback Reviewer
VOTE: SAFE
1. Each step can be reversed with DROP INDEX and DROP COLUMN.
--- Consensus-Agent
FINAL VERDICT: UNSAFE (2-1). Build the index with CREATE INDEX CONCURRENTLY
and backfill in small batches outside peak hours.
The output field is a list of {"role", "content"} turns: one per reviewer, then the consensus agent's verdict (response shape). The docs recommend an odd number of voters so there is always a majority. To get a synthesized answer instead of a verdict, change swarm_type to "MixtureOfAgents" and give the agents open-ended analysis prompts; the aggregator then merges their perspectives into one report.
The second example removes the model from the aggregation step. Five labelers run as a ConcurrentWorkflow, so nothing coordinates them, and the tally happens in ordinary Python. This is closer to a real colony, where the "decision" is just pheromone adding up. It also lets you set a threshold: if the swarm does not agree strongly, a human gets the ticket.
import asyncio
import os
import re
from collections import Counter
import aiohttp
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ["SWARMS_API_KEY"]
BASE_URL = "https://api.swarms.world"
HEADERS = {"x-api-key": API_KEY, "Content-Type": "application/json"}
TICKET = "I was charged twice for my March invoice and now my account is locked."
LABELS = ["BILLING", "BUG", "ACCOUNT"]
MODELS = ["gpt-5.4", "claude-sonnet-5", "gpt-5.4-mini", "gpt-5.4", "claude-sonnet-5"]
async def main() -> None:
payload = {
"name": "Ticket Label Swarm",
"description": "Five independent labelers, tallied in plain Python",
"swarm_type": "ConcurrentWorkflow",
"task": f"Label this support ticket: {TICKET}",
"agents": [
{
"agent_name": f"Labeler-{i}",
"description": "Labels one customer support ticket",
"system_prompt": (
"You label customer support tickets. Work alone. "
f"Your first line must be 'LABEL: X' where X is one of {', '.join(LABELS)}. "
"Then give one sentence of reasoning."
),
"model_name": model,
"max_loops": 1,
"max_tokens": 512,
"temperature": 0.7,
}
for i, model in enumerate(MODELS, start=1)
],
"max_loops": 1,
}
# Multi-agent runs can take minutes, so give the whole request room.
timeout = aiohttp.ClientTimeout(total=600)
async with aiohttp.ClientSession(headers=HEADERS, timeout=timeout) as session:
async with session.post(f"{BASE_URL}/v1/swarm/completions", json=payload) as resp:
resp.raise_for_status()
result = await resp.json()
pattern = re.compile(r"LABEL:\s*(" + "|".join(LABELS) + r")")
votes = []
for turn in result["output"]:
if not turn["role"].startswith("Labeler-"):
continue
match = pattern.search(str(turn["content"]))
if match:
votes.append(match.group(1))
tally = Counter(votes)
print("Votes:", dict(tally))
label, count = tally.most_common(1)[0] if tally else ("NONE", 0)
if count >= 4:
print("Decision:", label)
else:
print(f"Only {count} of {len(MODELS)} agree: send this ticket to a human")
asyncio.run(main())The ticket mixes a billing problem with an account problem on purpose, so the labelers may split. That is the useful case: a weak majority is a signal in its own right. ConcurrentWorkflow returns turns in the order the agents finished, which does not matter for a count. For a longer walkthrough that builds up from one agent to a full swarm, see how to build an agent swarm in Python, and the Swarms API examples suite has more ready-to-run payloads.
Use a voting swarm (MajorityVoting, or ConcurrentWorkflow with your own tally) when the answer is discrete and checkable, when one model gives different answers on different runs, and when a wrong answer costs more than a few extra calls. Classification, approval gates, extraction checks and code review verdicts fit this well.
Use a synthesis swarm (MixtureOfAgents) when the task is open-ended and the value comes from coverage: several specialists see different parts of a problem, and one report pulls them together.
Use a stigmergic pattern (GroupChat, RoundRobin) when agents need to build on each other's work, such as drafting and critiquing a design. Keep the transcript short and the roles distinct, because every agent reads everything that came before it.
Skip the swarm when one well-prompted agent with the right tools already does the job. Single agent vs multi-agent gives a checklist for that decision. And remember that a swarm can amplify a shared mistake as easily as it averages out independent ones: if every agent reads the same wrong document, the vote is unanimous and wrong. Multi-agent system failure modes covers the quieter ways these systems go wrong.
Swarm intelligence is useful group behavior that comes from many simple agents following local rules, with no leader and no global plan. Ant colonies finding short paths and birds flocking are the standard examples. The group solves a problem that no individual member understands or was assigned.
Gerardo Beni and Jing Wang introduced the term in 1989 in a paper on cellular robotic systems, presented at a NATO workshop and published in the 1993 proceedings. The underlying biology is older: Pierre-Paul Grassé described stigmergy in termites in 1959.
The three classics are Craig Reynolds' boids (1987), which simulates flocking with three steering rules; ant colony optimization, which Marco Dorigo introduced in his 1992 PhD thesis; and particle swarm optimization, published by James Kennedy and Russell Eberhart in 1995. ACO and PSO are optimization methods, while boids is a simulation of collective motion.
Partly. Patterns where agents answer independently and their outputs are aggregated (voting, concurrent fan-out, mixture of agents) or where agents coordinate through a shared transcript or queue follow swarm principles. Systems with a director or router in charge are hierarchies, and LLM swarms use a few capable agents where classic swarms use many simple ones.
AI swarms are used where independent judgments improve reliability or coverage: classifying and routing tickets, approving content or code, reviewing documents from several angles, and research tasks that benefit from multiple perspectives. With the Swarms API you choose the coordination pattern with one swarm_type field on POST /v1/swarm/completions.
Start with three or five for voting, since an odd number avoids ties, and add agents only if measured accuracy improves. Each agent is a billed model call, and agents that share a model and prompt add less than their count suggests. Varying the models and the instructions usually helps more than adding more identical agents.

Multi-agent orchestration explained: who runs when, what each agent sees, how outputs combine and when to stop, with patterns, failure handling and API code.

A reference guide to every swarm architecture in the Swarms API: a diagram for each, when to use it, when to skip it, and the exact swarm_type payload to send.

Multi-agent collaboration patterns with working Swarms API code: debate, majority voting, Mixture of Agents, LLM councils, and the research behind each.