maribiel's picture
Upload entire agent directory with critical fixes
32cfc4a verified
Raw History Blame Contribute Delete
13.5 kB
"""
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