create an ai agent communication system for terminal based agents where each agent runs…
- User
create an ai agent communication system for terminal based agents where each agent runs independtly in individule terminals
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:
- Agent Framework (
agent_framework.py): Provides the base structure for all agents. - Message Broker (
message_broker.py): Manages agent registrations and message routing. - Agent Launcher (
agent_launcher.py): Starts individual agents with specified configurations. - Sample Agents (
agents/directory): Example agents demonstrating different capabilities.
Step 1: Install Dependencies
pip install pyzmq coloramaStep 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
agentsand 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:
- Start the system:
python agent_launcher.py-
Multiple terminal windows will open:
- One for the Message Broker
- One for each agent (ChatBot, TaskMaster, Calculator)
-
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:
- Multi-Agent System: Independent agents running in separate terminals
- Broker-Based Architecture: Centralized message routing
- Asynchronous Communication: Agents receive messages in real-time
- Custom Agent Behaviors: Different agents respond differently to messages
- Interactive Terminal Interface: Easy to use chat-like interaction
Future Enhancements:
- Add authentication for agents
- Implement message encryption
- Create GUI for agent management
- Add persistent storage for agent states
- 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!
- Agent Framework (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.