File size: 13,522 Bytes
7fed096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""
Narzędzia pomocnicze dla agenta GAIA.
Zawiera cache, retry logic i monitoring wydajności.
"""

import time
import hashlib
import json
import logging
from typing import Any, Callable, Optional, Dict, List
from functools import wraps
from tenacity import retry, stop_after_attempt, wait_exponential
from dataclasses import dataclass, asdict

logger = logging.getLogger(__name__)


@dataclass
class CacheEntry:
    """Wpis w cache z metadanymi."""
    answer: str
    timestamp: float
    question_type: Optional[str] = None
    confidence: Optional[float] = None
    tools_used: Optional[List[str]] = None


class ResponseCache:
    """Cache dla odpowiedzi agenta z TTL i inteligentnym zarządzaniem."""
    
    def __init__(self, max_size: int = 200, ttl: int = 3600):
        """
        Inicjalizuj cache.
        
        Args:
            max_size: Maksymalna liczba wpisów w cache
            ttl: Time to live w sekundach (domyślnie 1h)
        """
        self.cache = {}
        self.max_size = max_size
        self.ttl = ttl
        self.hits = 0
        self.misses = 0
        
    def _hash_key(self, question: str) -> str:
        """Generuj stabilny hash dla pytania."""
        # Normalizuj pytanie dla lepszego cache hit rate
        normalized = question.lower().strip()
        # Usuń nadmiarowe spacje
        normalized = ' '.join(normalized.split())
        return hashlib.md5(normalized.encode('utf-8')).hexdigest()
    
    def get(self, question: str) -> Optional[CacheEntry]:
        """
        Pobierz odpowiedź z cache.
        
        Args:
            question: Pytanie do sprawdzenia
            
        Returns:
            CacheEntry jeśli znaleziono i nie wygasł, None w przeciwnym razie
        """
        key = self._hash_key(question)
        
        if key in self.cache:
            entry = self.cache[key]
            
            # Sprawdź TTL
            if time.time() - entry.timestamp < self.ttl:
                self.hits += 1
                logger.debug(f"Cache HIT for question: {question[:50]}...")
                return entry
            else:
                # Wygasły wpis - usuń
                del self.cache[key]
                logger.debug(f"Cache EXPIRED for question: {question[:50]}...")
        
        self.misses += 1
        logger.debug(f"Cache MISS for question: {question[:50]}...")
        return None
    
    def set(self, question: str, answer: str, question_type: Optional[str] = None, 
            confidence: Optional[float] = None, tools_used: Optional[List[str]] = None):
        """
        Zapisz odpowiedź do cache.
        
        Args:
            question: Pytanie
            answer: Odpowiedź
            question_type: Typ pytania
            confidence: Poziom pewności
            tools_used: Lista użytych narzędzi
        """
        # Ogranicz rozmiar cache - LRU eviction
        if len(self.cache) >= self.max_size:
            # Znajdź i usuń najstarszy wpis
            oldest_key = min(self.cache, key=lambda k: self.cache[k].timestamp)
            del self.cache[oldest_key]
            logger.debug("Cache evicted oldest entry")
        
        key = self._hash_key(question)
        entry = CacheEntry(
            answer=answer,
            timestamp=time.time(),
            question_type=question_type,
            confidence=confidence,
            tools_used=tools_used or []
        )
        
        self.cache[key] = entry
        logger.debug(f"Cache SET for question: {question[:50]}...")
    
    def get_stats(self) -> Dict[str, Any]:
        """Pobierz statystyki cache."""
        total_requests = self.hits + self.misses
        hit_rate = (self.hits / total_requests) if total_requests > 0 else 0
        
        return {
            'size': len(self.cache),
            'max_size': self.max_size,
            'hits': self.hits,
            'misses': self.misses,
            'hit_rate': hit_rate,
            'ttl': self.ttl
        }
    
    def clear(self):
        """Wyczyść cache."""
        self.cache.clear()
        self.hits = 0
        self.misses = 0
        logger.info("Cache cleared")
    
    def cleanup_expired(self):
        """Usuń wygasłe wpisy z cache."""
        current_time = time.time()
        expired_keys = [
            key for key, entry in self.cache.items()
            if current_time - entry.timestamp >= self.ttl
        ]
        
        for key in expired_keys:
            del self.cache[key]
        
        if expired_keys:
            logger.info(f"Cleaned up {len(expired_keys)} expired cache entries")


def with_retry(max_attempts: int = 3, backoff: float = 1.0, exceptions: tuple = (Exception,)):
    """
    Dekorator retry dla funkcji z konfiguracją backoff i exceptions.
    
    Args:
        max_attempts: Maksymalna liczba prób
        backoff: Podstawowy czas oczekiwania (sekundy)
        exceptions: Tuple wyjątków, dla których retry ma działać
    """
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args, **kwargs):
            last_error = None
            
            for attempt in range(max_attempts):
                try:
                    result = func(*args, **kwargs)
                    if attempt > 0:
                        logger.info(f"Function {func.__name__} succeeded on attempt {attempt + 1}")
                    return result
                    
                except exceptions as e:
                    last_error = e
                    
                    if attempt < max_attempts - 1:
                        wait_time = backoff * (2 ** attempt)  # Exponential backoff
                        logger.warning(f"Function {func.__name__} failed on attempt {attempt + 1}/{max_attempts}: {e}. "
                                     f"Retrying in {wait_time:.1f}s...")
                        time.sleep(wait_time)
                    else:
                        logger.error(f"Function {func.__name__} failed after {max_attempts} attempts: {e}")
                
                except Exception as e:
                    # Nie retry dla innych wyjątków
                    logger.error(f"Function {func.__name__} failed with non-retryable error: {e}")
                    raise e
            
            # Wszystkie próby wyczerpane
            raise last_error
        
        return wrapper
    return decorator


class PerformanceMonitor:
    """Monitor wydajności agenta z metrykami i statystykami."""
    
    def __init__(self):
        """Inicjalizuj monitor wydajności."""
        self.metrics = {
            'total_questions': 0,
            'correct_answers': 0,  # Wymaga manualnego update
            'total_time': 0.0,
            'tool_usage': {},
            'error_count': 0,
            'question_types': {},
            'confidence_scores': [],
            'response_times': [],
            'cache_usage': {
                'hits': 0,
                'misses': 0
            }
        }
        self.start_time = time.time()
    
    def record_question(self, question: str, answer: str, time_taken: float, 
                       tools_used: List[str], question_type: Optional[str] = None,
                       confidence: Optional[float] = None, was_cached: bool = False):
        """
        Zapisz metryki dla pytania.
        
        Args:
            question: Zadane pytanie
            answer: Uzyskana odpowiedź  
            time_taken: Czas wykonania w sekundach
            tools_used: Lista użytych narzędzi
            question_type: Typ pytania
            confidence: Poziom pewności (0.0-1.0)
            was_cached: Czy odpowiedź pochodziła z cache
        """
        self.metrics['total_questions'] += 1
        self.metrics['total_time'] += time_taken
        
        # Zapisz czasy odpowiedzi
        self.metrics['response_times'].append(time_taken)
        if len(self.metrics['response_times']) > 1000:  # Limit do 1000 ostatnich
            self.metrics['response_times'] = self.metrics['response_times'][-1000:]
        
        # Użycie narzędzi
        for tool in tools_used:
            if tool not in self.metrics['tool_usage']:
                self.metrics['tool_usage'][tool] = 0
            self.metrics['tool_usage'][tool] += 1
        
        # Typy pytań
        if question_type:
            if question_type not in self.metrics['question_types']:
                self.metrics['question_types'][question_type] = 0
            self.metrics['question_types'][question_type] += 1
        
        # Poziom pewności
        if confidence is not None:
            self.metrics['confidence_scores'].append(confidence)
            if len(self.metrics['confidence_scores']) > 1000:  # Limit
                self.metrics['confidence_scores'] = self.metrics['confidence_scores'][-1000:]
        
        # Cache usage
        if was_cached:
            self.metrics['cache_usage']['hits'] += 1
        else:
            self.metrics['cache_usage']['misses'] += 1
        
        logger.debug(f"Recorded metrics for question type: {question_type}, "
                    f"time: {time_taken:.2f}s, tools: {tools_used}")
    
    def record_error(self, error: Exception, question: str = ""):
        """Zapisz informację o błędzie."""
        self.metrics['error_count'] += 1
        logger.warning(f"Error recorded: {type(error).__name__}: {error}")
    
    def mark_correct_answer(self):
        """Oznacz odpowiedź jako poprawną (do obliczenia accuracy)."""
        self.metrics['correct_answers'] += 1
    
    def get_stats(self) -> Dict[str, Any]:
        """
        Pobierz pełne statystyki wydajności.
        
        Returns:
            Słownik ze statystykami
        """
        total_questions = self.metrics['total_questions']
        if total_questions == 0:
            return {
                'status': 'no_data',
                'message': 'No questions processed yet'
            }
        
        # Podstawowe metryki
        stats = {
            'total_questions': total_questions,
            'accuracy': self.metrics['correct_answers'] / total_questions if total_questions > 0 else 0,
            'avg_response_time': self.metrics['total_time'] / total_questions,
            'total_time': self.metrics['total_time'],
            'error_rate': self.metrics['error_count'] / total_questions,
            'uptime': time.time() - self.start_time
        }
        
        # Statystyki czasów odpowiedzi
        if self.metrics['response_times']:
            times = self.metrics['response_times']
            stats['response_time_stats'] = {
                'min': min(times),
                'max': max(times),
                'avg': sum(times) / len(times),
                'median': sorted(times)[len(times) // 2]
            }
        
        # Statystyki poziomu pewności
        if self.metrics['confidence_scores']:
            scores = self.metrics['confidence_scores']
            stats['confidence_stats'] = {
                'min': min(scores),
                'max': max(scores),
                'avg': sum(scores) / len(scores)
            }
        
        # Cache statistics
        cache_total = self.metrics['cache_usage']['hits'] + self.metrics['cache_usage']['misses']
        if cache_total > 0:
            stats['cache_hit_rate'] = self.metrics['cache_usage']['hits'] / cache_total
        
        # Dodatkowe metryki
        stats.update({
            'tool_usage': self.metrics['tool_usage'].copy(),
            'question_types': self.metrics['question_types'].copy(),
            'cache_usage': self.metrics['cache_usage'].copy()
        })
        
        return stats
    
    def get_summary(self) -> str:
        """Pobierz tekstowe podsumowanie statystyk."""
        stats = self.get_stats()
        
        if stats.get('status') == 'no_data':
            return "No performance data available yet."
        
        summary = [
            f"📊 GAIA Agent Performance Summary",
            f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
            f"Questions processed: {stats['total_questions']}",
            f"Accuracy: {stats['accuracy']:.1%}",
            f"Avg response time: {stats['avg_response_time']:.2f}s",
            f"Error rate: {stats['error_rate']:.1%}",
        ]
        
        if 'cache_hit_rate' in stats:
            summary.append(f"Cache hit rate: {stats['cache_hit_rate']:.1%}")
        
        if stats['tool_usage']:
            summary.append("\n🔧 Most used tools:")
            for tool, count in sorted(stats['tool_usage'].items(), key=lambda x: x[1], reverse=True)[:3]:
                summary.append(f"  • {tool}: {count} times")
        
        if stats['question_types']:
            summary.append("\n❓ Question types:")
            for qtype, count in sorted(stats['question_types'].items(), key=lambda x: x[1], reverse=True):
                pct = (count / stats['total_questions']) * 100
                summary.append(f"  • {qtype}: {count} ({pct:.1f}%)")
        
        return "\n".join(summary)
    
    def reset(self):
        """Resetuj wszystkie metryki."""
        self.__init__()
        logger.info("Performance metrics reset")


# Singleton instance dla globalnego użycia
_performance_monitor = PerformanceMonitor()

def get_performance_monitor() -> PerformanceMonitor:
    """Pobierz globalną instancję performance monitor."""
    return _performance_monitor