Below is one way to create a simple terminal-based AI agent communication system in Python. In this example, each agent runs in its own terminal and uses ZeroMQ’s Pub/Sub pattern to exchange messages. One agent “publishes” its messages and “subscribes” to the messages of other agents.
Overview
Each Agent
Runs in a separate terminal session. It has its own publisher socket and subscriber socket. The publisher binds to its own port so that other agents can subscribe to it.
Communication Setup
Each agent is launched with its own unique name, a port number for publishing, and a list of ports to which it should subscribe (i.e. the other agents’ publisher ports).
Message Structure
Messages are sent as JSON objects containing a sender name, timestamp, and the message content.
Step 1. Install Dependencies
Make sure you have Python installed, and then install the ZeroMQ Python bindings (pyzmq):
bash
pip install pyzmq
Step 2. Write the Agent Code
Create a file named agent.py with the following content:
python
import zmq
import sys
import json
import threading
import time
from datetime import datetime
class Agent:
def __init__(self, name, pub_port, subscription_ports):
self.name = name
self.pub_port = pub_port
self.subscription_ports = subscription_ports
# ZeroMQ context
self.context = zmq.Context()
# Create a publisher socket and bind to our port.
self.publisher = self.context.socket(zmq.PUB)
self.publisher.bind(f"tcp://*:{self.pub_port}")
# Create a subscriber socket
self.subscriber = self.context.socket(zmq.SUB)
# Subscribe to all messages by default
self.subscriber.setsockopt_string(zmq.SUBSCRIBE, "")
# Connect to the publisher ports of other agents
for port in self.subscription_ports:
try:
self.subscriber.connect(f"tcp://localhost:{port}")
print(f"[{self.name}] Subscribing to messages on port {port}")
except Exception as e:
print(f"Error connecting to port {port}: {e}")
self.running = True
# Start the background thread to listen for incoming messages.
self.listener_thread = threading.Thread(target=self.listen)
self.listener_thread.daemon = True
self.listener_thread.start()
def listen(self):
"""Continuously listen for messages from other agents."""
while self.running:
try:
# Use a non-blocking poll for new messages.
if self.subscriber.poll(100): # timeout is in milliseconds
message = self.subscriber.recv_json()
# Process message if it's not from ourselves.
if message.get("sender") != self.name:
self.process_message(message)
except zmq.ZMQError as e:
print(f"[{self.name}] ZMQ error: {e}")
break
def process_message(self, message):
"""Process a received message."""
sender = message.get("sender")
content = message.get("content")
timestamp = message.get("timestamp")
print(f"\n[{self.name}] Received from {sender} at {timestamp}: {content}")
def send_message(self, content):
"""Compose and send a message."""
message = {
"sender": self.name,
"timestamp": datetime.now().isoformat(),
"content": content
}
self.publisher.send_json(message)
def stop(self):
"""Clean up sockets and threads."""
self.running = False
# Give the listener thread some time to close
time.sleep(0.2)
self.publisher.close()
self.subscriber.close()
self.context.term()
def main():
if len(sys.argv) != 4:
print("Usage: python agent.py <name> <pub_port> <comma_separated_subscription_ports>")
print("Example: python agent.py Agent1 5555 5556,5557")
sys.exit(1)
name = sys.argv[1]
pub_port = sys.argv[2]
# Split provided subscription ports by comma and filter out any empty strings.
subscription_ports = [port.strip() for port in sys.argv[3].split(',') if port.strip()]
# Create an agent with the provided configuration
agent = Agent(name, pub_port, subscription_ports)
print(f"[{agent.name}] Started. Publishing on port {pub_port}.")
try:
# Main loop: read from standard input and send outgoing messages.
while True:
content = input(f"{name}> ")
if content.lower().strip() in ["quit", "exit"]:
break
agent.send_message(content)
# A small sleep to allow message delivery
time.sleep(0.1)
except KeyboardInterrupt:
print("\nInterrupted...")
# Stop agent before quitting
agent.stop()
print(f"[{agent.name}] Stopped.")
if __name__ == "__main__":
main()
Step 3. Run Multiple Agents in Separate Terminals
Suppose you want to create three agents: Agent1, Agent2, and Agent3. You will choose different publishing ports for each and have them subscribe to each other’s ports.
Terminal 1:
Start Agent1. For example, Agent1 publishes on port 5555 and subscribes to Agent2 and Agent3 (on ports 5556 and 5557):
bash
python agent.py Agent1 5555 5556,5557
Terminal 2:
Start Agent2. For example, Agent2 publishes on port 5556 and subscribes to Agent1 and Agent3 (on ports 5555 and 5557):
bash
python agent.py Agent2 5556 5555,5557
Terminal 3:
Start Agent3. For example, Agent3 publishes on port 5557 and subscribes to Agent1 and Agent2 (on ports 5555 and 5556):
bash
python agent.py Agent3 5557 5555,5556
Step 4. Communicate Between Agents
In each terminal, type a message and press Enter.
The message will be published from the current agent’s publisher, and any agents that are subscribed will receive and print the message.
For example, if you type "Hello from Agent1" on Terminal 1, you should see that message displayed as received by Agent2 and Agent3 in their respective terminals.
Type quit or press Ctrl+C to exit an agent’s terminal session.
Extending the System
This basic example can be improved or extended in many ways:
Targeted Messages: Modify the message structure to include a target agent so only specific agents process the message.
Agent Discovery: Implement a mechanism for dynamic discovery of agents rather than manually supplying subscription ports.
Different Communication Patterns: Use ZeroMQ’s REQ/REP or ROUTER/DEALER sockets for two-way communication and more complex interaction.
Message Encryption: Secure the data exchange over the network.
Logging and Error Handling: Enhance logging and handle connection errors more robustly.
This should give you a good start toward building an AI agent communication system where each agent runs independently in its own terminal. Happy coding!