DEV Community

Samuel James Hiotis
Samuel James Hiotis

Posted on

I built a 17-agent AI swarm on my phone — here's how

I built a 17-agent AI swarm on my phone — here's how

Okay, buckle up. This is a weird one. For the past few weeks I've been obsessed with the idea of running a distributed, multi-agent AI system entirely on my phone. Not just a single model, but a swarm of 17 distinct agents, each with their own task, communicating and collaborating to solve problems. And I actually did it.

It wasn’t easy. It wasn’t efficient. But it was incredibly rewarding. This article details how I pulled it off, the challenges I faced, and the surprisingly powerful capabilities that emerged. Be warned: this is fairly technical, geared toward developers comfortable with Python and a little bit of mobile development concepts.

The Goal: Decentralized Intelligence in Your Pocket

The core concept was inspired by swarm intelligence, like ant colonies or bee hives. Instead of one monolithic AI, I wanted a network of smaller, specialized agents. Each agent would be relatively simple, but collectively they could tackle tasks beyond the capacity of any single agent.

My specific use case? Automated data analysis and report generation from a constantly updating stream of information (think crypto market data, but adaptable to anything). I envisioned agents responsible for:

  • Data Acquisition (3 agents): Scraping different sources, handling API connections.
  • Data Preprocessing (4 agents): Cleaning, transforming, and validating data.
  • Analysis & Modeling (6 agents): Performing calculations, running simple regressions, identifying trends.
  • Report Generation (4 agents): Crafting summaries, charts (text-based initially), and alerts.

The Tech Stack: Python, Termux & A Little Magic

The biggest constraint was, of course, the limited resources of a phone. Forget heavy frameworks like TensorFlow or PyTorch. I needed something lightweight and efficient. Here's what I landed on:

  • Python: My go-to for rapid prototyping and data manipulation.
  • Termux: An Android terminal emulator and Linux environment. This is the key. Termux allows you to run a full Python environment on your phone. (Install from F-Droid for best results).
  • SQLite: For lightweight data storage. No need for a full database server.
  • Requests: For making HTTP requests to APIs and scraping websites.
  • A Custom Inter-Agent Communication Protocol: More on this later.
  • Threading: Essential for concurrency, allowing the agents to operate "simultaneously".

Building the Agents: Small, Focused, and Pythonic

Each agent is essentially a Python script with a specific function. Let's look at a simplified example: a Data Acquisition agent scraping a hypothetical price feed:

# agent_data_acq_01.py
import requests
import time
import sqlite3

def acquire_price():
  try:
    response = requests.get("https://api.example.com/price") # Replace with real API
    response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
    data = response.json()
    price = data['price']
    return price
  except requests.exceptions.RequestException as e:
    print(f"Error acquiring price: {e}")
    return None

def main():
  conn = sqlite3.connect('data.db')
  cursor = conn.cursor()
  cursor.execute('''CREATE TABLE IF NOT EXISTS prices (timestamp REAL, price REAL)''')

  while True:
    price = acquire_price()
    if price:
      timestamp = time.time()
      cursor.execute("INSERT INTO prices (timestamp, price) VALUES (?, ?)", (timestamp, price))
      conn.commit()
      print(f"Price acquired: {price} at {timestamp}")
    time.sleep(60) # Check every 60 seconds

if __name__ == "__main__":
  main()
Enter fullscreen mode Exit fullscreen mode

This is a simplified agent. Real-world agents would have more robust error handling, logging, and configuration options. The crucial point is its simplicity and focus – it does one thing well.

The Communication Layer: A Message Queue with Files

Getting the agents to talk to each other was the biggest challenge. I initially tried using sockets, but the overhead and complexity were too high for a mobile environment. I ended up with a surprisingly effective solution: a file-based message queue.

Each agent has a dedicated input and output directory. Agents "publish" messages (serialized as JSON) to other agents’ input directories. Agents "subscribe" by periodically checking their input directories for new messages.

import os
import json
import time

def publish_message(target_agent, message):
  filepath = f"/data/data/com.termux/files/home/swarm/{target_agent}_in/{time.time()}.json"
  with open(filepath, 'w') as f:
    json.dump(message, f)

def subscribe_messages(agent_name):
  while True:
    in_dir = f"/data/data/com.termux/files/home/swarm/{agent_name}_in"
    for filename in os.listdir(in_dir):
      filepath = os.path.join(in_dir, filename)
      try:
        with open(filepath, 'r') as f:
          message = json.load(f)
          # Process message here
          print(f"Agent {agent_name} received: {message}")
        os.remove(filepath) # Delete message after processing
      except json.JSONDecodeError:
        print(f"Error decoding JSON in file: {filename}")

    time.sleep(1)
Enter fullscreen mode Exit fullscreen mode

This is a rudimentary system, but it works! It avoids the complexities of networking and relies on the file system, which is generally well-optimized on Android.

Orchestration: A Simple Loop and Startup Script

There's no sophisticated orchestration framework here. It's mostly a shell script that launches each agent in a separate background process:


bash
#!/bin/bash

# Create directories for each agent
mkdir -p /data/data/com.termux/files/home/swarm/agent_data_acq_01_in
mkdir -p /data/data/com.termux/files/home/swarm/agent_data_acq_01_out

# Launch agents
python /data/data/com.termux/files/home/swarm/agent_data_acq_01.py &
python /data/data/com.termux/files/home/swarm/agent_data_acq_02.py &
# ... launch all 17 agents ...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)