I built a 17-agent AI swarm on my phone — here's how
Okay, buckle up. This is going to be a bit of a deep dive. I've always been fascinated by swarm intelligence – the emergent behavior you get when a bunch of simple agents interact. Think ant colonies, bird flocks, even market movements. So I decided to challenge myself: could I build a functioning, albeit basic, AI swarm entirely on my smartphone? The answer, surprisingly, is yes. And it's been a wild ride.
This isn't about running a pre-trained LLM on-device (though that's cool too). This is about building 17 independent agents, each with simple rules, all communicating via a local network facilitated by Python and a little bit of clever engineering. It's resource intensive, yes. My phone gets warm. But it works.
The Goal: Simple Foraging and Resource Allocation
I wanted a swarm that could "forage" for resources (simulated data points) and then "allocate" them to a central "base" (also simulated). Each agent would have limited sensing capabilities (a radius around itself), communication range, and energy. The core idea was to see if collective behavior would emerge, leading to efficient resource gathering.
The Tech Stack (Yes, on a Phone!)
This isn't using a fancy dedicated AI framework. I'm aiming for portability and demonstration of the concept.
- Python: The backbone. I used the Termux app on Android, which provides a Linux environment on your phone. It’s surprisingly capable.
- Sockets: The agents communicate using Python sockets. They broadcast their location and resource status, and listen for broadcasts from others.
- Multiprocessing (Limited): Android's background processing limitations made true multiprocessing tricky. I settled for a pseudo-parallel approach using threading and asynchronous operations where possible.
- NumPy (Surprisingly Effective): NumPy, despite the performance hit, handles basic vector calculations (distance, direction) efficiently enough for this scale.
-
randommodule: For randomness in agent behavior – crucial for exploration. -
A Simple Data Format: I defined a simple JSON-like format for messages between agents:
{"type": "status", "id": 0, "x": 10, "y": 20, "energy": 80, "has_resource": true}.
The Agent Code (Simplified)
Let’s look at the core agent logic. This is a heavily stripped-down version. Each agent runs in its own Python script within Termux.
import socket
import random
import time
import numpy as np
# Config
HOST = '127.0.0.1' # Loopback for local communication
PORT = 5000 + agent_id # Unique port per agent
BASE_PORT = 5001
RESOURCE_RADIUS = 20
COMMUNICATION_RADIUS = 30
ENERGY_COST_MOVE = 1
ENERGY_COST_COMMUNICATE = 0.5
STARTING_ENERGY = 100
agent_id = int(input("Enter agent ID (0-16): "))
def distance(x1, y1, x2, y2):
return np.sqrt((x1 - x2)**2 + (y1 - y2)**2)
def main():
x = random.uniform(0, 100)
y = random.uniform(0, 100)
energy = STARTING_ENERGY
has_resource = False
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST, PORT))
while True:
# 1. Sense Environment (Simplified)
# For now, just check for resources. In a more complex system,
# this would involve scanning for other agents too.
if not has_resource:
if random.random() < 0.1: # 10% chance of finding a resource
has_resource = True
print(f"Agent {agent_id}: Found a resource!")
# 2. Communicate with Swarm
sock.sendto(f'{{"type": "status", "id": {agent_id}, "x": {x:.2f}, "y": {y:.2f}, "energy": {energy:.2f}, "has_resource": {has_resource}}}'.encode(), (HOST, BASE_PORT))
# 3. Make a Decision (Simple Behavior)
if has_resource:
# Head towards the base (0,0)
dx = 0 - x
dy = 0 - y
dist = distance(x, y, 0, 0)
if dist > 0:
x += (dx / dist) * 2 # Move 2 units per step
y += (dy / dist) * 2
energy -= ENERGY_COST_MOVE
else:
# At the base – deliver resource
has_resource = False
print(f"Agent {agent_id}: Delivered resource!")
else:
# Random Walk
direction = random.uniform(0, 2 * np.pi)
x += np.cos(direction) * 2
y += np.sin(direction) * 2
energy -= ENERGY_COST_MOVE
# 4. Keep within bounds
x = max(0, min(x, 100))
y = max(0, min(y, 100))
# 5. Check Energy
if energy <= 0:
print(f"Agent {agent_id}: Out of energy!")
break
time.sleep(0.2)
The Base Station (Also Python)
The base station is a single script that listens for agent updates, tracks resources delivered, and broadcasts information (currently just a simple beacon).
python
import socket
HOST = '127.0.0.1'
PORT = 5001
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST, PORT))
resource_count = 0
while True:
data, addr = sock.recvfrom(1024)
message = data.decode()
# In a real application, you'd parse this JSON properly
# print(f"Received from {addr}: {message}")
if "has_resource: true" in message:
resource_count +=1
print(f"Resource Delivered! Total
Top comments (0)