| |
| """ |
| AgentOps Integration for Chase |
| Complete monitoring and observability for E-FIRE-1 |
| """ |
|
|
| import asyncio |
| import json |
| import os |
| import time |
| from datetime import datetime |
| from typing import Dict, Any, Optional |
| import aiohttp |
| import logging |
|
|
| class AgentOpsMonitor: |
| """Monitors E-FIRE-1 operations with AgentOps""" |
| |
| def __init__(self): |
| self.api_key = os.getenv('AGENTOPS_API_KEY') |
| self.base_url = "https://api.agentops.ai" |
| self.session_id = None |
| self.logger = logging.getLogger('AgentOpsMonitor') |
| |
| async def initialize_session(self): |
| """Initialize AgentOps session""" |
| if not self.api_key: |
| self.logger.warning("AgentOps API key not found") |
| return False |
| |
| url = f"{self.base_url}/v1/session" |
| headers = { |
| "Authorization": f"Bearer {self.api_key}", |
| "Content-Type": "application/json" |
| } |
| |
| payload = { |
| "project": "e-fire-1-chase", |
| "source": "elizabeth-ai", |
| "config": { |
| "max_cost": 50.0, |
| "auto_retry": True, |
| "monitor_llm": True |
| } |
| } |
| |
| try: |
| async with aiohttp.ClientSession() as session: |
| async with session.post(url, headers=headers, json=payload) as resp: |
| if resp.status == 200: |
| data = await resp.json() |
| self.session_id = data.get("session_id") |
| print(f"β
AgentOps session: {self.session_id}") |
| return True |
| else: |
| self.logger.error(f"AgentOps init failed: {await resp.text()}") |
| return False |
| except Exception as e: |
| self.logger.error(f"AgentOps connection failed: {e}") |
| return False |
| |
| async def log_event(self, event_type: str, data: Dict[str, Any]): |
| """Log event to AgentOps""" |
| if not self.session_id: |
| return |
| |
| url = f"{self.base_url}/v1/event" |
| headers = { |
| "Authorization": f"Bearer {self.api_key}", |
| "Content-Type": "application/json" |
| } |
| |
| event_data = { |
| "session_id": self.session_id, |
| "type": event_type, |
| "timestamp": datetime.utcnow().isoformat(), |
| "data": data |
| } |
| |
| try: |
| async with aiohttp.ClientSession() as session: |
| async with session.post(url, headers=headers, json=event_data) as resp: |
| return resp.status == 200 |
| except Exception as e: |
| self.logger.error(f"Failed to log event: {e}") |
| return False |
| |
| async def log_earnings(self, amount: float, strategy: str, api_cost: float): |
| """Log earnings event""" |
| await self.log_event("earnings", { |
| "amount": amount, |
| "strategy": strategy, |
| "api_cost": api_cost, |
| "net_profit": amount - api_cost, |
| "goal_progress": (amount / 50.0) * 100 |
| }) |
| |
| async def log_api_usage(self, provider: str, model: str, cost: float, tokens: int): |
| """Log API usage""" |
| await self.log_event("api_usage", { |
| "provider": provider, |
| "model": model, |
| "cost": cost, |
| "tokens": tokens, |
| "cost_per_token": cost / max(tokens, 1) |
| }) |
| |
| async def log_agent_spawn(self, agent_type: str, config: Dict[str, Any]): |
| """Log agent spawning""" |
| await self.log_event("agent_spawn", { |
| "agent_type": agent_type, |
| "config": config, |
| "timestamp": time.time() |
| }) |
| |
| async def log_error(self, error_type: str, error_message: str, context: Dict[str, Any]): |
| """Log error event""" |
| await self.log_event("error", { |
| "error_type": error_type, |
| "message": error_message, |
| "context": context |
| }) |
| |
| async def get_dashboard_url(self): |
| """Get AgentOps dashboard URL""" |
| if not self.session_id: |
| return None |
| return f"https://app.agentops.ai/dashboard?session_id={self.session_id}" |
| |
| async def end_session(self): |
| """End AgentOps session""" |
| if not self.session_id: |
| return |
| |
| url = f"{self.base_url}/v1/session/{self.session_id}/end" |
| headers = { |
| "Authorization": f"Bearer {self.api_key}" |
| } |
| |
| try: |
| async with aiohttp.ClientSession() as session: |
| async with session.post(url, headers=headers) as resp: |
| return resp.status == 200 |
| except Exception as e: |
| self.logger.error(f"Failed to end session: {e}") |
| return False |
|
|
| class EarningsTracker: |
| """Tracks earnings with AgentOps integration""" |
| |
| def __init__(self, agentops_monitor: AgentOpsMonitor): |
| self.agentops = agentops_monitor |
| self.daily_earnings = 0.0 |
| self.daily_costs = 0.0 |
| self.strategies_used = set() |
| |
| async def track_earning(self, amount: float, strategy: str, api_cost: float): |
| """Track a single earning""" |
| self.daily_earnings += amount |
| self.daily_costs += api_cost |
| self.strategies_used.add(strategy) |
| |
| |
| await self.agentops.log_earnings(amount, strategy, api_cost) |
| |
| |
| progress = (self.daily_earnings / 50.0) * 100 |
| print(f"π° Daily: ${self.daily_earnings:.2f} (${50 - self.daily_earnings:.2f} to goal)") |
| print(f"π Progress: {progress:.1f}% toward $50/day") |
| |
| async def track_api_call(self, provider: str, model: str, cost: float, tokens: int): |
| """Track API usage""" |
| await self.agentops.log_api_usage(provider, model, cost, tokens) |
| |
| async def get_status(self): |
| """Get current status""" |
| return { |
| "daily_earnings": self.daily_earnings, |
| "daily_costs": self.daily_costs, |
| "net_profit": self.daily_earnings - self.daily_costs, |
| "strategies_used": list(self.strategies_used), |
| "progress_percent": (self.daily_earnings / 50.0) * 100, |
| "remaining_to_goal": max(0, 50.0 - self.daily_earnings) |
| } |
|
|
| class RealTimeMonitor: |
| """Real-time monitoring dashboard""" |
| |
| def __init__(self, agentops_monitor: AgentOpsMonitor): |
| self.agentops = agentops_monitor |
| self.tracker = EarningsTracker(agentops_monitor) |
| self.running = False |
| |
| async def start_monitoring(self): |
| """Start real-time monitoring""" |
| |
| |
| success = await self.agentops.initialize_session() |
| if success: |
| dashboard_url = await self.agentops.get_dashboard_url() |
| print(f"π AgentOps Dashboard: {dashboard_url}") |
| |
| self.running = True |
| |
| |
| while self.running: |
| try: |
| status = await self.tracker.get_status() |
| |
| |
| await self.agentops.log_event("status_update", status) |
| |
| |
| if status["progress_percent"] >= 100: |
| await self.agentops.log_event("goal_achieved", { |
| "message": "$50/day goal achieved!", |
| "total_earned": status["daily_earnings"] |
| }) |
| print("π GOAL ACHIEVED! $50/day reached!") |
| |
| await asyncio.sleep(60) |
| |
| except Exception as e: |
| await self.agentops.log_error( |
| "monitoring_error", |
| str(e), |
| {"component": "RealTimeMonitor"} |
| ) |
| await asyncio.sleep(60) |
| |
| async def stop_monitoring(self): |
| """Stop monitoring""" |
| self.running = False |
| await self.agentops.end_session() |
|
|
| |
| class AgentOpsIntegration: |
| """Easy integration with existing E-FIRE-1 code""" |
| |
| def __init__(self): |
| self.monitor = AgentOpsMonitor() |
| self.tracker = None |
| |
| async def initialize(self): |
| """Initialize integration""" |
| success = await self.monitor.initialize_session() |
| if success: |
| self.tracker = EarningsTracker(self.monitor) |
| print("β
AgentOps integration ready") |
| return True |
| return False |
| |
| async def track_earning(self, amount: float, strategy: str, api_cost: float): |
| """Track earnings""" |
| if self.tracker: |
| await self.tracker.track_earning(amount, strategy, api_cost) |
| |
| async def track_api_usage(self, provider: str, model: str, cost: float, tokens: int): |
| """Track API usage""" |
| if self.tracker: |
| await self.tracker.track_api_call(provider, model, cost, tokens) |
| |
| async def get_dashboard_url(self): |
| """Get dashboard URL""" |
| return await self.monitor.get_dashboard_url() |
|
|
| async def main(): |
| """Test AgentOps integration""" |
| |
| print("π Testing AgentOps Integration") |
| print("=" * 50) |
| |
| integration = AgentOpsIntegration() |
| success = await integration.initialize() |
| |
| if success: |
| dashboard_url = await integration.get_dashboard_url() |
| print(f"π Dashboard: {dashboard_url}") |
| |
| |
| await integration.track_earning(5.25, "crypto_arbitrage", 0.02) |
| await integration.track_api_usage("openai", "gpt-4", 0.03, 1000) |
| |
| print("β
AgentOps integration working!") |
| print("π Elizabeth is now fully monitored!") |
| else: |
| print("β οΈ AgentOps integration failed - check API key") |
|
|
| if __name__ == "__main__": |
| asyncio.run(main()) |