File size: 10,132 Bytes
42bba47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python3
"""
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,  # Daily budget
                "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)
        
        # Log to AgentOps
        await self.agentops.log_earnings(amount, strategy, api_cost)
        
        # Log progress
        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"""
        
        # Initialize AgentOps
        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
        
        # Start monitoring loop
        while self.running:
            try:
                status = await self.tracker.get_status()
                
                # Send status update
                await self.agentops.log_event("status_update", status)
                
                # Check if goal reached
                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)  # Update every minute
                
            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()

# Integration wrapper for existing code
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}")
        
        # Test tracking
        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())