Spaces:
Sleeping
Sleeping
File size: 12,165 Bytes
e0aa230 |
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 374 375 376 377 378 379 380 381 382 383 384 |
"""
Error Handler Module
This module provides centralized error handling and logging
for the RAG AI system.
"""
import logging
import traceback
import functools
from typing import Any, Callable, Dict, Optional, Type, Union
from enum import Enum
class ErrorType(Enum):
"""Enumeration of error types in the system."""
DOCUMENT_PROCESSING = "document_processing"
URL_PROCESSING = "url_processing"
EMBEDDING_GENERATION = "embedding_generation"
VECTOR_STORAGE = "vector_storage"
QUERY_PROCESSING = "query_processing"
RESPONSE_GENERATION = "response_generation"
API_ERROR = "api_error"
CONFIGURATION = "configuration"
UI_ERROR = "ui_error"
UNKNOWN = "unknown"
class RAGError(Exception):
"""Base exception class for RAG AI system errors."""
def __init__(
self,
message: str,
error_type: ErrorType = ErrorType.UNKNOWN,
details: Optional[Dict[str, Any]] = None,
):
"""
Initialize RAGError.
Args:
message: Error message
error_type: Type of error
details: Additional error details
"""
super().__init__(message)
self.error_type = error_type
self.details = details or {}
self.message = message
class DocumentProcessingError(RAGError):
"""Exception for document processing errors."""
def __init__(
self,
message: str,
file_path: Optional[str] = None,
details: Optional[Dict[str, Any]] = None,
):
details = details or {}
if file_path:
details["file_path"] = file_path
super().__init__(message, ErrorType.DOCUMENT_PROCESSING, details)
class URLProcessingError(RAGError):
"""Exception for URL processing errors."""
def __init__(
self,
message: str,
url: Optional[str] = None,
details: Optional[Dict[str, Any]] = None,
):
details = details or {}
if url:
details["url"] = url
super().__init__(message, ErrorType.URL_PROCESSING, details)
class EmbeddingError(RAGError):
"""Exception for embedding generation errors."""
def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
super().__init__(message, ErrorType.EMBEDDING_GENERATION, details)
class VectorStorageError(RAGError):
"""Exception for vector storage errors."""
def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
super().__init__(message, ErrorType.VECTOR_STORAGE, details)
class QueryProcessingError(RAGError):
"""Exception for query processing errors."""
def __init__(
self,
message: str,
query: Optional[str] = None,
details: Optional[Dict[str, Any]] = None,
):
details = details or {}
if query:
details["query"] = query
super().__init__(message, ErrorType.QUERY_PROCESSING, details)
class ResponseGenerationError(RAGError):
"""Exception for response generation errors."""
def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
super().__init__(message, ErrorType.RESPONSE_GENERATION, details)
class APIError(RAGError):
"""Exception for API-related errors."""
def __init__(
self,
message: str,
api_name: Optional[str] = None,
status_code: Optional[int] = None,
details: Optional[Dict[str, Any]] = None,
):
details = details or {}
if api_name:
details["api_name"] = api_name
if status_code:
details["status_code"] = status_code
super().__init__(message, ErrorType.API_ERROR, details)
class ConfigurationError(RAGError):
"""Exception for configuration errors."""
def __init__(
self,
message: str,
config_key: Optional[str] = None,
details: Optional[Dict[str, Any]] = None,
):
details = details or {}
if config_key:
details["config_key"] = config_key
super().__init__(message, ErrorType.CONFIGURATION, details)
class ErrorHandler:
"""
Centralized error handler for the RAG AI system.
Features:
- Error logging with context
- Error categorization
- Error recovery suggestions
- Performance monitoring
"""
def __init__(self, logger_name: str = __name__):
"""
Initialize the ErrorHandler.
Args:
logger_name: Name for the logger instance
"""
self.logger = logging.getLogger(logger_name)
self.error_counts = {}
def handle_error(
self, error: Exception, context: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Handle an error with logging and context.
Args:
error: The exception that occurred
context: Additional context information
Returns:
Dictionary containing error information
"""
context = context or {}
# Determine error type
if isinstance(error, RAGError):
error_type = error.error_type
error_details = error.details
else:
error_type = ErrorType.UNKNOWN
error_details = {}
# Create error info
error_info = {
"type": error_type.value,
"message": str(error),
"details": error_details,
"context": context,
"traceback": traceback.format_exc(),
}
# Log the error
self._log_error(error_info)
# Update error counts
self._update_error_counts(error_type)
# Add recovery suggestions
error_info["recovery_suggestions"] = self._get_recovery_suggestions(error_type)
return error_info
def _log_error(self, error_info: Dict[str, Any]) -> None:
"""
Log error information.
Args:
error_info: Error information dictionary
"""
error_type = error_info["type"]
message = error_info["message"]
context = error_info.get("context", {})
log_message = f"[{error_type.upper()}] {message}"
if context:
context_str = ", ".join([f"{k}={v}" for k, v in context.items()])
log_message += f" | Context: {context_str}"
self.logger.error(log_message)
# Log traceback at debug level
if error_info.get("traceback"):
self.logger.debug(f"Traceback: {error_info['traceback']}")
def _update_error_counts(self, error_type: ErrorType) -> None:
"""
Update error count statistics.
Args:
error_type: Type of error that occurred
"""
if error_type not in self.error_counts:
self.error_counts[error_type] = 0
self.error_counts[error_type] += 1
def _get_recovery_suggestions(self, error_type: ErrorType) -> list:
"""
Get recovery suggestions for an error type.
Args:
error_type: Type of error
Returns:
List of recovery suggestions
"""
suggestions = {
ErrorType.DOCUMENT_PROCESSING: [
"Check if the document format is supported",
"Verify the document is not corrupted",
"Ensure sufficient disk space for processing",
],
ErrorType.URL_PROCESSING: [
"Verify the URL is accessible",
"Check internet connectivity",
"Ensure the website allows scraping",
],
ErrorType.EMBEDDING_GENERATION: [
"Check Gemini API key configuration",
"Verify API quota and rate limits",
"Ensure text content is not empty",
],
ErrorType.VECTOR_STORAGE: [
"Check Pinecone API key configuration",
"Verify Pinecone index exists",
"Check vector dimensions match index configuration",
],
ErrorType.QUERY_PROCESSING: [
"Ensure query is not empty",
"Check if knowledge base has content",
"Verify embedding generation is working",
],
ErrorType.RESPONSE_GENERATION: [
"Check language model configuration",
"Verify retrieved context is valid",
"Ensure API keys are configured",
],
ErrorType.API_ERROR: [
"Check API key validity",
"Verify network connectivity",
"Check API rate limits and quotas",
],
ErrorType.CONFIGURATION: [
"Check configuration file syntax",
"Verify all required settings are present",
"Ensure environment variables are set",
],
ErrorType.UI_ERROR: [
"Refresh the page",
"Check browser compatibility",
"Verify Gradio is properly installed",
],
}
return suggestions.get(error_type, ["Contact support for assistance"])
def get_error_statistics(self) -> Dict[str, Any]:
"""
Get error statistics.
Returns:
Dictionary containing error statistics
"""
total_errors = sum(self.error_counts.values())
return {
"total_errors": total_errors,
"error_counts": {
error_type.value: count
for error_type, count in self.error_counts.items()
},
"most_common_error": (
max(self.error_counts.items(), key=lambda x: x[1])[0].value
if self.error_counts
else None
),
}
def error_handler(
error_type: ErrorType = ErrorType.UNKNOWN, context: Optional[Dict[str, Any]] = None
):
"""
Decorator for automatic error handling.
Args:
error_type: Type of error to handle
context: Additional context information
Returns:
Decorated function
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
handler = ErrorHandler()
try:
return func(*args, **kwargs)
except Exception as e:
error_context = context or {}
error_context.update(
{
"function": func.__name__,
"args": str(args)[:100], # Truncate for logging
"kwargs": str(kwargs)[:100],
}
)
error_info = handler.handle_error(e, error_context)
# Re-raise as appropriate RAG error type
if error_type == ErrorType.DOCUMENT_PROCESSING:
raise DocumentProcessingError(str(e), details=error_info)
elif error_type == ErrorType.URL_PROCESSING:
raise URLProcessingError(str(e), details=error_info)
elif error_type == ErrorType.EMBEDDING_GENERATION:
raise EmbeddingError(str(e), details=error_info)
elif error_type == ErrorType.VECTOR_STORAGE:
raise VectorStorageError(str(e), details=error_info)
elif error_type == ErrorType.QUERY_PROCESSING:
raise QueryProcessingError(str(e), details=error_info)
elif error_type == ErrorType.RESPONSE_GENERATION:
raise ResponseGenerationError(str(e), details=error_info)
else:
raise RAGError(str(e), error_type, error_info)
return wrapper
return decorator
|