File size: 2,486 Bytes
695b33f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Utility functions for agent operations
"""

import time
from typing import Tuple
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class PerformanceMonitor:
    """
    Monitor agent performance and timing
    """
    
    def __init__(self):
        self.metrics = {}
    
    def start_timer(self, operation: str) -> None:
        """
        Start timing an operation
        """
        self.metrics[f"{operation}_start"] = time.time()
    
    def end_timer(self, operation: str) -> float:
        """
        End timing an operation and return duration
        """
        start_time = self.metrics.get(f"{operation}_start")
        if start_time:
            duration = time.time() - start_time
            self.metrics[f"{operation}_duration"] = duration
            return duration
        return 0.0
    
    def get_metrics(self) -> dict:
        """
        Get all collected metrics
        """
        return self.metrics.copy()
    
    def reset(self) -> None:
        """
        Reset all metrics
        """
        self.metrics.clear()


def validate_query(query: str) -> Tuple[bool, str]:
    """
    Validate user query
    """
    if not query or not query.strip():
        return False, "Query cannot be empty."
    
    if len(query) > 2500:
        return False, "Query is too long. Please keep it under 1000 characters."
    
    return True, None


def format_error_message(error: str) -> str:
    """
    Format error messages for user display
    """
    error_map = {
        "Server unreachable": "❌ The legal database is currently unavailable. Please try again in a moment.",
        "timeout": "❌ The request timed out. Please try again.",
        "invalid json": "❌ There was an issue processing the response. Please try again.",
        "health check failed": "❌ The system is initializing. Please wait a moment and try again."
    }
    
    for key, message in error_map.items():
        if key.lower() in error.lower():
            return message
    
    return f"❌ An error occurred: {error}"


def create_safe_filename(query: str, timestamp: str) -> str:
    """
    Create a safe filename for logging purposes
    """
    # Remove problematic characters
    safe_query = "".join(c for c in query if c.isalnum() or c in (' ', '-', '_')).strip()
    safe_query = safe_query[:50]  # Limit length
    
    return f"{timestamp}_{safe_query}.log"