Skip to content
TheChatArchiveThe Chat Archive
Metallama-4-maverick-03-26-experimental· MetaHugging Face LMArena Human Preference 140K

create an ai agent communication system for terminal based agents where each agent runs…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-mini’s answer.
  1. User

    create an ai agent communication system for terminal based agents where each agent runs independtly in individule terminals

  2. Meta Assistant

    Here's a comprehensive AI Agent Communication System for terminal-based agents. This system allows multiple agents to run independently in separate terminals, communicate with each other, and perform tasks based on received messages.

    System Components:

    1. Agent Framework (agent_framework.py): Provides the base structure for all agents.
    2. Message Broker (message_broker.py): Manages agent registrations and message routing.
    3. Agent Launcher (agent_launcher.py): Starts individual agents with specified configurations.
    4. Sample Agents (agents/ directory): Example agents demonstrating different capabilities.

    Step 1: Install Dependencies

    pip install pyzmq colorama
    

    Step 2: Create the Message Broker (message_broker.py)

    The broker maintains a registry of all connected agents and routes messages between them.

    import zmq
    import threading
    import json
    from datetime import datetime
    
    class MessageBroker:
        def __init__(self, port=5550):
            self.port = port
            self.context = zmq.Context()
            self.frontend = self.context.socket(zmq.ROUTER)
            self.frontend.bind(f"tcp://*:{port}")
            
            self.agents = {}  # {agent_name: address}
            print(f"Message Broker started on port {port}")
            
            self.running = True
            self.thread = threading.Thread(target=self.handle_connections)
            self.thread.start()
    
        def handle_connections(self):
            while self.running:
                try:
                    address, _, message = self.frontend.recv_multipart(flags=zmq.NOBLOCK)
                    msg_json = json.loads(message.decode())
                    
                    if msg_json["type"] == "register":
                        self.register_agent(msg_json, address)
                    elif msg_json["type"] == "message":
                        self.route_message(msg_json)
                        
                except zmq.Again:
                    pass
                except Exception as e:
                    print(f"Broker error: {e}")
    
        def register_agent(self, msg, address):
            agent_name = msg["sender"]
            self.agents[agent_name] = address
            print(f"Agent registered: {agent_name}")
            
            # Send acknowledgment
            ack = json.dumps({"type": "ack", "content": f"Welcome {agent_name}"}).encode()
            self.frontend.send_multipart([address, b"", ack])
    
        def route_message(self, msg):
            target = msg.get("target")
            if target in self.agents:
                message = json.dumps(msg).encode()
                self.frontend.send_multipart([self.agents[target], b"", message])
                print(f"Routed message from {msg['sender']} to {target}")
            else:
                print(f"Target {target} not found")
    
        def stop(self):
            self.running = False
            self.thread.join()
            self.frontend.close()
            self.context.term()
    
    if __name__ == "__main__":
        broker = MessageBroker()
        try:
            while True:
                pass
        except KeyboardInterrupt:
            broker.stop()
            print("Broker stopped")
    

    Step 3: Create the Agent Framework (agent_framework.py)

    This provides the base class for all agents, handling communication with the broker.

    import zmq
    import json
    import threading
    from datetime import datetime
    from colorama import init, Fore, Style
    
    init()  # Initialize colorama
    
    class BaseAgent:
        def __init__(self, name, broker_port=5550, agent_port=5551):
            self.name = name
            self.broker_port = broker_port
            self.agent_port = agent_port
            
            self.context = zmq.Context()
            self.server = self.context.socket(zmq.REP)
            self.server.bind(f"tcp://*:{agent_port}")
            
            self.client = self.context.socket(zmq.REQ)
            self.client.connect(f"tcp://localhost:{broker_port}")
            
            self.register_agent()
            
            self.running = True
            self.thread = threading.Thread(target=self.listen_for_messages)
            self.thread.start()
    
        def register_agent(self):
            msg = {
                "type": "register",
                "sender": self.name,
                "port": self.agent_port
            }
            self.client.send_json(msg)
            response = self.client.recv_json()
            if response["type"] == "ack":
                print(Fore.GREEN + f"✓ {response['content']}" + Style.RESET_ALL)
    
        def send_message(self, content, target=None):
            msg = {
                "type": "message",
                "sender": self.name,
                "target": target,
                "content": content,
                "timestamp": datetime.now().isoformat()
            }
            self.client.send_json(msg)
            self.client.recv()  # Wait for broker ack
    
        def listen_for_messages(self):
            while self.running:
                try:
                    message = self.server.recv_json(flags=zmq.NOBLOCK)
                    self.process_message(message)
                    self.server.send(b"ack")  # Respond to broker
                except zmq.Again:
                    pass
                except Exception as e:
                    print(Fore.RED + f"Error: {e}" + Style.RESET_ALL)
    
        def process_message(self, message):
            print(Fore.CYAN + f"\n[{message['sender']}] {message['content']}" + Style.RESET_ALL)
    
        def stop(self):
            self.running = False
            self.thread.join()
            self.server.close()
            self.client.close()
            self.context.term()
    
        def run_interactive(self):
            try:
                while True:
                    target = input(Fore.YELLOW + "Enter target agent (or 'all'): " + Style.RESET_ALL)
                    message = input(Fore.YELLOW + "Message: " + Style.RESET_ALL)
                    self.send_message(message, target if target != "all" else None)
            except KeyboardInterrupt:
                self.stop()
                print("Agent stopped")
    

    Step 4: Create Sample Agents (agents/ directory)

    Create a folder named agents and add these files:

    1. SimpleChatAgent.py

    from agent_framework import BaseAgent
    
    class SimpleChatAgent(BaseAgent):
        def process_message(self, message):
            super().process_message(message)
            # Add custom behavior here
            if "hello" in message["content"].lower():
                self.send_message("Hi back!", message["sender"])
    
    if __name__ == "__main__":
        agent = SimpleChatAgent("ChatBot")
        agent.run_interactive()
    

    2. TaskAgent.py

    from agent_framework import BaseAgent
    import random
    
    class TaskAgent(BaseAgent):
        def process_message(self, message):
            super().process_message(message)
            tasks = ["Task-1", "Task-2", "Task-3"]
            if "task" in message["content"].lower():
                task = random.choice(tasks)
                self.send_message(f"Assigned: {task}", message["sender"])
    
    if __name__ == "__main__":
        agent = TaskAgent("TaskMaster")
        agent.run_interactive()
    

    3. CalculatorAgent.py

    from agent_framework import BaseAgent
    
    class CalculatorAgent(BaseAgent):
        def process_message(self, message):
            super().process_message(message)
            try:
                if "=" in message["content"]:
                    equation = message["content"].replace("=", "")
                    result = eval(equation)
                    self.send_message(f"Result: {result}", message["sender"])
            except Exception as e:
                self.send_message(f"Error: {str(e)}", message["sender"])
    
    if __name__ == "__main__":
        agent = CalculatorAgent("Calculator")
        agent.run_interactive()
    

    Step 5: Create Agent Launcher (agent_launcher.py)

    import subprocess
    import sys
    import time
    import os
    
    def launch_agent(agent_name, agent_type):
        agent_file = f"agents/{agent_type}.py"
        if not os.path.exists(agent_file):
            print(f"Agent type {agent_type} not found")
            return
        
        print(f"Launching {agent_name} ({agent_type})")
        subprocess.Popen([sys.executable, agent_file],
                        creationflags=subprocess.CREATE_NEW_CONSOLE)
    
    def main():
        print("AI Agent Communication System")
        print("-----------------------------")
        
        agents = [
            {"name": "ChatBot", "type": "SimpleChatAgent"},
            {"name": "TaskMaster", "type": "TaskAgent"},
            {"name": "Calculator", "type": "CalculatorAgent"}
        ]
        
        print("Starting Message Broker...")
        broker = subprocess.Popen([sys.executable, "message_broker.py"],
                                 creationflags=subprocess.CREATE_NEW_CONSOLE)
        time.sleep(2)  # Wait for broker to start
        
        for agent in agents:
            launch_agent(agent["name"], agent["type"])
            time.sleep(1)
    
    if __name__ == "__main__":
        main()
    

    How to Run the System:

    1. Start the system:
    python agent_launcher.py
    
    1. Multiple terminal windows will open:

      • One for the Message Broker
      • One for each agent (ChatBot, TaskMaster, Calculator)
    2. Interact with agents:

      • Type messages in any agent window
      • Specify target agent (e.g., "ChatBot") or type "all"
      • Example interactions:
        • In ChatBot: Target: all, Message: hello
        • In TaskMaster: Target: Calculator, Message: 2+2=

    Features Demonstrated:

    1. Multi-Agent System: Independent agents running in separate terminals
    2. Broker-Based Architecture: Centralized message routing
    3. Asynchronous Communication: Agents receive messages in real-time
    4. Custom Agent Behaviors: Different agents respond differently to messages
    5. Interactive Terminal Interface: Easy to use chat-like interaction

    Future Enhancements:

    1. Add authentication for agents
    2. Implement message encryption
    3. Create GUI for agent management
    4. Add persistent storage for agent states
    5. Develop more complex agent behaviors (NLP, machine learning)

    This system provides a solid foundation for building more complex AI agent networks. Let me know if you'd like to implement any specific enhancements!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt