Spaces:
Build error
Build error
Create utils/monitoring.py
Browse files- utils/monitoring.py +142 -0
utils/monitoring.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from typing import Dict, Any, List
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
class MonitoringSystem:
|
| 8 |
+
"""
|
| 9 |
+
System for monitoring agent performance and tracking metrics.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, log_file="logs/monitoring_logs.json"):
|
| 13 |
+
self.log_file = log_file
|
| 14 |
+
self._ensure_log_directory()
|
| 15 |
+
|
| 16 |
+
def _ensure_log_directory(self):
|
| 17 |
+
"""Create logs directory if it doesn't exist."""
|
| 18 |
+
os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
|
| 19 |
+
|
| 20 |
+
# Initialize log file if it doesn't exist
|
| 21 |
+
if not os.path.exists(self.log_file):
|
| 22 |
+
with open(self.log_file, 'w') as f:
|
| 23 |
+
json.dump([], f)
|
| 24 |
+
|
| 25 |
+
def log_generation(self, data: Dict[str, Any]):
|
| 26 |
+
"""
|
| 27 |
+
Log a code generation event.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
data: Dictionary containing generation details
|
| 31 |
+
"""
|
| 32 |
+
try:
|
| 33 |
+
# Read existing logs
|
| 34 |
+
with open(self.log_file, 'r') as f:
|
| 35 |
+
logs = json.load(f)
|
| 36 |
+
|
| 37 |
+
# Add timestamp if not present
|
| 38 |
+
if 'timestamp' not in data:
|
| 39 |
+
data['timestamp'] = datetime.now().isoformat()
|
| 40 |
+
|
| 41 |
+
# Add to logs
|
| 42 |
+
logs.append(data)
|
| 43 |
+
|
| 44 |
+
# Write back (limit to last 100 entries)
|
| 45 |
+
with open(self.log_file, 'w') as f:
|
| 46 |
+
json.dump(logs[-100:], f, indent=2)
|
| 47 |
+
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"Error logging generation: {e}")
|
| 50 |
+
|
| 51 |
+
def get_metrics(self, n_days: int = 7) -> List[Dict]:
|
| 52 |
+
"""
|
| 53 |
+
Get metrics from the last n days.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
n_days: Number of days to look back
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
List of log entries
|
| 60 |
+
"""
|
| 61 |
+
try:
|
| 62 |
+
with open(self.log_file, 'r') as f:
|
| 63 |
+
logs = json.load(f)
|
| 64 |
+
|
| 65 |
+
# Filter by date if requested
|
| 66 |
+
if n_days:
|
| 67 |
+
cutoff_date = datetime.now().timestamp() - (n_days * 24 * 60 * 60)
|
| 68 |
+
filtered_logs = [
|
| 69 |
+
log for log in logs
|
| 70 |
+
if datetime.fromisoformat(log['timestamp']).timestamp() > cutoff_date
|
| 71 |
+
]
|
| 72 |
+
return filtered_logs
|
| 73 |
+
else:
|
| 74 |
+
return logs
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
print(f"Error reading metrics: {e}")
|
| 78 |
+
return []
|
| 79 |
+
|
| 80 |
+
def calculate_statistics(self) -> Dict[str, Any]:
|
| 81 |
+
"""
|
| 82 |
+
Calculate statistics from logs.
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
Dictionary with statistics
|
| 86 |
+
"""
|
| 87 |
+
logs = self.get_metrics(n_days=None)
|
| 88 |
+
|
| 89 |
+
if not logs:
|
| 90 |
+
return {
|
| 91 |
+
"total_generations": 0,
|
| 92 |
+
"average_score": 0,
|
| 93 |
+
"success_rate": 0
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
# Convert to DataFrame for easier analysis
|
| 97 |
+
df = pd.DataFrame(logs)
|
| 98 |
+
|
| 99 |
+
stats = {
|
| 100 |
+
"total_generations": len(df),
|
| 101 |
+
"models_used": df['model'].value_counts().to_dict() if 'model' in df.columns else {},
|
| 102 |
+
"unique_prompts": df['prompt'].nunique() if 'prompt' in df.columns else 0
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
# Calculate average scores if available
|
| 106 |
+
if 'review_score' in df.columns:
|
| 107 |
+
stats['average_review_score'] = df['review_score'].mean()
|
| 108 |
+
stats['best_score'] = df['review_score'].max()
|
| 109 |
+
stats['worst_score'] = df['review_score'].min()
|
| 110 |
+
|
| 111 |
+
if 'test_score' in df.columns:
|
| 112 |
+
test_scores = df['test_score'].dropna()
|
| 113 |
+
if len(test_scores) > 0:
|
| 114 |
+
stats['average_test_score'] = test_scores.mean()
|
| 115 |
+
|
| 116 |
+
# Calculate success rate (assuming any generation with a score is successful)
|
| 117 |
+
successful = len(df[df['review_score'] > 0]) if 'review_score' in df.columns else 0
|
| 118 |
+
stats['success_rate'] = (successful / len(df)) * 100 if len(df) > 0 else 0
|
| 119 |
+
|
| 120 |
+
return stats
|
| 121 |
+
|
| 122 |
+
def export_logs(self, format: str = "csv") -> str:
|
| 123 |
+
"""
|
| 124 |
+
Export logs in specified format.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
format: Output format (csv, json)
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
Path to exported file
|
| 131 |
+
"""
|
| 132 |
+
logs = self.get_metrics(n_days=None)
|
| 133 |
+
df = pd.DataFrame(logs)
|
| 134 |
+
|
| 135 |
+
if format == "csv":
|
| 136 |
+
export_path = self.log_file.replace('.json', '.csv')
|
| 137 |
+
df.to_csv(export_path, index=False)
|
| 138 |
+
return export_path
|
| 139 |
+
elif format == "json":
|
| 140 |
+
return self.log_file
|
| 141 |
+
else:
|
| 142 |
+
raise ValueError(f"Unsupported format: {format}")
|