Spaces:
Configuration error
Configuration error
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) | |
} |