| |
| """ |
| Multi-Agent Orchestration System for E-FIRE-1 |
| Autonomous agent coordination, communication, and task delegation |
| """ |
|
|
| import asyncio |
| import json |
| import time |
| import hashlib |
| from datetime import datetime |
| from typing import Dict, List, Any, Optional |
| from dataclasses import dataclass, asdict |
| import websockets |
| import threading |
| import sqlite3 |
| import os |
| try: |
| import psycopg2 |
| except Exception: |
| psycopg2 = None |
| import logging |
| import uuid |
|
|
|
|
| @dataclass |
| class AgentMessage: |
| """Message structure for inter-agent communication""" |
| id: str |
| sender: str |
| recipient: str |
| type: str |
| content: Any |
| timestamp: datetime |
| priority: int = 1 |
| ttl: int = 300 |
|
|
|
|
| @dataclass |
| class Task: |
| """Task structure for agent delegation""" |
| id: str |
| type: str |
| data: Dict[str, Any] |
| priority: int |
| assigned_agent: Optional[str] = None |
| status: str = 'pending' |
| created_at: datetime = None |
| completed_at: Optional[datetime] = None |
| result: Optional[Dict[str, Any]] = None |
| attempts: int = 0 |
| max_attempts: int = 3 |
|
|
|
|
| class AgentOrchestrator: |
| """Central orchestrator for multi-agent system""" |
| |
| def __init__(self, port=8765): |
| self.port = port |
| self.agents: Dict[str, Dict[str, Any]] = {} |
| self.message_queue: List[AgentMessage] = [] |
| self.tasks: Dict[str, Task] = {} |
| self.running = False |
| self.websocket_server = None |
| self.logger = logging.getLogger('AgentOrchestrator') |
| self.setup_database() |
| |
| def setup_database(self): |
| """Setup message and task storage""" |
| self.db = sqlite3.connect('agent_communications.db', check_same_thread=False) |
| cursor = self.db.cursor() |
| |
| cursor.execute(''' |
| CREATE TABLE IF NOT EXISTS messages ( |
| id TEXT PRIMARY KEY, |
| sender TEXT, |
| recipient TEXT, |
| type TEXT, |
| content TEXT, |
| timestamp TEXT, |
| priority INTEGER, |
| processed BOOLEAN DEFAULT FALSE |
| ) |
| ''') |
| |
| cursor.execute(''' |
| CREATE TABLE IF NOT EXISTS tasks ( |
| id TEXT PRIMARY KEY, |
| type TEXT, |
| data TEXT, |
| priority INTEGER, |
| assigned_agent TEXT, |
| status TEXT, |
| created_at TEXT, |
| completed_at TEXT, |
| result TEXT, |
| attempts INTEGER DEFAULT 0 |
| ) |
| ''') |
| |
| cursor.execute(''' |
| CREATE TABLE IF NOT EXISTS agent_performance ( |
| agent_id TEXT, |
| timestamp TEXT, |
| tasks_completed INTEGER, |
| earnings REAL, |
| uptime REAL |
| ) |
| ''') |
| |
| self.db.commit() |
| |
| self.pg = None |
| dsn = os.getenv('POSTGRES_DSN') |
| if dsn and psycopg2 is not None: |
| try: |
| self.pg = psycopg2.connect(dsn) |
| with self.pg.cursor() as cur: |
| ddl = open('/data/adaptai/projects/elizabeth/sql/orchestrator_store.sql').read() |
| cur.execute(ddl) |
| self.pg.commit() |
| except Exception: |
| self.pg = None |
| |
| def register_agent(self, agent_id: str, capabilities: List[str], endpoint: str = None): |
| """Register a new agent with capabilities""" |
| self.agents[agent_id] = { |
| 'id': agent_id, |
| 'capabilities': capabilities, |
| 'endpoint': endpoint, |
| 'status': 'active', |
| 'last_heartbeat': datetime.now(), |
| 'tasks_completed': 0, |
| 'earnings': 0.0 |
| } |
| |
| def send_message(self, sender: str, recipient: str, msg_type: str, content: Any, priority: int = 1) -> str: |
| """Send message to specific agent or broadcast""" |
| message_id = str(uuid.uuid4()) |
| message = AgentMessage( |
| id=message_id, |
| sender=sender, |
| recipient=recipient, |
| type=msg_type, |
| content=content, |
| timestamp=datetime.now(), |
| priority=priority |
| ) |
| |
| self.message_queue.append(message) |
| |
| |
| cursor = self.db.cursor() |
| cursor.execute(''' |
| INSERT INTO messages (id, sender, recipient, type, content, timestamp, priority) |
| VALUES (?, ?, ?, ?, ?, ?, ?) |
| ''', ( |
| message_id, sender, recipient, msg_type, |
| json.dumps(content), datetime.now().isoformat(), priority |
| )) |
| self.db.commit() |
| |
| if getattr(self, 'pg', None): |
| try: |
| with self.pg, self.pg.cursor() as cur: |
| cur.execute( |
| "INSERT INTO eliz_orch_messages (id, sender, recipient, type, content, timestamp, priority) VALUES (%s,%s,%s,%s,%s,%s,%s)", |
| (message_id, sender, recipient, msg_type, json.dumps(content), datetime.now(), priority) |
| ) |
| except Exception: |
| pass |
| |
| return message_id |
| |
| def create_task(self, task_type: str, data: Dict[str, Any], priority: int = 1) -> str: |
| """Create a new task for agent delegation""" |
| task_id = str(uuid.uuid4()) |
| task = Task( |
| id=task_id, |
| type=task_type, |
| data=data, |
| priority=priority, |
| created_at=datetime.now() |
| ) |
| |
| self.tasks[task_id] = task |
| |
| |
| cursor = self.db.cursor() |
| cursor.execute(''' |
| INSERT INTO tasks (id, type, data, priority, status, created_at) |
| VALUES (?, ?, ?, ?, ?, ?) |
| ''', ( |
| task_id, task_type, json.dumps(data), priority, 'pending', |
| datetime.now().isoformat() |
| )) |
| self.db.commit() |
| |
| if getattr(self, 'pg', None): |
| try: |
| with self.pg, self.pg.cursor() as cur: |
| cur.execute( |
| "INSERT INTO eliz_orch_tasks (id, type, data, priority, status, created_at) VALUES (%s,%s,%s,%s,%s,%s)", |
| (task_id, task_type, json.dumps(data), priority, 'pending', datetime.now()) |
| ) |
| except Exception: |
| pass |
| |
| return task_id |
| |
| def delegate_task(self, task_id: str) -> Optional[str]: |
| """Intelligently delegate task to most suitable agent""" |
| task = self.tasks.get(task_id) |
| if not task: |
| return None |
| |
| |
| suitable_agents = [] |
| for agent_id, agent in self.agents.items(): |
| if agent['status'] == 'active' and task['type'] in agent['capabilities']: |
| |
| score = ( |
| 1.0 / (agent.get('load', 1) + 1) + |
| 0.5 * (datetime.now() - agent['last_heartbeat']).total_seconds() < 300 |
| ) |
| suitable_agents.append((agent_id, score)) |
| |
| if suitable_agents: |
| |
| best_agent = max(suitable_agents, key=lambda x: x[1])[0] |
| task.assigned_agent = best_agent |
| task.status = 'assigned' |
| |
| |
| cursor = self.db.cursor() |
| cursor.execute(''' |
| UPDATE tasks SET assigned_agent = ?, status = ? WHERE id = ? |
| ''', (best_agent, 'assigned', task_id)) |
| self.db.commit() |
| |
| if getattr(self, 'pg', None): |
| try: |
| with self.pg, self.pg.cursor() as cur: |
| cur.execute("UPDATE eliz_orch_tasks SET assigned_agent=%s, status=%s WHERE id=%s", (best_agent, 'assigned', task_id)) |
| except Exception: |
| pass |
| |
| |
| self.send_message( |
| 'orchestrator', |
| best_agent, |
| 'task', |
| { |
| 'task_id': task_id, |
| 'type': task.type, |
| 'data': task.data, |
| 'priority': task.priority |
| }, |
| priority=task.priority |
| ) |
| |
| return best_agent |
| |
| return None |
| |
| async def handle_websocket_connection(self, websocket, path): |
| """Handle WebSocket connections from agents""" |
| agent_id = None |
| |
| try: |
| async for message in websocket: |
| data = json.loads(message) |
| |
| if data['type'] == 'register': |
| agent_id = data['agent_id'] |
| capabilities = data['capabilities'] |
| self.register_agent(agent_id, capabilities, websocket.remote_address) |
| |
| await websocket.send(json.dumps({ |
| 'type': 'registered', |
| 'agent_id': agent_id, |
| 'timestamp': datetime.now().isoformat() |
| })) |
| |
| elif data['type'] == 'heartbeat': |
| if agent_id in self.agents: |
| self.agents[agent_id]['last_heartbeat'] = datetime.now() |
| self.agents[agent_id]['status'] = 'active' |
| |
| elif data['type'] == 'task_result': |
| task_id = data['task_id'] |
| if task_id in self.tasks: |
| task = self.tasks[task_id] |
| task.result = data['result'] |
| task.status = 'completed' |
| task.completed_at = datetime.now() |
| |
| |
| if task.assigned_agent in self.agents: |
| self.agents[task.assigned_agent]['tasks_completed'] += 1 |
| if 'earnings' in data['result']: |
| self.agents[task.assigned_agent]['earnings'] += data['result']['earnings'] |
| |
| |
| cursor = self.db.cursor() |
| cursor.execute(''' |
| UPDATE tasks SET status = ?, completed_at = ?, result = ? |
| WHERE id = ? |
| ''', ( |
| 'completed', |
| datetime.now().isoformat(), |
| json.dumps(data['result']), |
| task_id |
| )) |
| self.db.commit() |
| if getattr(self, 'pg', None): |
| try: |
| with self.pg, self.pg.cursor() as cur: |
| cur.execute("UPDATE eliz_orch_tasks SET status=%s, completed_at=%s, result=%s WHERE id=%s", |
| ('completed', datetime.now(), json.dumps(data['result']), task_id)) |
| except Exception: |
| pass |
| |
| elif data['type'] == 'task_failed': |
| task_id = data['task_id'] |
| if task_id in self.tasks: |
| task = self.tasks[task_id] |
| task.attempts += 1 |
| |
| if task.attempts >= task.max_attempts: |
| task.status = 'failed' |
| cursor = self.db.cursor() |
| cursor.execute(''' |
| UPDATE tasks SET status = ?, attempts = ? WHERE id = ? |
| ''', ('failed', task.attempts, task_id)) |
| self.db.commit() |
| if getattr(self, 'pg', None): |
| try: |
| with self.pg, self.pg.cursor() as cur: |
| cur.execute("UPDATE eliz_orch_tasks SET status=%s, attempts=%s WHERE id=%s", ('failed', task.attempts, task_id)) |
| except Exception: |
| pass |
| else: |
| task.status = 'pending' |
| task.assigned_agent = None |
| |
| self.delegate_task(task_id) |
| |
| except websockets.exceptions.ConnectionClosed: |
| if agent_id in self.agents: |
| self.agents[agent_id]['status'] = 'offline' |
| |
| except Exception as e: |
| self.logger.error(f"WebSocket error: {e}") |
| |
| def process_message_queue(self): |
| """Process message queue with priority handling""" |
| while self.running: |
| if self.message_queue: |
| |
| self.message_queue.sort(key=lambda x: (-x.priority, x.timestamp)) |
| message = self.message_queue.pop(0) |
| |
| if message.recipient == 'broadcast': |
| |
| for agent_id, agent in self.agents.items(): |
| if agent['status'] == 'active': |
| self._send_to_agent(agent_id, message) |
| else: |
| |
| self._send_to_agent(message.recipient, message) |
| |
| time.sleep(0.1) |
| |
| def _send_to_agent(self, agent_id: str, message: AgentMessage): |
| """Send message to specific agent""" |
| |
| |
| self.logger.info(f"Sending message to {agent_id}: {message.content}") |
| |
| def get_system_metrics(self) -> Dict[str, Any]: |
| """Get comprehensive system metrics""" |
| return { |
| 'active_agents': len([a for a in self.agents.values() if a['status'] == 'active']), |
| 'total_agents': len(self.agents), |
| 'pending_tasks': len([t for t in self.tasks.values() if t.status == 'pending']), |
| 'completed_tasks': len([t for t in self.tasks.values() if t.status == 'completed']), |
| 'failed_tasks': len([t for t in self.tasks.values() if t.status == 'failed']), |
| 'message_queue_size': len(self.message_queue), |
| 'uptime': str(datetime.now() - datetime.now()) |
| } |
| |
| async def start_server(self): |
| """Start the WebSocket server for agent communication""" |
| self.running = True |
| |
| |
| message_thread = threading.Thread(target=self.process_message_queue, daemon=True) |
| message_thread.start() |
| |
| |
| self.websocket_server = await websockets.serve( |
| self.handle_websocket_connection, |
| "localhost", |
| self.port |
| ) |
| |
| self.logger.info(f"Agent orchestrator started on port {self.port}") |
| |
| |
| await self.websocket_server.wait_closed() |
| |
| def stop_server(self): |
| """Stop the orchestrator""" |
| self.running = False |
| if self.websocket_server: |
| self.websocket_server.close() |
|
|
|
|
| |
| class CryptoTradingAgent: |
| """Specialized cryptocurrency trading agent""" |
| |
| def __init__(self, orchestrator: AgentOrchestrator): |
| self.orchestrator = orchestrator |
| self.capabilities = ['crypto_analysis', 'arbitrage_detection', 'trade_execution'] |
| self.performance = {'trades': 0, 'profit': 0.0, 'accuracy': 0.0} |
| |
| async def start(self, endpoint: str = "ws://localhost:8765"): |
| """Connect to orchestrator and start processing tasks""" |
| async with websockets.connect(endpoint) as websocket: |
| |
| await websocket.send(json.dumps({ |
| 'type': 'register', |
| 'agent_id': 'crypto_trader', |
| 'capabilities': self.capabilities |
| })) |
| |
| |
| async for message in websocket: |
| data = json.loads(message) |
| if data['type'] == 'task': |
| result = await self.execute_task(data['data']) |
| await websocket.send(json.dumps({ |
| 'type': 'task_result', |
| 'task_id': data['task_id'], |
| 'result': result |
| })) |
| |
| async def execute_task(self, task_data: Dict[str, Any]) -> Dict[str, Any]: |
| """Execute cryptocurrency trading task""" |
| |
| return { |
| 'success': True, |
| 'earnings': 5.23, |
| 'currency': 'USD', |
| 'details': {'trade_type': 'arbitrage', 'pairs': ['BTC/USDT', 'ETH/USDT']} |
| } |
|
|
|
|
| class DeFiYieldAgent: |
| """DeFi yield farming agent""" |
| |
| def __init__(self, orchestrator: AgentOrchestrator): |
| self.orchestrator = orchestrator |
| self.capabilities = ['yield_farming', 'liquidity_provision', 'protocol_analysis'] |
| self.active_positions = [] |
| |
| async def start(self, endpoint: str = "ws://localhost:8765"): |
| """Connect to orchestrator and start processing tasks""" |
| async with websockets.connect(endpoint) as websocket: |
| await websocket.send(json.dumps({ |
| 'type': 'register', |
| 'agent_id': 'defi_farmer', |
| 'capabilities': self.capabilities |
| })) |
| |
| async for message in websocket: |
| data = json.loads(message) |
| if data['type'] == 'task': |
| result = await self.execute_task(data['data']) |
| await websocket.send(json.dumps({ |
| 'type': 'task_result', |
| 'task_id': data['task_id'], |
| 'result': result |
| })) |
| |
| async def execute_task(self, task_data: Dict[str, Any]) -> Dict[str, Any]: |
| """Execute DeFi yield farming task""" |
| |
| return { |
| 'success': True, |
| 'earnings': 2.15, |
| 'currency': 'USD', |
| 'details': {'protocol': 'Aave', 'apy': 8.5} |
| } |
|
|
|
|
| if __name__ == "__main__": |
| |
| orchestrator = AgentOrchestrator() |
| |
| async def main(): |
| await orchestrator.start_server() |
| |
| asyncio.run(main()) |
|
|