Spaces:
Configuration error
Configuration error
File size: 3,573 Bytes
b437302 |
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 |
import logging
from typing import Dict, Any
from prometheus_client import Counter, Histogram, start_http_server
import time
from datetime import datetime
class InteractionMonitor:
"""Monitor and track user interactions with the platform"""
def __init__(self, enable_metrics_server: bool = True, metrics_port: int = 8000):
"""Initialize the monitoring system
Args:
enable_metrics_server: Whether to start the Prometheus metrics server
metrics_port: Port for the metrics server
"""
self.logger = logging.getLogger(__name__)
# Initialize Prometheus metrics
self.interaction_counter = Counter(
'mental_wellness_interactions_total',
'Total number of interactions',
['agent_type', 'interaction_type']
)
self.response_time = Histogram(
'mental_wellness_response_time_seconds',
'Time taken to generate response',
['agent_type']
)
self.error_counter = Counter(
'mental_wellness_errors_total',
'Total number of errors',
['agent_type', 'error_type']
)
# Start metrics server if enabled
if enable_metrics_server:
try:
start_http_server(metrics_port)
self.logger.info(f"Metrics server started on port {metrics_port}")
except Exception as e:
self.logger.error(f"Failed to start metrics server: {str(e)}")
def track_interaction(self, data: Dict[str, Any]):
"""Track a user interaction
Args:
data: Dictionary containing interaction data
- agent_type: Type of agent (e.g., therapeutic, crisis)
- interaction_type: Type of interaction (e.g., chat, voice)
- response_time: Time taken to generate response
- error: Optional error information
"""
try:
# Log the interaction
self.logger.info(
f"Interaction tracked - Agent: {data.get('agent_type')}, "
f"Type: {data.get('interaction_type')}"
)
# Update Prometheus metrics
self.interaction_counter.labels(
agent_type=data.get('agent_type', 'unknown'),
interaction_type=data.get('interaction_type', 'unknown')
).inc()
# Track response time if available
if 'response_time' in data:
self.response_time.labels(
agent_type=data.get('agent_type', 'unknown')
).observe(data['response_time'])
# Track errors if any
if 'error' in data:
self.error_counter.labels(
agent_type=data.get('agent_type', 'unknown'),
error_type=type(data['error']).__name__
).inc()
except Exception as e:
self.logger.error(f"Error tracking interaction: {str(e)}")
def get_metrics(self) -> Dict[str, Any]:
"""Get current metrics
Returns:
Dictionary containing current metrics
"""
return {
"total_interactions": self.interaction_counter._value.sum(),
"total_errors": self.error_counter._value.sum(),
"average_response_time": self.response_time._sum.sum() / max(self.response_time._count.sum(), 1)
} |