Commit ·
64b2383
1
Parent(s): d2da2aa
refactor code structure for enhanced maintainability and clarity
Browse files
app.py
CHANGED
|
@@ -12,6 +12,7 @@ import copy
|
|
| 12 |
import re
|
| 13 |
from abc import ABC, abstractmethod
|
| 14 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
|
|
| 15 |
from collections import defaultdict
|
| 16 |
|
| 17 |
try:
|
|
@@ -63,7 +64,7 @@ except ImportError:
|
|
| 63 |
print("WARNING: librosa library not found. Audio processing may be impaired. Install with: pip install librosa")
|
| 64 |
|
| 65 |
try:
|
| 66 |
-
import openpyxl
|
| 67 |
except ImportError:
|
| 68 |
openpyxl = None
|
| 69 |
print("WARNING: openpyxl library not found. .xlsx file processing might fail. Install with: pip install openpyxl")
|
|
@@ -73,7 +74,6 @@ try:
|
|
| 73 |
except ImportError:
|
| 74 |
pdfplumber = None
|
| 75 |
print("WARNING: pdfplumber library not found. PDF file processing will be unavailable. Install with: pip install pdfplumber")
|
| 76 |
-
# --- End of New Imports ---
|
| 77 |
|
| 78 |
logging.basicConfig(
|
| 79 |
level=logging.INFO,
|
|
@@ -90,15 +90,15 @@ GOOGLE_GEMINI_API_KEY = os.getenv("GOOGLE_GEMINI_API_KEY")
|
|
| 90 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 91 |
|
| 92 |
AGENT_DEFAULT_TIMEOUT = 15
|
| 93 |
-
MAX_CONTEXT_LENGTH_LLM = 30000
|
| 94 |
|
| 95 |
-
MAX_FILE_SIZE = 5 * 1024 * 1024
|
| 96 |
CSV_SAMPLE_ROWS = 3
|
| 97 |
-
MAX_FILE_CONTEXT_LENGTH = 10000
|
| 98 |
|
| 99 |
-
# Global variable for ASR pipeline (initialized on first use)
|
| 100 |
asr_pipeline_instance: Optional[Any] = None
|
| 101 |
-
ASR_MODEL_NAME = "openai/whisper-tiny"
|
|
|
|
| 102 |
|
| 103 |
DEFAULT_RAG_CONFIG = {
|
| 104 |
'search': {
|
|
@@ -108,7 +108,8 @@ DEFAULT_RAG_CONFIG = {
|
|
| 108 |
'google_cse_id': GOOGLE_CUSTOM_SEARCH_CSE_ID,
|
| 109 |
'tavily_api_key': TAVILY_API_KEY,
|
| 110 |
'default_max_results': 3, 'retry_attempts': 2, 'retry_delay': 2,
|
| 111 |
-
'google_timeout': 8, 'tavily_depth': "basic"
|
|
|
|
| 112 |
},
|
| 113 |
'processing': {
|
| 114 |
'trusted_sources': {'wikipedia.org': 0.8, 'reuters.com': 0.75, 'apnews.com': 0.75},
|
|
@@ -135,9 +136,7 @@ class FileProcessor:
|
|
| 135 |
global asr_pipeline_instance
|
| 136 |
if asr_pipeline_instance is None and hf_transformers_pipeline and torch:
|
| 137 |
try:
|
| 138 |
-
|
| 139 |
-
# Simpler for HF Spaces CPU instances:
|
| 140 |
-
device = -1 # CPU
|
| 141 |
asr_pipeline_instance = hf_transformers_pipeline(
|
| 142 |
"automatic-speech-recognition",
|
| 143 |
model=ASR_MODEL_NAME,
|
|
@@ -167,34 +166,26 @@ class FileProcessor:
|
|
| 167 |
|
| 168 |
try:
|
| 169 |
if len(content) > MAX_FILE_SIZE:
|
| 170 |
-
gaia_logger.warning(f"File '{filename_str}' exceeds max size {MAX_FILE_SIZE} bytes.")
|
| 171 |
return f"Error: File '{filename_str}' exceeds maximum allowed size ({MAX_FILE_SIZE // (1024*1024)}MB)."
|
| 172 |
|
| 173 |
if 'csv' in content_type_str or filename_str.endswith('.csv'):
|
| 174 |
-
gaia_logger.info(f"Processing CSV file: {filename_str}")
|
| 175 |
return FileProcessor._process_csv(content, filename_str)
|
| 176 |
elif 'json' in content_type_str or filename_str.endswith('.json'):
|
| 177 |
-
gaia_logger.info(f"Processing JSON file: {filename_str}")
|
| 178 |
return FileProcessor._process_json(content, filename_str)
|
| 179 |
elif ('excel' in content_type_str or 'spreadsheetml' in content_type_str or \
|
| 180 |
-
filename_str.endswith(('.xlsx', '.xls'))) and openpyxl:
|
| 181 |
-
gaia_logger.info(f"Processing Excel file: {filename_str}")
|
| 182 |
return FileProcessor._process_excel(content, filename_str)
|
| 183 |
-
elif ('pdf' in content_type_str or filename_str.endswith('.pdf')) and pdfplumber:
|
| 184 |
-
gaia_logger.info(f"Processing PDF file: {filename_str}")
|
| 185 |
return FileProcessor._process_pdf(content, filename_str)
|
| 186 |
elif ('audio' in content_type_str or \
|
| 187 |
filename_str.endswith(('.mp3', '.wav', '.flac', '.ogg', '.m4a'))) and \
|
| 188 |
-
hf_transformers_pipeline and librosa:
|
| 189 |
-
gaia_logger.info(f"Processing Audio file: {filename_str}")
|
| 190 |
return FileProcessor._process_audio(content, filename_str)
|
| 191 |
elif 'text/plain' in content_type_str or \
|
| 192 |
('text/' in content_type_str and not any(sub in content_type_str for sub in ['html', 'xml'])) or \
|
| 193 |
filename_str.endswith(('.txt', '.md', '.py', '.js', '.c', '.cpp', '.java', '.html', '.xml', '.log')):
|
| 194 |
-
gaia_logger.info(f"Processing Text-like file: {filename_str} (Content-Type: {content_type_str})")
|
| 195 |
return FileProcessor._process_text(content, filename_str)
|
| 196 |
else:
|
| 197 |
-
gaia_logger.info(f"Handling unknown/binary file type: {filename_str} (Content-Type: {content_type_str})")
|
| 198 |
return FileProcessor._handle_unknown_type(content, filename_str)
|
| 199 |
except Exception as e:
|
| 200 |
gaia_logger.error(f"File processing error for '{filename_str}': {str(e)}", exc_info=True)
|
|
@@ -210,9 +201,10 @@ class FileProcessor:
|
|
| 210 |
|
| 211 |
@staticmethod
|
| 212 |
def _process_csv(content: bytes, filename: str) -> str:
|
|
|
|
|
|
|
| 213 |
try:
|
| 214 |
encodings_to_try = ['utf-8', 'latin1', 'iso-8859-1', 'cp1252']
|
| 215 |
-
df = None
|
| 216 |
for enc in encodings_to_try:
|
| 217 |
try:
|
| 218 |
df = pd.read_csv(io.BytesIO(content), encoding=enc)
|
|
@@ -221,19 +213,30 @@ class FileProcessor:
|
|
| 221 |
except Exception: continue
|
| 222 |
if df is None: return f"Error: Could not decode CSV '{filename}'."
|
| 223 |
|
| 224 |
-
num_rows, num_cols = len(df), len(df.columns)
|
| 225 |
-
cols_str = ', '.join(df.columns)
|
| 226 |
-
sample_str = df.head(CSV_SAMPLE_ROWS).to_markdown(index=False)
|
| 227 |
summary = (
|
| 228 |
-
f"CSV Document Summary: '{filename}' ({
|
| 229 |
-
f"Columns: {
|
| 230 |
)
|
| 231 |
return FileProcessor._truncate_text(summary, filename, "CSV")
|
| 232 |
-
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
return f"Error processing CSV '{filename}': {str(e)}"
|
| 234 |
|
|
|
|
| 235 |
@staticmethod
|
| 236 |
def _process_json(content: bytes, filename: str) -> str:
|
|
|
|
| 237 |
try:
|
| 238 |
decoded_content = content.decode('utf-8', errors='replace')
|
| 239 |
data = json.loads(decoded_content)
|
|
@@ -248,6 +251,7 @@ class FileProcessor:
|
|
| 248 |
|
| 249 |
@staticmethod
|
| 250 |
def _process_text(content: bytes, filename: str) -> str:
|
|
|
|
| 251 |
try:
|
| 252 |
text = None
|
| 253 |
encodings_to_try = ['utf-8', 'latin1', 'iso-8859-1', 'cp1252']
|
|
@@ -265,33 +269,59 @@ class FileProcessor:
|
|
| 265 |
|
| 266 |
@staticmethod
|
| 267 |
def _process_excel(content: bytes, filename: str) -> str:
|
|
|
|
| 268 |
if not openpyxl: return f"Error: Excel processing skipped for '{filename}', openpyxl library not available."
|
|
|
|
|
|
|
| 269 |
try:
|
| 270 |
-
# Reading all sheets and summarizing; can be adjusted for first sheet or specific sheets
|
| 271 |
xls = pd.ExcelFile(io.BytesIO(content), engine='openpyxl')
|
| 272 |
summary_parts = [f"Excel Document Summary: '{filename}'"]
|
| 273 |
for sheet_name in xls.sheet_names:
|
| 274 |
df = xls.parse(sheet_name)
|
| 275 |
-
|
| 276 |
-
cols_str = ', '.join(df.columns)
|
| 277 |
-
sample_str = df.head(CSV_SAMPLE_ROWS).to_markdown(index=False)
|
| 278 |
sheet_summary = (
|
| 279 |
-
f"\n---\nSheet: '{sheet_name}' ({
|
| 280 |
-
f"Columns: {
|
| 281 |
)
|
| 282 |
summary_parts.append(sheet_summary)
|
| 283 |
-
|
| 284 |
-
if sum(len(p) for p in summary_parts) > MAX_FILE_CONTEXT_LENGTH * 0.8: # Soft limit before final truncate
|
| 285 |
summary_parts.append("\n... (further sheets omitted due to length)")
|
| 286 |
break
|
| 287 |
full_summary = "".join(summary_parts)
|
| 288 |
return FileProcessor._truncate_text(full_summary, filename, "Excel")
|
| 289 |
-
except Exception as e:
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
return f"Error processing Excel file '{filename}': {str(e)}"
|
| 292 |
|
| 293 |
@staticmethod
|
| 294 |
def _process_pdf(content: bytes, filename: str) -> str:
|
|
|
|
| 295 |
if not pdfplumber: return f"Error: PDF processing skipped for '{filename}', pdfplumber library not available."
|
| 296 |
text_content = ""
|
| 297 |
try:
|
|
@@ -301,46 +331,67 @@ class FileProcessor:
|
|
| 301 |
page_text = page.extract_text()
|
| 302 |
if page_text:
|
| 303 |
text_content += page_text + "\n"
|
| 304 |
-
if len(text_content) > MAX_FILE_CONTEXT_LENGTH * 1.2:
|
| 305 |
-
gaia_logger.info(f"PDF '{filename}' text extraction stopped early due to length at page {i+1}.")
|
| 306 |
break
|
| 307 |
if not text_content:
|
| 308 |
return f"PDF Document: '{filename}'. No text could be extracted or PDF is empty."
|
| 309 |
summary = f"PDF Document: '{filename}':\n{text_content}"
|
| 310 |
return FileProcessor._truncate_text(summary, filename, "PDF")
|
| 311 |
except Exception as e:
|
| 312 |
-
gaia_logger.error(f"PDF processing error for '{filename}': {str(e)}", exc_info=True)
|
| 313 |
return f"Error processing PDF file '{filename}': {str(e)}"
|
| 314 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
@staticmethod
|
| 316 |
def _process_audio(content: bytes, filename: str) -> str:
|
| 317 |
-
|
| 318 |
-
|
|
|
|
| 319 |
return f"Error: Audio processing skipped for '{filename}', ASR pipeline not available."
|
| 320 |
if not librosa:
|
| 321 |
return f"Error: Audio processing skipped for '{filename}', librosa library not available."
|
|
|
|
| 322 |
try:
|
| 323 |
with io.BytesIO(content) as audio_buffer:
|
| 324 |
y, sr = librosa.load(audio_buffer, sr=16000, mono=True)
|
| 325 |
|
| 326 |
-
|
|
|
|
| 327 |
start_time = time.time()
|
| 328 |
-
|
| 329 |
-
transcription_result = asr_pipeline(y, generate_kwargs={"task": "transcribe", "language": "en"})
|
| 330 |
-
end_time = time.time()
|
| 331 |
-
gaia_logger.info(f"Audio transcription for '{filename}' took {end_time - start_time:.2f} seconds.")
|
| 332 |
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
|
| 335 |
if not transcribed_text.strip():
|
| 336 |
-
return f"Audio Document: '{filename}'. Transcription result was empty."
|
| 337 |
|
| 338 |
summary = f"Audio Document (Transcription): '{filename}':\n{transcribed_text}"
|
| 339 |
return FileProcessor._truncate_text(summary, filename, "Audio Transcription")
|
|
|
|
| 340 |
except Exception as e:
|
| 341 |
gaia_logger.error(f"Audio processing/transcription error for '{filename}': {str(e)}", exc_info=True)
|
| 342 |
return f"Error processing Audio file '{filename}': {str(e)}"
|
| 343 |
|
|
|
|
| 344 |
@staticmethod
|
| 345 |
def _handle_unknown_type(content: bytes, filename: str) -> str:
|
| 346 |
gaia_logger.warning(f"Attempting to handle unknown file type for '{filename}' as text snippet.")
|
|
@@ -351,7 +402,7 @@ class FileProcessor:
|
|
| 351 |
except Exception:
|
| 352 |
return f"File with Unknown Content Type: '{filename}'. Content is likely binary and cannot be displayed as text."
|
| 353 |
|
| 354 |
-
class CacheManager:
|
| 355 |
def __init__(self, ttl: int = 300, max_size: int = 100, name: str = "Cache"):
|
| 356 |
self.ttl = ttl; self.max_size = max_size
|
| 357 |
self._cache: Dict[Any, Any] = {}; self._timestamps: Dict[Any, float] = {}
|
|
@@ -361,13 +412,10 @@ class CacheManager:
|
|
| 361 |
if key in self._cache and (time.time() - self._timestamps.get(key, 0) < self.ttl):
|
| 362 |
try:
|
| 363 |
self._access_order.remove(key); self._access_order.append(key)
|
| 364 |
-
gaia_logger.debug(f"[{self.name}] Cache hit: {str(key)[:100]}...")
|
| 365 |
return copy.deepcopy(self._cache[key])
|
| 366 |
except (ValueError, TypeError) as e:
|
| 367 |
-
gaia_logger.debug(f"[{self.name}] Error accessing {str(key)[:100]}: {e}")
|
| 368 |
self.delete(key); return None
|
| 369 |
elif key in self._cache:
|
| 370 |
-
gaia_logger.debug(f"[{self.name}] Cache expired: {str(key)[:100]}...")
|
| 371 |
self.delete(key)
|
| 372 |
return None
|
| 373 |
def set(self, key: Any, value: Any):
|
|
@@ -375,12 +423,10 @@ class CacheManager:
|
|
| 375 |
while len(self._cache) >= self.max_size and self._access_order:
|
| 376 |
old_key = self._access_order.pop(0)
|
| 377 |
if old_key in self._cache:
|
| 378 |
-
gaia_logger.debug(f"[{self.name}] Evicting: {str(old_key)[:100]}...")
|
| 379 |
del self._cache[old_key]; del self._timestamps[old_key]
|
| 380 |
try: self._cache[key] = copy.deepcopy(value)
|
| 381 |
except TypeError: self._cache[key] = value
|
| 382 |
self._timestamps[key] = time.time(); self._access_order.append(key)
|
| 383 |
-
gaia_logger.debug(f"[{self.name}] Cache set: {str(key)[:100]}. Size: {len(self)}")
|
| 384 |
def delete(self, key: Any):
|
| 385 |
if key in self._cache:
|
| 386 |
try:
|
|
@@ -391,28 +437,20 @@ class CacheManager:
|
|
| 391 |
def __len__(self): return len(self._cache)
|
| 392 |
def __contains__(self, key): return key in self._cache and (time.time()-self._timestamps.get(key,0)<self.ttl)
|
| 393 |
|
| 394 |
-
class SearchProvider(ABC):
|
| 395 |
def __init__(self, config_dict: Dict):
|
| 396 |
self.provider_config = config_dict.get('search', {})
|
| 397 |
-
self._enabled = False
|
| 398 |
self._quota_used = 0
|
| 399 |
-
# This call to self.provider_name will invoke the subclass's implementation.
|
| 400 |
raw_quota = self.provider_config.get(f'{self.provider_name.lower()}_quota', float('inf'))
|
| 401 |
self._quota_limit = float(raw_quota) if raw_quota is not None else float('inf')
|
| 402 |
-
|
| 403 |
@property
|
| 404 |
@abstractmethod
|
| 405 |
-
def provider_name(self) -> str:
|
| 406 |
-
pass
|
| 407 |
-
|
| 408 |
@abstractmethod
|
| 409 |
-
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 410 |
-
pass
|
| 411 |
-
|
| 412 |
def search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 413 |
-
if not self._enabled:
|
| 414 |
-
gaia_logger.debug(f"[{self.provider_name}] Skip: Not enabled.")
|
| 415 |
-
return None
|
| 416 |
if self._quota_limit != float('inf') and self._quota_used >= self._quota_limit:
|
| 417 |
gaia_logger.warning(f"[{self.provider_name}] Skip: Quota ({self._quota_used}/{int(self._quota_limit)})")
|
| 418 |
return None
|
|
@@ -422,371 +460,230 @@ class SearchProvider(ABC):
|
|
| 422 |
usage_str = f"({self._quota_used}/{int(self._quota_limit)}) "
|
| 423 |
gaia_logger.info(f"[{self.provider_name}] {usage_str}Search: '{query[:70]}...'")
|
| 424 |
return self._perform_search(query, max_results)
|
|
|
|
| 425 |
|
| 426 |
-
|
| 427 |
-
return self._enabled
|
| 428 |
-
|
| 429 |
-
class GoogleProvider(SearchProvider):
|
| 430 |
@property
|
| 431 |
-
def provider_name(self) -> str:
|
| 432 |
-
return "Google"
|
| 433 |
-
|
| 434 |
def __init__(self, config_dict: Dict):
|
| 435 |
-
super().__init__(config_dict)
|
| 436 |
self._api_key = self.provider_config.get("google_api_key")
|
| 437 |
self._cse_id = self.provider_config.get("google_cse_id")
|
| 438 |
self._timeout = self.provider_config.get("google_timeout", 8)
|
| 439 |
-
if self._api_key and self._cse_id:
|
| 440 |
-
|
| 441 |
-
gaia_logger.info(f"✓ {self.provider_name} API configured.")
|
| 442 |
-
else:
|
| 443 |
-
self._enabled = False # Explicitly ensure it's false if keys are missing
|
| 444 |
-
gaia_logger.warning(f"✗ {self.provider_name} API key/CSE ID missing in RAG config.")
|
| 445 |
-
|
| 446 |
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 447 |
try:
|
| 448 |
-
params = {
|
| 449 |
-
|
| 450 |
-
'cx': self._cse_id,
|
| 451 |
-
'q': query,
|
| 452 |
-
'num': max_results,
|
| 453 |
-
'safe': 'active'
|
| 454 |
-
}
|
| 455 |
-
response = requests.get(
|
| 456 |
-
"https://www.googleapis.com/customsearch/v1",
|
| 457 |
-
params=params,
|
| 458 |
-
timeout=self._timeout
|
| 459 |
-
)
|
| 460 |
response.raise_for_status()
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
'body': i.get('snippet', '')
|
| 470 |
-
} for i in items]
|
| 471 |
-
except requests.exceptions.Timeout:
|
| 472 |
-
gaia_logger.warning(f"[{self.provider_name}] Timeout: '{query[:70]}'")
|
| 473 |
-
return None
|
| 474 |
-
except requests.exceptions.RequestException as e:
|
| 475 |
-
gaia_logger.warning(f"[{self.provider_name}] RequestEx: '{query[:70]}': {e}")
|
| 476 |
-
return None
|
| 477 |
-
except Exception as e:
|
| 478 |
-
gaia_logger.error(f"[{self.provider_name}] Error: '{query[:70]}': {e}", exc_info=True)
|
| 479 |
-
return None
|
| 480 |
-
|
| 481 |
-
class TavilyProvider(SearchProvider):
|
| 482 |
@property
|
| 483 |
-
def provider_name(self) -> str:
|
| 484 |
-
return "Tavily"
|
| 485 |
-
|
| 486 |
def __init__(self, config_dict: Dict):
|
| 487 |
-
super().__init__(config_dict)
|
| 488 |
self._api_key = self.provider_config.get("tavily_api_key")
|
| 489 |
self._search_depth = self.provider_config.get("tavily_depth", "basic")
|
| 490 |
if self._api_key and TavilyClient:
|
| 491 |
-
try:
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
except Exception as e:
|
| 496 |
-
self._enabled = False # Explicitly ensure it's false on init fail
|
| 497 |
-
gaia_logger.warning(f"✗ {self.provider_name} init fail: {e}", exc_info=False)
|
| 498 |
-
elif not TavilyClient:
|
| 499 |
-
self._enabled = False # Explicitly ensure it's false if lib missing
|
| 500 |
-
gaia_logger.warning(f"✗ {self.provider_name}: TavilyClient lib missing.")
|
| 501 |
-
else:
|
| 502 |
-
self._enabled = False # Explicitly ensure it's false if API key missing
|
| 503 |
-
gaia_logger.warning(f"✗ {self.provider_name}: API key missing in RAG config.")
|
| 504 |
-
|
| 505 |
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 506 |
-
if not self._enabled: return None
|
| 507 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
response = self._client.search(query=query, max_results=max_results, search_depth=self._search_depth)
|
| 509 |
hits = response.get('results', [])
|
| 510 |
-
if not hits:
|
| 511 |
return [{'href': h.get('url'), 'title': h.get('title',''), 'body': h.get('content','')} for h in hits]
|
| 512 |
except Exception as e: gaia_logger.warning(f"[{self.provider_name}] Search fail: '{query[:70]}': {e}"); return None
|
| 513 |
|
| 514 |
-
class DuckDuckGoProvider(SearchProvider):
|
| 515 |
@property
|
| 516 |
-
def provider_name(self) -> str:
|
| 517 |
-
return "DuckDuckGo"
|
| 518 |
-
|
| 519 |
def __init__(self, config_dict: Dict):
|
| 520 |
-
super().__init__(config_dict)
|
| 521 |
if DDGS:
|
| 522 |
-
try:
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
gaia_logger.info(f"✓ {self.provider_name} Search initialized.")
|
| 526 |
-
except Exception as e:
|
| 527 |
-
self._enabled = False # Explicitly ensure it's false on init fail
|
| 528 |
-
gaia_logger.warning(f"✗ {self.provider_name} init fail: {e}", exc_info=False)
|
| 529 |
-
else:
|
| 530 |
-
self._enabled = False # Explicitly ensure it's false if lib missing
|
| 531 |
-
gaia_logger.warning(f"✗ {self.provider_name}: DDGS lib missing.")
|
| 532 |
-
|
| 533 |
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 534 |
-
if not self._enabled: return None
|
| 535 |
try:
|
| 536 |
hits = list(self._client.text(query, region='wt-wt', max_results=max_results))[:max_results]
|
| 537 |
-
if not hits:
|
| 538 |
return [{'href': r.get('href'), 'title': r.get('title',''), 'body': r.get('body','')} for r in hits]
|
| 539 |
except Exception as e: gaia_logger.warning(f"[{self.provider_name}] Search fail: '{query[:70]}': {e}"); return None
|
| 540 |
|
| 541 |
-
class CompositeSearchClient:
|
| 542 |
def __init__(self, config_dict: Dict):
|
| 543 |
self.config = config_dict
|
| 544 |
self._search_config = config_dict.get('search', {})
|
| 545 |
self.providers = self._init_providers(config_dict)
|
| 546 |
self.cache = CacheManager(
|
| 547 |
ttl=config_dict.get('caching', {}).get('search_cache_ttl', 300),
|
| 548 |
-
max_size=config_dict.get('caching', {}).get('search_cache_size', 50),
|
| 549 |
-
name="SearchClientCache"
|
| 550 |
)
|
| 551 |
self._retry_att = self._search_config.get("retry_attempts", 2)
|
| 552 |
self._retry_del = self._search_config.get("retry_delay", 2)
|
| 553 |
self._def_max_r = self._search_config.get("default_max_results", 3)
|
| 554 |
-
|
| 555 |
def _init_providers(self, config_dict: Dict) -> List[SearchProvider]:
|
| 556 |
providers: List[SearchProvider] = []
|
| 557 |
if TAVILY_API_KEY and TavilyClient:
|
| 558 |
tavily_prov = TavilyProvider(config_dict)
|
| 559 |
-
if tavily_prov.available():
|
| 560 |
-
providers.append(tavily_prov)
|
| 561 |
if GOOGLE_CUSTOM_SEARCH_API_KEY and GOOGLE_CUSTOM_SEARCH_CSE_ID:
|
| 562 |
google_prov = GoogleProvider(config_dict)
|
| 563 |
-
if google_prov.available():
|
| 564 |
-
providers.append(google_prov)
|
| 565 |
if DDGS:
|
| 566 |
ddgs_prov = DuckDuckGoProvider(config_dict)
|
| 567 |
-
if ddgs_prov.available():
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
gaia_logger.error("RAG: No search providers initialized!")
|
| 571 |
-
else:
|
| 572 |
-
gaia_logger.info(f"RAG Providers: {[p.provider_name for p in providers]}")
|
| 573 |
return providers
|
| 574 |
-
|
| 575 |
def search(self, query: str, max_results: Optional[int] = None, force_refresh: bool = False) -> List[Dict]:
|
| 576 |
q, actual_r = query.strip(), max_results if max_results is not None else self._def_max_r
|
| 577 |
-
if not q:
|
| 578 |
-
return []
|
| 579 |
cache_key = (q, actual_r)
|
| 580 |
-
if not force_refresh and (cached := self.cache.get(cache_key)) is not None:
|
| 581 |
-
return cached
|
| 582 |
for prov in self.providers:
|
| 583 |
for attempt in range(self._retry_att + 1):
|
| 584 |
-
if not prov.available():
|
| 585 |
-
break
|
| 586 |
try:
|
| 587 |
results = prov.search(q, actual_r)
|
| 588 |
-
if results is not None:
|
| 589 |
-
|
| 590 |
-
return results
|
| 591 |
-
gaia_logger.warning(f"[{prov.provider_name}] search None: '{q[:50]}' (att {attempt+1})")
|
| 592 |
-
if attempt < self._retry_att:
|
| 593 |
-
time.sleep(self._retry_del)
|
| 594 |
except Exception as e:
|
| 595 |
-
|
| 596 |
-
if attempt < self._retry_att:
|
| 597 |
-
time.sleep(self._retry_del)
|
| 598 |
-
gaia_logger.error(f"RAG: All providers failed for query: '{q[:50]}'.")
|
| 599 |
self.cache.set(cache_key, [])
|
| 600 |
return []
|
| 601 |
|
| 602 |
-
class GaiaQueryBuilder:
|
| 603 |
def __init__(self, base_query: str, config_dict: Dict):
|
| 604 |
self.base_query = base_query.strip()
|
| 605 |
-
self.config = config_dict
|
| 606 |
-
gaia_logger.debug(f"GaiaQueryBuilder init: '{self.base_query[:100]}'")
|
| 607 |
-
|
| 608 |
def get_queries(self) -> Dict[str, List[Tuple[str, str]]]:
|
| 609 |
-
|
| 610 |
-
gaia_logger.debug(f"RAG Generated queries: {queries}")
|
| 611 |
-
return queries
|
| 612 |
|
| 613 |
-
class ResultProcessor:
|
| 614 |
def __init__(self, config_dict: Dict):
|
| 615 |
self.proc_config = config_dict.get('processing', {})
|
| 616 |
self.trusted_sources = self.proc_config.get('trusted_sources', {})
|
| 617 |
self.seen_urls: Set[str] = set()
|
| 618 |
self.date_pattern = DEFAULT_RAG_CONFIG['processing'].get('date_pattern', r'\b\d{4}\b')
|
| 619 |
-
gaia_logger.debug("RAG ResultProcessor initialized.")
|
| 620 |
-
|
| 621 |
def process_batch(self, results: List[Dict], query_tag: str, initial_cat: str='GENERAL') -> List[Dict]:
|
| 622 |
processed: List[Dict] = []
|
| 623 |
-
if not results:
|
| 624 |
-
return processed
|
| 625 |
for r in results:
|
| 626 |
url = r.get('href')
|
| 627 |
-
if not url or self._normalize_url(url) in self.seen_urls:
|
| 628 |
-
continue
|
| 629 |
self.seen_urls.add(self._normalize_url(url))
|
| 630 |
-
res_data = {
|
| 631 |
-
'title': r.get('title',''),
|
| 632 |
-
'body': r.get('body',''),
|
| 633 |
-
'href': url,
|
| 634 |
-
'query_tag': query_tag,
|
| 635 |
-
'category': initial_cat,
|
| 636 |
-
'source_quality': 0.5,
|
| 637 |
-
'temporal_relevance': 0.1,
|
| 638 |
-
'combined_score': 0.0
|
| 639 |
-
}
|
| 640 |
self._score_result(res_data)
|
| 641 |
processed.append(res_data)
|
| 642 |
-
gaia_logger.debug(f"[RAG Proc] Batch: {len(processed)} new results from '{query_tag}'")
|
| 643 |
return processed
|
| 644 |
-
|
| 645 |
-
def _normalize_url(self, url: str) -> str:
|
| 646 |
-
return re.sub(r'^https?://(?:www\.)?', '', str(url)).rstrip('/') if url else ""
|
| 647 |
-
|
| 648 |
def _score_result(self, result: Dict):
|
| 649 |
url, body, title = result.get('href', ''), result.get('body', ''), result.get('title', '')
|
| 650 |
source_q = 0.5
|
| 651 |
-
if domain_match := re.search(r'https?://(?:www\.)?([^/]+)', url or ""):
|
| 652 |
-
source_q = self.trusted_sources.get(domain_match.group(1), 0.5)
|
| 653 |
result['source_quality'] = source_q
|
| 654 |
-
temporal_r = 0.1
|
| 655 |
-
text_combo
|
| 656 |
-
|
| 657 |
-
temporal_r = 0.9
|
| 658 |
-
elif re.search(self.date_pattern, text_combo):
|
| 659 |
-
temporal_r = 0.5
|
| 660 |
result['temporal_relevance'] = temporal_r
|
| 661 |
result['combined_score'] = (source_q * 0.6 + temporal_r * 0.4)
|
| 662 |
|
| 663 |
-
class ContentEnricher:
|
| 664 |
def __init__(self, config_dict: Dict):
|
| 665 |
self.enrich_config = config_dict.get('enrichment', {})
|
| 666 |
self._enabled = self.enrich_config.get('enabled', False) and bool(BeautifulSoup)
|
| 667 |
-
if not self._enabled:
|
| 668 |
-
gaia_logger.warning("RAG ContentEnricher disabled (BeautifulSoup missing or config).")
|
| 669 |
-
return
|
| 670 |
self._timeout = self.enrich_config.get('timeout', 10)
|
| 671 |
self._max_w = self.enrich_config.get('workers', 3)
|
| 672 |
self._min_l, self._max_l = self.enrich_config.get('min_text_length', 200), self.enrich_config.get('max_text_length', 8000)
|
| 673 |
self._skip_ext = tuple(self.enrich_config.get('skip_extensions', []))
|
| 674 |
-
self.cache = CacheManager(
|
| 675 |
-
ttl=config_dict.get('caching', {}).get('enrich_cache_ttl', 600),
|
| 676 |
-
max_size=config_dict.get('caching', {}).get('enrich_cache_size', 25),
|
| 677 |
-
name="EnrichCache"
|
| 678 |
-
)
|
| 679 |
gaia_logger.info(f"RAG ContentEnricher Initialized. Enabled: {self._enabled}")
|
| 680 |
-
|
| 681 |
def enrich_batch(self, results: List[Dict], force_refresh: bool = False) -> List[Dict]:
|
| 682 |
-
if not self._enabled or not results:
|
| 683 |
-
return results
|
| 684 |
updated_res = []
|
| 685 |
with ThreadPoolExecutor(max_workers=self._max_w) as executor:
|
| 686 |
future_map = {executor.submit(self._fetch_single, r, force_refresh): r for r in results}
|
| 687 |
-
for future in as_completed(future_map):
|
| 688 |
-
updated_res.append(future.result())
|
| 689 |
return updated_res
|
| 690 |
-
|
| 691 |
def _fetch_single(self, result: Dict, force_refresh: bool) -> Dict:
|
| 692 |
-
url = result.get('href')
|
| 693 |
-
result
|
| 694 |
-
result.setdefault('enrichment_failed', None)
|
| 695 |
-
result.setdefault('enrichment_skipped_type', None)
|
| 696 |
-
if not url:
|
| 697 |
-
result['enrichment_skipped_type'] = 'no_url'
|
| 698 |
-
return result
|
| 699 |
if not force_refresh and (cached := self.cache.get(url)) is not None:
|
| 700 |
-
if cached:
|
| 701 |
-
|
| 702 |
-
gaia_logger.debug(f"[Enrich] Cache hit: {url}")
|
| 703 |
-
return result
|
| 704 |
-
if url.lower().endswith(self._skip_ext):
|
| 705 |
-
result['enrichment_skipped_type'] = 'extension'
|
| 706 |
-
return result
|
| 707 |
try:
|
| 708 |
headers = {'User-Agent': 'Mozilla/5.0 GaiaRAGAgent/1.0'}
|
| 709 |
response = requests.get(url, headers=headers, timeout=self._timeout, allow_redirects=True)
|
| 710 |
response.raise_for_status()
|
| 711 |
-
if 'text/html' not in response.headers.get('Content-Type', '').lower():
|
| 712 |
-
result['enrichment_skipped_type'] = 'non-html'
|
| 713 |
-
return result
|
| 714 |
soup = BeautifulSoup(response.text, 'lxml')
|
| 715 |
for el_name in ["script", "style", "nav", "header", "footer", "aside", "form", "iframe", "img", "svg", ".ad", ".advertisement"]:
|
| 716 |
-
for el in soup.select(el_name):
|
| 717 |
-
el.decompose()
|
| 718 |
main_el = soup.select_one('article, main, [role="main"], .entry-content, .post-content, #content, #main') or soup.body
|
| 719 |
text = main_el.get_text(separator='\n', strip=True) if main_el else ""
|
| 720 |
text = re.sub(r'(\s*\n\s*){2,}', '\n\n', text).strip()
|
| 721 |
if len(text) >= self._min_l:
|
| 722 |
result['body'] = text[:self._max_l] + ("..." if len(text) > self._max_l else "")
|
| 723 |
-
result['enriched'] = True
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
else:
|
| 727 |
-
result['enrichment_failed'] = 'too_short'
|
| 728 |
-
except Exception as e:
|
| 729 |
-
result['enrichment_failed'] = type(e).__name__
|
| 730 |
-
gaia_logger.warning(f"[Enrich] Fail: {url}: {e}", exc_info=False)
|
| 731 |
return result
|
| 732 |
|
| 733 |
-
class GeneralRAGPipeline:
|
| 734 |
def __init__(self, config_dict: Optional[Dict] = None):
|
| 735 |
self.config = config_dict if config_dict is not None else DEFAULT_RAG_CONFIG
|
| 736 |
self.search_client = CompositeSearchClient(self.config)
|
| 737 |
enrich_cfg = self.config.get('enrichment', {})
|
| 738 |
self.enricher = ContentEnricher(self.config) if enrich_cfg.get('enabled', False) and BeautifulSoup else None
|
| 739 |
-
if not self.enricher:
|
| 740 |
-
|
| 741 |
-
self.pipeline_cache = CacheManager(
|
| 742 |
-
ttl=self.config.get('caching', {}).get('analyzer_cache_ttl', 3600),
|
| 743 |
-
max_size=self.config.get('caching', {}).get('analyzer_cache_size', 30),
|
| 744 |
-
name="RAGPipelineCache"
|
| 745 |
-
)
|
| 746 |
gaia_logger.info("GeneralRAGPipeline initialized.")
|
| 747 |
-
|
| 748 |
def analyze(self, query: str, force_refresh: bool = False) -> List[Dict]:
|
| 749 |
-
q = query.strip()
|
| 750 |
-
if not q:
|
| 751 |
-
return []
|
| 752 |
cfg_res, cfg_search = self.config.get('results', {}), self.config.get('search', {})
|
| 753 |
total_lim, enrich_cnt = cfg_res.get('total_limit', 3), cfg_res.get('enrich_count', 2)
|
| 754 |
enrich_en = self.config.get('enrichment', {}).get('enabled', False) and bool(self.enricher)
|
| 755 |
max_r_pq = cfg_search.get('default_max_results', 3)
|
| 756 |
cache_key = (q, max_r_pq, total_lim, enrich_en, enrich_cnt)
|
| 757 |
-
if not force_refresh and (cached := self.pipeline_cache.get(cache_key)) is not None:
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
if force_refresh:
|
| 761 |
-
self.search_client.cache.clear()
|
| 762 |
-
if self.enricher:
|
| 763 |
-
self.enricher.cache.clear()
|
| 764 |
all_res, res_proc = [], ResultProcessor(self.config)
|
| 765 |
staged_qs = GaiaQueryBuilder(q, self.config).get_queries()
|
| 766 |
for stage, qs_in_stage in staged_qs.items():
|
| 767 |
for query_s, cat in qs_in_stage:
|
| 768 |
-
if len(all_res) >= total_lim * 2:
|
| 769 |
-
break
|
| 770 |
-
gaia_logger.info(f"[RAG Analyze] Stage '{stage}': Search '{query_s[:70]}'")
|
| 771 |
s_res = self.search_client.search(query_s, max_results=max_r_pq, force_refresh=force_refresh)
|
| 772 |
all_res.extend(res_proc.process_batch(s_res or [], query_s, initial_cat=cat))
|
| 773 |
all_res.sort(key=lambda x: x.get('combined_score', 0), reverse=True)
|
| 774 |
if enrich_en and self.enricher and all_res:
|
| 775 |
to_enrich = [r for r in all_res[:enrich_cnt] if r.get('href')]
|
| 776 |
-
|
| 777 |
-
enriched_map = {
|
| 778 |
-
item['href']: item for item in self.enricher.enrich_batch(to_enrich, force_refresh=force_refresh)
|
| 779 |
-
if item.get('href')
|
| 780 |
-
}
|
| 781 |
temp_results = [enriched_map.get(r['href'], r) if r.get('href') else r for r in all_res]
|
| 782 |
-
all_res = temp_results
|
| 783 |
-
all_res.sort(key=lambda x: x.get('combined_score', 0), reverse=True)
|
| 784 |
final_results = all_res[:total_lim]
|
| 785 |
-
gaia_logger.info(f"[RAG Analyze] Done. {len(final_results)} results for '{q[:50]}'")
|
| 786 |
self.pipeline_cache.set(cache_key, final_results)
|
| 787 |
return final_results
|
| 788 |
|
| 789 |
-
|
| 790 |
class GaiaLevel1Agent:
|
| 791 |
def __init__(self, api_url: str = DEFAULT_API_URL):
|
| 792 |
self.api_url = api_url
|
|
@@ -796,9 +693,7 @@ class GaiaLevel1Agent:
|
|
| 796 |
if genai and GOOGLE_GEMINI_API_KEY:
|
| 797 |
try:
|
| 798 |
genai.configure(api_key=GOOGLE_GEMINI_API_KEY)
|
| 799 |
-
|
| 800 |
-
# and consistency with MAX_CONTEXT_LENGTH_LLM = 30000
|
| 801 |
-
model_name = 'gemini-2.0-flash'
|
| 802 |
self.llm_model = genai.GenerativeModel(model_name)
|
| 803 |
gaia_logger.info(f"Gemini LLM ('{model_name}') initialized.")
|
| 804 |
except Exception as e:
|
|
@@ -813,7 +708,6 @@ class GaiaLevel1Agent:
|
|
| 813 |
@lru_cache(maxsize=32)
|
| 814 |
def _fetch_and_process_file_content(self, task_id: str) -> Optional[str]:
|
| 815 |
file_url = f"{self.api_url}/files/{task_id}"
|
| 816 |
-
# gaia_logger.info(f"Agent fetching file from: {file_url}") # Reduced verbosity
|
| 817 |
for attempt in range(2):
|
| 818 |
try:
|
| 819 |
response = requests.get(file_url, timeout=AGENT_DEFAULT_TIMEOUT)
|
|
@@ -827,8 +721,6 @@ class GaiaLevel1Agent:
|
|
| 827 |
filename = header_filename
|
| 828 |
|
| 829 |
content_type = response.headers.get("Content-Type", "")
|
| 830 |
-
|
| 831 |
-
# gaia_logger.info(f"File downloaded: {filename}, type: {content_type}, size: {len(response.content)} bytes") # Reduced verbosity
|
| 832 |
processed_content = FileProcessor.process(response.content, filename, content_type)
|
| 833 |
return processed_content
|
| 834 |
|
|
@@ -845,19 +737,43 @@ class GaiaLevel1Agent:
|
|
| 845 |
if attempt < 1: time.sleep(1)
|
| 846 |
return None
|
| 847 |
|
| 848 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 849 |
if not self.llm_model:
|
| 850 |
gaia_logger.warning("LLM model (Gemini) not available for answer formulation.")
|
| 851 |
-
|
|
|
|
| 852 |
if web_context and file_context:
|
| 853 |
-
|
| 854 |
elif web_context:
|
| 855 |
-
|
| 856 |
elif file_context:
|
| 857 |
-
|
| 858 |
-
|
|
|
|
|
|
|
| 859 |
|
| 860 |
-
# --- NEW PROMPT STRUCTURE ---
|
| 861 |
prompt_parts = [
|
| 862 |
"You are a general AI assistant. Your primary goal is to answer the user's question accurately and concisely based *only* on the provided context (from a document and/or web search results).",
|
| 863 |
"First, think step-by-step and briefly explain your reasoning based on the context. This part is for clarity and should come before your final answer.",
|
|
@@ -870,18 +786,16 @@ class GaiaLevel1Agent:
|
|
| 870 |
"Prioritize information from 'Enriched Content' from web search results if available and relevant over shorter 'Snippets'.",
|
| 871 |
"\nUser Question: ", question
|
| 872 |
]
|
| 873 |
-
# --- END OF NEW PROMPT STRUCTURE HEAD ---
|
| 874 |
|
| 875 |
current_prompt_text_len = sum(len(p) for p in prompt_parts)
|
| 876 |
|
| 877 |
-
# Context preparation (similar to before, but ensure it fits with new prompt instructions)
|
| 878 |
context_added = False
|
| 879 |
if file_context:
|
| 880 |
file_header = "\n\nContext from Provided Document:\n---"
|
| 881 |
file_footer = "\n---"
|
| 882 |
-
max_len_for_file = MAX_CONTEXT_LENGTH_LLM - current_prompt_text_len - (len(web_context) if web_context else 0) - len(file_header) - len(file_footer) - 500
|
| 883 |
|
| 884 |
-
if max_len_for_file > 100 :
|
| 885 |
truncated_file_context = file_context[:max_len_for_file]
|
| 886 |
if len(file_context) > len(truncated_file_context):
|
| 887 |
truncated_file_context += " ... (file context truncated)"
|
|
@@ -895,10 +809,9 @@ class GaiaLevel1Agent:
|
|
| 895 |
if web_context:
|
| 896 |
web_header = "\n\nContext from Web Search Results:\n---"
|
| 897 |
web_footer = "\n---"
|
| 898 |
-
|
| 899 |
-
available_len_for_web = MAX_CONTEXT_LENGTH_LLM - current_prompt_text_len - len(web_header) - len(web_footer) - 300 # Buffer for answer instructions
|
| 900 |
|
| 901 |
-
if available_len_for_web > 100:
|
| 902 |
truncated_web_context = web_context
|
| 903 |
if len(web_context) > available_len_for_web:
|
| 904 |
truncated_web_context = web_context[:available_len_for_web] + "\n... (web context truncated)"
|
|
@@ -910,10 +823,10 @@ class GaiaLevel1Agent:
|
|
| 910 |
gaia_logger.warning("Not enough space for web context in LLM prompt, or web context itself is empty.")
|
| 911 |
|
| 912 |
|
| 913 |
-
if not context_added:
|
| 914 |
prompt_parts.append("\n\nNo document or web context could be provided due to length constraints or availability.")
|
| 915 |
|
| 916 |
-
prompt_parts.append("\n\nReasoning and Final Answer:")
|
| 917 |
final_prompt = "\n".join(prompt_parts)
|
| 918 |
|
| 919 |
gaia_logger.info(f"LLM Prompt (first 300): {final_prompt[:300]}...")
|
|
@@ -922,15 +835,14 @@ class GaiaLevel1Agent:
|
|
| 922 |
|
| 923 |
if not GenerationConfig:
|
| 924 |
gaia_logger.error("GenerationConfig not available. Cannot make LLM call.")
|
| 925 |
-
return "
|
| 926 |
|
| 927 |
try:
|
| 928 |
gen_config = GenerationConfig(
|
| 929 |
-
temperature=0.1,
|
| 930 |
-
top_p=0.95,
|
| 931 |
-
max_output_tokens=2048
|
| 932 |
)
|
| 933 |
-
# Safety settings remain the same
|
| 934 |
safety_set = [{"category": c, "threshold": "BLOCK_MEDIUM_AND_ABOVE"} for c in ["HARM_CATEGORY_HARASSMENT", "HARM_CATEGORY_HATE_SPEECH", "HARM_CATEGORY_SEXUALLY_EXPLICIT", "HARM_CATEGORY_DANGEROUS_CONTENT"]]
|
| 935 |
|
| 936 |
response = self.llm_model.generate_content(
|
|
@@ -940,59 +852,38 @@ class GaiaLevel1Agent:
|
|
| 940 |
)
|
| 941 |
|
| 942 |
if not response.candidates or (hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason):
|
| 943 |
-
|
| 944 |
if hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason:
|
| 945 |
-
|
| 946 |
-
gaia_logger.warning(f"Gemini response blocked. Reason: {
|
| 947 |
-
|
| 948 |
-
return f"My response was blocked (Reason: {reason}). FINAL ANSWER: Error processing request."
|
| 949 |
|
| 950 |
-
|
| 951 |
-
gaia_logger.info(f"LLM Full Answer (first 200): {
|
| 952 |
|
| 953 |
-
|
| 954 |
-
# If not, we might need to append it or re-prompt, but for now, let's see how well the LLM adheres.
|
| 955 |
-
if "FINAL ANSWER:" not in llm_answer:
|
| 956 |
-
gaia_logger.warning("LLM did not produce 'FINAL ANSWER:' template. Appending based on full response.")
|
| 957 |
-
# This is a fallback, ideally the LLM follows the prompt.
|
| 958 |
-
# For a GAIA contest, just returning the raw text might be safer if it's mostly the answer.
|
| 959 |
-
# Or, if the answer is consistently the last part:
|
| 960 |
-
# lines = llm_answer.strip().split('\n')
|
| 961 |
-
# simple_final_answer = lines[-1] if lines else "Could not extract answer"
|
| 962 |
-
# return f"LLM output did not follow template. Attempted extraction: FINAL ANSWER: {simple_final_answer}"
|
| 963 |
-
# For now, let the raw output pass, as it might contain partial reasoning + answer.
|
| 964 |
-
# The strictness of GAIA might penalize this more than a missing template from the LLM.
|
| 965 |
-
# The prompt is very explicit, so the LLM *should* follow it.
|
| 966 |
-
pass # Let raw LLM output through if it misses the template for now.
|
| 967 |
-
|
| 968 |
-
return llm_answer
|
| 969 |
|
| 970 |
except Exception as e:
|
| 971 |
gaia_logger.error(f"Error calling Gemini API: {e}", exc_info=True)
|
| 972 |
error_type_name = type(e).__name__
|
|
|
|
|
|
|
| 973 |
if "429" in str(e) or "ResourceExhausted" in error_type_name:
|
| 974 |
-
|
| 975 |
-
|
|
|
|
| 976 |
|
| 977 |
-
def __call__(self, question: str, task_id: Optional[str] = None) -> str:
|
| 978 |
-
# This part remains largely the same, as it's about gathering context
|
| 979 |
-
# The _formulate_answer_with_llm will now use the new prompt
|
| 980 |
gaia_logger.info(f"Agent processing: '{question[:70]}...', TaskID: {task_id}")
|
| 981 |
q_lower = question.lower().strip()
|
| 982 |
|
| 983 |
-
# Simple canned response - ensure it also follows the new format if strictly needed,
|
| 984 |
-
# but this is usually for agent identity, not a GAIA scored question.
|
| 985 |
-
# For GAIA, it might be better to let the LLM answer this with context if any.
|
| 986 |
-
# However, if this is a hardcoded check:
|
| 987 |
if "what is your name" in q_lower or "who are you" in q_lower:
|
| 988 |
-
return "
|
| 989 |
|
| 990 |
|
| 991 |
file_ctx_str: Optional[str] = None
|
| 992 |
-
# Expanded keywords slightly for more robust file-related question detection
|
| 993 |
file_kws = ["document", "file", "text", "provide", "attach", "read", "content", "table", "data", "excel", "pdf", "audio", "code", "script", "log"]
|
| 994 |
-
|
| 995 |
-
if task_id and (any(kw in q_lower for kw in file_kws) or "this task involves a file" in q_lower): # Hypothetical trigger
|
| 996 |
file_ctx_str = self._fetch_and_process_file_content(task_id)
|
| 997 |
if file_ctx_str:
|
| 998 |
gaia_logger.info(f"Processed file context ({len(file_ctx_str)} chars) for task {task_id}")
|
|
@@ -1001,14 +892,11 @@ class GaiaLevel1Agent:
|
|
| 1001 |
|
| 1002 |
web_ctx_str: Optional[str] = None
|
| 1003 |
needs_web = True
|
| 1004 |
-
|
| 1005 |
-
if file_ctx_str and len(file_ctx_str) > 300: # If file context is somewhat substantial
|
| 1006 |
-
# Keywords that strongly suggest a web search is still needed
|
| 1007 |
web_still_needed_kws = [
|
| 1008 |
"what is", "who is", "current", "latest", "news", "public opinion",
|
| 1009 |
"recent events", "search for", "find information on", "browse", "look up"
|
| 1010 |
]
|
| 1011 |
-
# Keywords that might be answerable from a good document
|
| 1012 |
doc_can_answer_kws = ["summarize", "according to the document", "in the provided text"]
|
| 1013 |
|
| 1014 |
if any(kw in q_lower for kw in doc_can_answer_kws) and not any(kw in q_lower for kw in web_still_needed_kws):
|
|
@@ -1024,10 +912,8 @@ class GaiaLevel1Agent:
|
|
| 1024 |
|
| 1025 |
if needs_web:
|
| 1026 |
search_q = question.replace("?", "").strip()
|
| 1027 |
-
# Tavily query length is handled within TavilyProvider now.
|
| 1028 |
-
# No general truncation here unless other providers also show issues.
|
| 1029 |
gaia_logger.info(f"RAG Pipeline initiated for query: {search_q[:70]}")
|
| 1030 |
-
rag_res = self.rag_pipeline.analyze(query=search_q, force_refresh=False)
|
| 1031 |
if rag_res:
|
| 1032 |
snippets = []
|
| 1033 |
for i, res_item in enumerate(rag_res):
|
|
@@ -1036,93 +922,97 @@ class GaiaLevel1Agent:
|
|
| 1036 |
href = res_item.get('href','#')
|
| 1037 |
provider = res_item.get('query_tag','WebSearch')
|
| 1038 |
prefix = "EnrichedContent" if res_item.get('enriched') else "Snippet"
|
| 1039 |
-
|
| 1040 |
-
# Truncate individual snippets less aggressively here, final truncation happens in _formulate_answer_with_llm
|
| 1041 |
body_preview = (body[:1500] + "...") if len(body) > 1500 else body
|
| 1042 |
-
|
| 1043 |
snippets.append(f"Source [{i+1} - {provider}]: {title}\nURL: {href}\n{prefix}: {body_preview}\n---")
|
| 1044 |
web_ctx_str = "\n\n".join(snippets)
|
| 1045 |
gaia_logger.info(f"RAG processed {len(rag_res)} sources, total web context length for LLM (pre-truncation): {len(web_ctx_str)} chars.")
|
| 1046 |
else:
|
| 1047 |
gaia_logger.warning("RAG pipeline yielded no web results for the query.")
|
| 1048 |
|
| 1049 |
-
|
| 1050 |
-
gaia_logger.info(f"LLM-based
|
| 1051 |
-
return
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
|
| 1055 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 1056 |
space_id = os.getenv("SPACE_ID")
|
| 1057 |
-
if profile:
|
| 1058 |
-
|
| 1059 |
-
gaia_logger.info(f"User logged in: {username}")
|
| 1060 |
-
else:
|
| 1061 |
-
gaia_logger.warning("User not logged in.")
|
| 1062 |
-
return "Please Login to Hugging Face.", None
|
| 1063 |
questions_url, submit_url = f"{DEFAULT_API_URL}/questions", f"{DEFAULT_API_URL}/submit"
|
| 1064 |
-
try:
|
| 1065 |
-
|
| 1066 |
-
gaia_logger.info("GaiaLevel1Agent (RAG & FileProcessor) initialized for evaluation.")
|
| 1067 |
-
except Exception as e:
|
| 1068 |
-
gaia_logger.error(f"Error instantiating agent: {e}", exc_info=True)
|
| 1069 |
-
return f"Error initializing agent: {e}", None
|
| 1070 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code link unavailable"
|
| 1071 |
-
gaia_logger.info(f"Agent code link: {agent_code}")
|
| 1072 |
try:
|
| 1073 |
-
response = requests.get(questions_url, timeout=15)
|
| 1074 |
-
response.raise_for_status()
|
| 1075 |
questions_data = response.json()
|
| 1076 |
-
if not questions_data or not isinstance(questions_data, list):
|
| 1077 |
-
|
| 1078 |
-
|
| 1079 |
-
|
| 1080 |
-
|
| 1081 |
-
|
| 1082 |
-
|
| 1083 |
-
results_log, answers_payload = [], []
|
| 1084 |
-
GEMINI_RPM_LIMIT = 60
|
| 1085 |
-
sleep_llm = (60.0 / GEMINI_RPM_LIMIT) + 0.8 if GEMINI_RPM_LIMIT > 0 else 0.5
|
| 1086 |
-
gaia_logger.info(f"LLM Rate: {GEMINI_RPM_LIMIT} RPM. Sleep ~{sleep_llm:.2f}s between LLM calls.")
|
| 1087 |
-
gaia_logger.info(f"Running agent on {len(questions_data)} questions...")
|
| 1088 |
for i, item in enumerate(questions_data):
|
| 1089 |
task_id, q_text = item.get("task_id"), item.get("question")
|
| 1090 |
if not task_id or q_text is None:
|
| 1091 |
-
results_log.append({"Task ID": task_id, "Question": q_text, "
|
| 1092 |
continue
|
| 1093 |
gaia_logger.info(f"Q {i+1}/{len(questions_data)} - Task: {task_id}")
|
|
|
|
|
|
|
| 1094 |
try:
|
| 1095 |
-
|
| 1096 |
-
|
| 1097 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1098 |
except Exception as e:
|
| 1099 |
-
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
-
|
| 1103 |
-
|
| 1104 |
-
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1108 |
try:
|
| 1109 |
-
response = requests.post(submit_url, json=
|
| 1110 |
response.raise_for_status()
|
| 1111 |
result_data = response.json()
|
| 1112 |
status = (f"Submission Successful!\nUser: {result_data.get('username')}\nScore: {result_data.get('score','N/A')}% "
|
| 1113 |
f"({result_data.get('correct_count','?')}/{result_data.get('total_attempted','?')} correct)\n"
|
| 1114 |
f"Msg: {result_data.get('message','No message.')}")
|
| 1115 |
-
gaia_logger.info("Submission successful.")
|
| 1116 |
return status, pd.DataFrame(results_log)
|
| 1117 |
except requests.exceptions.HTTPError as e:
|
| 1118 |
err_detail = f"Server: {e.response.status_code}. Detail: {e.response.text[:200]}"
|
| 1119 |
-
gaia_logger.error(f"Submission Fail HTTP: {err_detail}", exc_info=False)
|
| 1120 |
return f"Submission Failed: {err_detail}", pd.DataFrame(results_log)
|
| 1121 |
-
except Exception as e:
|
| 1122 |
-
gaia_logger.error(f"Submission Fail: {e}", exc_info=True)
|
| 1123 |
-
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 1124 |
|
| 1125 |
-
with gr.Blocks(title="GAIA RAG Agent - Advanced") as demo:
|
| 1126 |
gr.Markdown("# Gaia Level 1 Agent (RAG & FileProcessor) Evaluation Runner")
|
| 1127 |
gr.Markdown(
|
| 1128 |
"""
|
|
@@ -1131,6 +1021,7 @@ with gr.Blocks(title="GAIA RAG Agent - Advanced") as demo:
|
|
| 1131 |
2. Click 'Run Evaluation & Submit All Answers'.
|
| 1132 |
---
|
| 1133 |
Agent uses RAG, advanced File Processing, and LLM.
|
|
|
|
| 1134 |
"""
|
| 1135 |
)
|
| 1136 |
gr.LoginButton()
|
|
@@ -1139,37 +1030,14 @@ with gr.Blocks(title="GAIA RAG Agent - Advanced") as demo:
|
|
| 1139 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 1140 |
run_button.click(fn=run_and_submit_all, inputs=[], outputs=[status_output, results_table])
|
| 1141 |
|
| 1142 |
-
if __name__ == "__main__":
|
| 1143 |
print("\n" + "-"*30 + " RAG & FileProcessor Agent App Starting " + "-"*30)
|
| 1144 |
-
required_env = {
|
| 1145 |
-
|
| 1146 |
-
|
| 1147 |
-
|
| 1148 |
-
"
|
| 1149 |
-
|
| 1150 |
-
missing_keys
|
| 1151 |
-
for key_name in required_env:
|
| 1152 |
-
if required_env[key_name]:
|
| 1153 |
-
print(f"✅ {key_name} found.")
|
| 1154 |
-
else:
|
| 1155 |
-
print(f"⚠️ WARNING: {key_name} not set.")
|
| 1156 |
-
|
| 1157 |
-
if not DDGS:
|
| 1158 |
-
print("⚠️ WARNING: duckduckgo_search lib missing (for RAG DDG).")
|
| 1159 |
-
else:
|
| 1160 |
-
print("✅ duckduckgo_search lib found (for RAG DDG).")
|
| 1161 |
-
if not BeautifulSoup:
|
| 1162 |
-
print("⚠️ WARNING: BeautifulSoup lib missing (for RAG Enricher).")
|
| 1163 |
-
else:
|
| 1164 |
-
print("✅ BeautifulSoup lib found (for RAG Enricher).")
|
| 1165 |
-
if not genai:
|
| 1166 |
-
print("⚠️ WARNING: google-generativeai lib missing (for LLM).")
|
| 1167 |
-
else:
|
| 1168 |
-
print("✅ google-generativeai lib found (for LLM).")
|
| 1169 |
-
|
| 1170 |
-
if missing_keys:
|
| 1171 |
-
print(f"\n--- PLEASE SET THE FOLLOWING MISSING ENVIRONMENT VARIABLES FOR FULL FUNCTIONALITY: {', '.join(missing_keys)} ---\n")
|
| 1172 |
-
|
| 1173 |
print("-"*(60 + len(" RAG & FileProcessor Agent App Starting ")) + "\n")
|
| 1174 |
-
|
| 1175 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, share=False)
|
|
|
|
| 12 |
import re
|
| 13 |
from abc import ABC, abstractmethod
|
| 14 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 15 |
+
from concurrent.futures import TimeoutError as FuturesTimeoutError
|
| 16 |
from collections import defaultdict
|
| 17 |
|
| 18 |
try:
|
|
|
|
| 64 |
print("WARNING: librosa library not found. Audio processing may be impaired. Install with: pip install librosa")
|
| 65 |
|
| 66 |
try:
|
| 67 |
+
import openpyxl
|
| 68 |
except ImportError:
|
| 69 |
openpyxl = None
|
| 70 |
print("WARNING: openpyxl library not found. .xlsx file processing might fail. Install with: pip install openpyxl")
|
|
|
|
| 74 |
except ImportError:
|
| 75 |
pdfplumber = None
|
| 76 |
print("WARNING: pdfplumber library not found. PDF file processing will be unavailable. Install with: pip install pdfplumber")
|
|
|
|
| 77 |
|
| 78 |
logging.basicConfig(
|
| 79 |
level=logging.INFO,
|
|
|
|
| 90 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 91 |
|
| 92 |
AGENT_DEFAULT_TIMEOUT = 15
|
| 93 |
+
MAX_CONTEXT_LENGTH_LLM = 30000
|
| 94 |
|
| 95 |
+
MAX_FILE_SIZE = 5 * 1024 * 1024
|
| 96 |
CSV_SAMPLE_ROWS = 3
|
| 97 |
+
MAX_FILE_CONTEXT_LENGTH = 10000
|
| 98 |
|
|
|
|
| 99 |
asr_pipeline_instance: Optional[Any] = None
|
| 100 |
+
ASR_MODEL_NAME = "openai/whisper-tiny"
|
| 101 |
+
ASR_PROCESSING_TIMEOUT_SECONDS = 240
|
| 102 |
|
| 103 |
DEFAULT_RAG_CONFIG = {
|
| 104 |
'search': {
|
|
|
|
| 108 |
'google_cse_id': GOOGLE_CUSTOM_SEARCH_CSE_ID,
|
| 109 |
'tavily_api_key': TAVILY_API_KEY,
|
| 110 |
'default_max_results': 3, 'retry_attempts': 2, 'retry_delay': 2,
|
| 111 |
+
'google_timeout': 8, 'tavily_depth': "basic",
|
| 112 |
+
'max_query_length_tavily': 380
|
| 113 |
},
|
| 114 |
'processing': {
|
| 115 |
'trusted_sources': {'wikipedia.org': 0.8, 'reuters.com': 0.75, 'apnews.com': 0.75},
|
|
|
|
| 136 |
global asr_pipeline_instance
|
| 137 |
if asr_pipeline_instance is None and hf_transformers_pipeline and torch:
|
| 138 |
try:
|
| 139 |
+
device = -1
|
|
|
|
|
|
|
| 140 |
asr_pipeline_instance = hf_transformers_pipeline(
|
| 141 |
"automatic-speech-recognition",
|
| 142 |
model=ASR_MODEL_NAME,
|
|
|
|
| 166 |
|
| 167 |
try:
|
| 168 |
if len(content) > MAX_FILE_SIZE:
|
|
|
|
| 169 |
return f"Error: File '{filename_str}' exceeds maximum allowed size ({MAX_FILE_SIZE // (1024*1024)}MB)."
|
| 170 |
|
| 171 |
if 'csv' in content_type_str or filename_str.endswith('.csv'):
|
|
|
|
| 172 |
return FileProcessor._process_csv(content, filename_str)
|
| 173 |
elif 'json' in content_type_str or filename_str.endswith('.json'):
|
|
|
|
| 174 |
return FileProcessor._process_json(content, filename_str)
|
| 175 |
elif ('excel' in content_type_str or 'spreadsheetml' in content_type_str or \
|
| 176 |
+
filename_str.endswith(('.xlsx', '.xls'))) and openpyxl:
|
|
|
|
| 177 |
return FileProcessor._process_excel(content, filename_str)
|
| 178 |
+
elif ('pdf' in content_type_str or filename_str.endswith('.pdf')) and pdfplumber:
|
|
|
|
| 179 |
return FileProcessor._process_pdf(content, filename_str)
|
| 180 |
elif ('audio' in content_type_str or \
|
| 181 |
filename_str.endswith(('.mp3', '.wav', '.flac', '.ogg', '.m4a'))) and \
|
| 182 |
+
hf_transformers_pipeline and librosa:
|
|
|
|
| 183 |
return FileProcessor._process_audio(content, filename_str)
|
| 184 |
elif 'text/plain' in content_type_str or \
|
| 185 |
('text/' in content_type_str and not any(sub in content_type_str for sub in ['html', 'xml'])) or \
|
| 186 |
filename_str.endswith(('.txt', '.md', '.py', '.js', '.c', '.cpp', '.java', '.html', '.xml', '.log')):
|
|
|
|
| 187 |
return FileProcessor._process_text(content, filename_str)
|
| 188 |
else:
|
|
|
|
| 189 |
return FileProcessor._handle_unknown_type(content, filename_str)
|
| 190 |
except Exception as e:
|
| 191 |
gaia_logger.error(f"File processing error for '{filename_str}': {str(e)}", exc_info=True)
|
|
|
|
| 201 |
|
| 202 |
@staticmethod
|
| 203 |
def _process_csv(content: bytes, filename: str) -> str:
|
| 204 |
+
gaia_logger.info(f"Processing CSV file: {filename}")
|
| 205 |
+
df = None
|
| 206 |
try:
|
| 207 |
encodings_to_try = ['utf-8', 'latin1', 'iso-8859-1', 'cp1252']
|
|
|
|
| 208 |
for enc in encodings_to_try:
|
| 209 |
try:
|
| 210 |
df = pd.read_csv(io.BytesIO(content), encoding=enc)
|
|
|
|
| 213 |
except Exception: continue
|
| 214 |
if df is None: return f"Error: Could not decode CSV '{filename}'."
|
| 215 |
|
|
|
|
|
|
|
|
|
|
| 216 |
summary = (
|
| 217 |
+
f"CSV Document Summary: '{filename}' ({len(df)} rows, {len(df.columns)} columns):\n"
|
| 218 |
+
f"Columns: {', '.join(df.columns)}\nFirst {min(CSV_SAMPLE_ROWS, len(df))} sample rows:\n{df.head(CSV_SAMPLE_ROWS).to_markdown(index=False)}"
|
| 219 |
)
|
| 220 |
return FileProcessor._truncate_text(summary, filename, "CSV")
|
| 221 |
+
except Exception as e:
|
| 222 |
+
if "tabulate" in str(e).lower() and df is not None:
|
| 223 |
+
gaia_logger.error(f"CSV to_markdown error for '{filename}' (missing tabulate): {e}", exc_info=False)
|
| 224 |
+
try:
|
| 225 |
+
summary = (
|
| 226 |
+
f"CSV Document Summary: '{filename}' ({len(df)} rows, {len(df.columns)} columns):\n"
|
| 227 |
+
f"Columns: {', '.join(df.columns)}\nFirst {min(CSV_SAMPLE_ROWS, len(df))} sample rows (plain text):\n{df.head(CSV_SAMPLE_ROWS).to_string(index=False)}"
|
| 228 |
+
)
|
| 229 |
+
return FileProcessor._truncate_text(summary, filename, "CSV (plain)")
|
| 230 |
+
except Exception as e_fallback:
|
| 231 |
+
gaia_logger.error(f"CSV fallback to_string error for '{filename}': {e_fallback}", exc_info=True)
|
| 232 |
+
return f"Error processing CSV '{filename}' (formatting fallback failed): {str(e_fallback)}"
|
| 233 |
+
gaia_logger.error(f"CSV processing error for '{filename}': {e}", exc_info=True)
|
| 234 |
return f"Error processing CSV '{filename}': {str(e)}"
|
| 235 |
|
| 236 |
+
|
| 237 |
@staticmethod
|
| 238 |
def _process_json(content: bytes, filename: str) -> str:
|
| 239 |
+
gaia_logger.info(f"Processing JSON file: {filename}")
|
| 240 |
try:
|
| 241 |
decoded_content = content.decode('utf-8', errors='replace')
|
| 242 |
data = json.loads(decoded_content)
|
|
|
|
| 251 |
|
| 252 |
@staticmethod
|
| 253 |
def _process_text(content: bytes, filename: str) -> str:
|
| 254 |
+
gaia_logger.info(f"Processing Text-like file: {filename}")
|
| 255 |
try:
|
| 256 |
text = None
|
| 257 |
encodings_to_try = ['utf-8', 'latin1', 'iso-8859-1', 'cp1252']
|
|
|
|
| 269 |
|
| 270 |
@staticmethod
|
| 271 |
def _process_excel(content: bytes, filename: str) -> str:
|
| 272 |
+
gaia_logger.info(f"Processing Excel file: {filename}")
|
| 273 |
if not openpyxl: return f"Error: Excel processing skipped for '{filename}', openpyxl library not available."
|
| 274 |
+
xls = None
|
| 275 |
+
df_list_for_fallback = []
|
| 276 |
try:
|
|
|
|
| 277 |
xls = pd.ExcelFile(io.BytesIO(content), engine='openpyxl')
|
| 278 |
summary_parts = [f"Excel Document Summary: '{filename}'"]
|
| 279 |
for sheet_name in xls.sheet_names:
|
| 280 |
df = xls.parse(sheet_name)
|
| 281 |
+
df_list_for_fallback.append((sheet_name, df))
|
|
|
|
|
|
|
| 282 |
sheet_summary = (
|
| 283 |
+
f"\n---\nSheet: '{sheet_name}' ({len(df)} rows, {len(df.columns)} columns):\n"
|
| 284 |
+
f"Columns: {', '.join(df.columns)}\nFirst {min(CSV_SAMPLE_ROWS, len(df))} sample rows:\n{df.head(CSV_SAMPLE_ROWS).to_markdown(index=False)}"
|
| 285 |
)
|
| 286 |
summary_parts.append(sheet_summary)
|
| 287 |
+
if sum(len(p) for p in summary_parts) > MAX_FILE_CONTEXT_LENGTH * 0.8:
|
|
|
|
| 288 |
summary_parts.append("\n... (further sheets omitted due to length)")
|
| 289 |
break
|
| 290 |
full_summary = "".join(summary_parts)
|
| 291 |
return FileProcessor._truncate_text(full_summary, filename, "Excel")
|
| 292 |
+
except Exception as e:
|
| 293 |
+
if "tabulate" in str(e).lower():
|
| 294 |
+
gaia_logger.error(f"Excel to_markdown error for '{filename}' (missing tabulate): {e}", exc_info=False)
|
| 295 |
+
try:
|
| 296 |
+
summary_parts_fallback = [f"Excel Document Summary: '{filename}'"]
|
| 297 |
+
if not df_list_for_fallback and xls:
|
| 298 |
+
for sheet_name in xls.sheet_names:
|
| 299 |
+
df_list_for_fallback.append((sheet_name, xls.parse(sheet_name)))
|
| 300 |
+
elif not xls and not df_list_for_fallback:
|
| 301 |
+
temp_xls = pd.ExcelFile(io.BytesIO(content), engine='openpyxl')
|
| 302 |
+
for sheet_name in temp_xls.sheet_names:
|
| 303 |
+
df_list_for_fallback.append((sheet_name, temp_xls.parse(sheet_name)))
|
| 304 |
+
|
| 305 |
+
for sheet_name_fb, df_fb in df_list_for_fallback:
|
| 306 |
+
sheet_summary_fallback = (
|
| 307 |
+
f"\n---\nSheet: '{sheet_name_fb}' ({len(df_fb)} rows, {len(df_fb.columns)} columns):\n"
|
| 308 |
+
f"Columns: {', '.join(df_fb.columns)}\nFirst {min(CSV_SAMPLE_ROWS, len(df_fb))} sample rows (plain text):\n{df_fb.head(CSV_SAMPLE_ROWS).to_string(index=False)}"
|
| 309 |
+
)
|
| 310 |
+
summary_parts_fallback.append(sheet_summary_fallback)
|
| 311 |
+
if sum(len(p) for p in summary_parts_fallback) > MAX_FILE_CONTEXT_LENGTH * 0.8:
|
| 312 |
+
summary_parts_fallback.append("\n... (further sheets omitted due to length)")
|
| 313 |
+
break
|
| 314 |
+
full_summary_fallback = "".join(summary_parts_fallback)
|
| 315 |
+
return FileProcessor._truncate_text(full_summary_fallback, filename, "Excel (plain)")
|
| 316 |
+
except Exception as e_fallback:
|
| 317 |
+
gaia_logger.error(f"Excel fallback to_string error for '{filename}': {e_fallback}", exc_info=True)
|
| 318 |
+
return f"Error processing Excel '{filename}' (formatting fallback failed): {str(e_fallback)}"
|
| 319 |
+
gaia_logger.error(f"Excel processing error for '{filename}': {e}", exc_info=True)
|
| 320 |
return f"Error processing Excel file '{filename}': {str(e)}"
|
| 321 |
|
| 322 |
@staticmethod
|
| 323 |
def _process_pdf(content: bytes, filename: str) -> str:
|
| 324 |
+
gaia_logger.info(f"Processing PDF file: {filename}")
|
| 325 |
if not pdfplumber: return f"Error: PDF processing skipped for '{filename}', pdfplumber library not available."
|
| 326 |
text_content = ""
|
| 327 |
try:
|
|
|
|
| 331 |
page_text = page.extract_text()
|
| 332 |
if page_text:
|
| 333 |
text_content += page_text + "\n"
|
| 334 |
+
if len(text_content) > MAX_FILE_CONTEXT_LENGTH * 1.2:
|
|
|
|
| 335 |
break
|
| 336 |
if not text_content:
|
| 337 |
return f"PDF Document: '{filename}'. No text could be extracted or PDF is empty."
|
| 338 |
summary = f"PDF Document: '{filename}':\n{text_content}"
|
| 339 |
return FileProcessor._truncate_text(summary, filename, "PDF")
|
| 340 |
except Exception as e:
|
|
|
|
| 341 |
return f"Error processing PDF file '{filename}': {str(e)}"
|
| 342 |
|
| 343 |
+
@staticmethod
|
| 344 |
+
def _perform_asr_transcription(asr_pipeline_ref, audio_data_np, filename_for_log):
|
| 345 |
+
gaia_logger.info(f"ASR: Starting transcription for {filename_for_log} in thread.")
|
| 346 |
+
return asr_pipeline_ref(audio_data_np, chunk_length_s=30, return_timestamps=False, generate_kwargs={"task": "transcribe", "language": "en"})
|
| 347 |
+
|
| 348 |
+
|
| 349 |
@staticmethod
|
| 350 |
def _process_audio(content: bytes, filename: str) -> str:
|
| 351 |
+
gaia_logger.info(f"Processing Audio file: {filename}")
|
| 352 |
+
asr_pipeline_ref = FileProcessor._get_asr_pipeline()
|
| 353 |
+
if not asr_pipeline_ref:
|
| 354 |
return f"Error: Audio processing skipped for '{filename}', ASR pipeline not available."
|
| 355 |
if not librosa:
|
| 356 |
return f"Error: Audio processing skipped for '{filename}', librosa library not available."
|
| 357 |
+
|
| 358 |
try:
|
| 359 |
with io.BytesIO(content) as audio_buffer:
|
| 360 |
y, sr = librosa.load(audio_buffer, sr=16000, mono=True)
|
| 361 |
|
| 362 |
+
duration_seconds = len(y) / sr
|
| 363 |
+
gaia_logger.info(f"Audio file: {filename}, Duration: {duration_seconds:.2f} seconds. Timeout set to: {ASR_PROCESSING_TIMEOUT_SECONDS}s")
|
| 364 |
start_time = time.time()
|
| 365 |
+
transcribed_text = ""
|
|
|
|
|
|
|
|
|
|
| 366 |
|
| 367 |
+
with ThreadPoolExecutor(max_workers=1) as executor:
|
| 368 |
+
future = executor.submit(FileProcessor._perform_asr_transcription, asr_pipeline_ref, y, filename)
|
| 369 |
+
try:
|
| 370 |
+
transcription_result = future.result(timeout=ASR_PROCESSING_TIMEOUT_SECONDS)
|
| 371 |
+
transcribed_text = transcription_result.get("text", "") if isinstance(transcription_result, dict) else str(transcription_result)
|
| 372 |
+
except FuturesTimeoutError:
|
| 373 |
+
gaia_logger.warning(f"ASR transcription for '{filename}' timed out after {ASR_PROCESSING_TIMEOUT_SECONDS} seconds.")
|
| 374 |
+
return f"Error: Audio transcription for '{filename}' timed out after {ASR_PROCESSING_TIMEOUT_SECONDS}s."
|
| 375 |
+
except Exception as e_thread:
|
| 376 |
+
gaia_logger.error(f"ASR transcription thread for '{filename}' failed: {e_thread}", exc_info=True)
|
| 377 |
+
if "3000 mel input features" in str(e_thread) or "return_timestamps" in str(e_thread):
|
| 378 |
+
return f"Error processing Audio file '{filename}': Transcription failed due to long-form audio issue (mel features/timestamps). Original error: {str(e_thread)}"
|
| 379 |
+
return f"Error during audio transcription for '{filename}': {str(e_thread)}"
|
| 380 |
+
|
| 381 |
+
end_time = time.time()
|
| 382 |
+
gaia_logger.info(f"Audio transcription for '{filename}' (or timeout) took {end_time - start_time:.2f} seconds.")
|
| 383 |
|
| 384 |
if not transcribed_text.strip():
|
| 385 |
+
return f"Audio Document: '{filename}'. Transcription result was empty or ASR failed."
|
| 386 |
|
| 387 |
summary = f"Audio Document (Transcription): '{filename}':\n{transcribed_text}"
|
| 388 |
return FileProcessor._truncate_text(summary, filename, "Audio Transcription")
|
| 389 |
+
|
| 390 |
except Exception as e:
|
| 391 |
gaia_logger.error(f"Audio processing/transcription error for '{filename}': {str(e)}", exc_info=True)
|
| 392 |
return f"Error processing Audio file '{filename}': {str(e)}"
|
| 393 |
|
| 394 |
+
|
| 395 |
@staticmethod
|
| 396 |
def _handle_unknown_type(content: bytes, filename: str) -> str:
|
| 397 |
gaia_logger.warning(f"Attempting to handle unknown file type for '{filename}' as text snippet.")
|
|
|
|
| 402 |
except Exception:
|
| 403 |
return f"File with Unknown Content Type: '{filename}'. Content is likely binary and cannot be displayed as text."
|
| 404 |
|
| 405 |
+
class CacheManager:
|
| 406 |
def __init__(self, ttl: int = 300, max_size: int = 100, name: str = "Cache"):
|
| 407 |
self.ttl = ttl; self.max_size = max_size
|
| 408 |
self._cache: Dict[Any, Any] = {}; self._timestamps: Dict[Any, float] = {}
|
|
|
|
| 412 |
if key in self._cache and (time.time() - self._timestamps.get(key, 0) < self.ttl):
|
| 413 |
try:
|
| 414 |
self._access_order.remove(key); self._access_order.append(key)
|
|
|
|
| 415 |
return copy.deepcopy(self._cache[key])
|
| 416 |
except (ValueError, TypeError) as e:
|
|
|
|
| 417 |
self.delete(key); return None
|
| 418 |
elif key in self._cache:
|
|
|
|
| 419 |
self.delete(key)
|
| 420 |
return None
|
| 421 |
def set(self, key: Any, value: Any):
|
|
|
|
| 423 |
while len(self._cache) >= self.max_size and self._access_order:
|
| 424 |
old_key = self._access_order.pop(0)
|
| 425 |
if old_key in self._cache:
|
|
|
|
| 426 |
del self._cache[old_key]; del self._timestamps[old_key]
|
| 427 |
try: self._cache[key] = copy.deepcopy(value)
|
| 428 |
except TypeError: self._cache[key] = value
|
| 429 |
self._timestamps[key] = time.time(); self._access_order.append(key)
|
|
|
|
| 430 |
def delete(self, key: Any):
|
| 431 |
if key in self._cache:
|
| 432 |
try:
|
|
|
|
| 437 |
def __len__(self): return len(self._cache)
|
| 438 |
def __contains__(self, key): return key in self._cache and (time.time()-self._timestamps.get(key,0)<self.ttl)
|
| 439 |
|
| 440 |
+
class SearchProvider(ABC):
|
| 441 |
def __init__(self, config_dict: Dict):
|
| 442 |
self.provider_config = config_dict.get('search', {})
|
| 443 |
+
self._enabled = False
|
| 444 |
self._quota_used = 0
|
|
|
|
| 445 |
raw_quota = self.provider_config.get(f'{self.provider_name.lower()}_quota', float('inf'))
|
| 446 |
self._quota_limit = float(raw_quota) if raw_quota is not None else float('inf')
|
|
|
|
| 447 |
@property
|
| 448 |
@abstractmethod
|
| 449 |
+
def provider_name(self) -> str: pass
|
|
|
|
|
|
|
| 450 |
@abstractmethod
|
| 451 |
+
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]: pass
|
|
|
|
|
|
|
| 452 |
def search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 453 |
+
if not self._enabled: return None
|
|
|
|
|
|
|
| 454 |
if self._quota_limit != float('inf') and self._quota_used >= self._quota_limit:
|
| 455 |
gaia_logger.warning(f"[{self.provider_name}] Skip: Quota ({self._quota_used}/{int(self._quota_limit)})")
|
| 456 |
return None
|
|
|
|
| 460 |
usage_str = f"({self._quota_used}/{int(self._quota_limit)}) "
|
| 461 |
gaia_logger.info(f"[{self.provider_name}] {usage_str}Search: '{query[:70]}...'")
|
| 462 |
return self._perform_search(query, max_results)
|
| 463 |
+
def available(self) -> bool: return self._enabled
|
| 464 |
|
| 465 |
+
class GoogleProvider(SearchProvider):
|
|
|
|
|
|
|
|
|
|
| 466 |
@property
|
| 467 |
+
def provider_name(self) -> str: return "Google"
|
|
|
|
|
|
|
| 468 |
def __init__(self, config_dict: Dict):
|
| 469 |
+
super().__init__(config_dict)
|
| 470 |
self._api_key = self.provider_config.get("google_api_key")
|
| 471 |
self._cse_id = self.provider_config.get("google_cse_id")
|
| 472 |
self._timeout = self.provider_config.get("google_timeout", 8)
|
| 473 |
+
if self._api_key and self._cse_id: self._enabled = True; gaia_logger.info(f"✓ {self.provider_name} API configured.")
|
| 474 |
+
else: self._enabled = False; gaia_logger.warning(f"✗ {self.provider_name} API key/CSE ID missing.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 476 |
try:
|
| 477 |
+
params = {'key': self._api_key, 'cx': self._cse_id, 'q': query, 'num': max_results, 'safe': 'active'}
|
| 478 |
+
response = requests.get("https://www.googleapis.com/customsearch/v1", params=params, timeout=self._timeout)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
response.raise_for_status()
|
| 480 |
+
items = response.json().get('items', [])
|
| 481 |
+
if not items: return []
|
| 482 |
+
return [{'href': i.get('link'), 'title': i.get('title', ''), 'body': i.get('snippet', '')} for i in items]
|
| 483 |
+
except requests.exceptions.Timeout: gaia_logger.warning(f"[{self.provider_name}] Timeout: '{query[:70]}'"); return None
|
| 484 |
+
except requests.exceptions.RequestException as e: gaia_logger.warning(f"[{self.provider_name}] RequestEx: '{query[:70]}': {e}"); return None
|
| 485 |
+
except Exception as e: gaia_logger.error(f"[{self.provider_name}] Error: '{query[:70]}': {e}", exc_info=True); return None
|
| 486 |
+
|
| 487 |
+
class TavilyProvider(SearchProvider):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
@property
|
| 489 |
+
def provider_name(self) -> str: return "Tavily"
|
|
|
|
|
|
|
| 490 |
def __init__(self, config_dict: Dict):
|
| 491 |
+
super().__init__(config_dict)
|
| 492 |
self._api_key = self.provider_config.get("tavily_api_key")
|
| 493 |
self._search_depth = self.provider_config.get("tavily_depth", "basic")
|
| 494 |
if self._api_key and TavilyClient:
|
| 495 |
+
try: self._client = TavilyClient(api_key=self._api_key); self._enabled = True; gaia_logger.info(f"✓ {self.provider_name} API initialized.")
|
| 496 |
+
except Exception as e: self._enabled = False; gaia_logger.warning(f"✗ {self.provider_name} init fail: {e}", exc_info=False)
|
| 497 |
+
elif not TavilyClient: self._enabled = False; gaia_logger.warning(f"✗ {self.provider_name}: TavilyClient lib missing.")
|
| 498 |
+
else: self._enabled = False; gaia_logger.warning(f"✗ {self.provider_name}: API key missing.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 500 |
+
if not self._enabled: return None
|
| 501 |
try:
|
| 502 |
+
max_len = DEFAULT_RAG_CONFIG['search'].get('max_query_length_tavily', 380)
|
| 503 |
+
if len(query) > max_len:
|
| 504 |
+
gaia_logger.warning(f"[{self.provider_name}] Query truncated from {len(query)} to {max_len} chars for API limit.")
|
| 505 |
+
query = query[:max_len]
|
| 506 |
response = self._client.search(query=query, max_results=max_results, search_depth=self._search_depth)
|
| 507 |
hits = response.get('results', [])
|
| 508 |
+
if not hits: return []
|
| 509 |
return [{'href': h.get('url'), 'title': h.get('title',''), 'body': h.get('content','')} for h in hits]
|
| 510 |
except Exception as e: gaia_logger.warning(f"[{self.provider_name}] Search fail: '{query[:70]}': {e}"); return None
|
| 511 |
|
| 512 |
+
class DuckDuckGoProvider(SearchProvider):
|
| 513 |
@property
|
| 514 |
+
def provider_name(self) -> str: return "DuckDuckGo"
|
|
|
|
|
|
|
| 515 |
def __init__(self, config_dict: Dict):
|
| 516 |
+
super().__init__(config_dict)
|
| 517 |
if DDGS:
|
| 518 |
+
try: self._client = DDGS(timeout=10); self._enabled = True; gaia_logger.info(f"✓ {self.provider_name} Search initialized.")
|
| 519 |
+
except Exception as e: self._enabled = False; gaia_logger.warning(f"✗ {self.provider_name} init fail: {e}", exc_info=False)
|
| 520 |
+
else: self._enabled = False; gaia_logger.warning(f"✗ {self.provider_name}: DDGS lib missing.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 521 |
def _perform_search(self, query: str, max_results: int) -> Optional[List[Dict[str, str]]]:
|
| 522 |
+
if not self._enabled: return None
|
| 523 |
try:
|
| 524 |
hits = list(self._client.text(query, region='wt-wt', max_results=max_results))[:max_results]
|
| 525 |
+
if not hits: return []
|
| 526 |
return [{'href': r.get('href'), 'title': r.get('title',''), 'body': r.get('body','')} for r in hits]
|
| 527 |
except Exception as e: gaia_logger.warning(f"[{self.provider_name}] Search fail: '{query[:70]}': {e}"); return None
|
| 528 |
|
| 529 |
+
class CompositeSearchClient:
|
| 530 |
def __init__(self, config_dict: Dict):
|
| 531 |
self.config = config_dict
|
| 532 |
self._search_config = config_dict.get('search', {})
|
| 533 |
self.providers = self._init_providers(config_dict)
|
| 534 |
self.cache = CacheManager(
|
| 535 |
ttl=config_dict.get('caching', {}).get('search_cache_ttl', 300),
|
| 536 |
+
max_size=config_dict.get('caching', {}).get('search_cache_size', 50), name="SearchClientCache"
|
|
|
|
| 537 |
)
|
| 538 |
self._retry_att = self._search_config.get("retry_attempts", 2)
|
| 539 |
self._retry_del = self._search_config.get("retry_delay", 2)
|
| 540 |
self._def_max_r = self._search_config.get("default_max_results", 3)
|
|
|
|
| 541 |
def _init_providers(self, config_dict: Dict) -> List[SearchProvider]:
|
| 542 |
providers: List[SearchProvider] = []
|
| 543 |
if TAVILY_API_KEY and TavilyClient:
|
| 544 |
tavily_prov = TavilyProvider(config_dict)
|
| 545 |
+
if tavily_prov.available(): providers.append(tavily_prov)
|
|
|
|
| 546 |
if GOOGLE_CUSTOM_SEARCH_API_KEY and GOOGLE_CUSTOM_SEARCH_CSE_ID:
|
| 547 |
google_prov = GoogleProvider(config_dict)
|
| 548 |
+
if google_prov.available(): providers.append(google_prov)
|
|
|
|
| 549 |
if DDGS:
|
| 550 |
ddgs_prov = DuckDuckGoProvider(config_dict)
|
| 551 |
+
if ddgs_prov.available(): providers.append(ddgs_prov)
|
| 552 |
+
if not providers: gaia_logger.error("RAG: No search providers initialized!")
|
| 553 |
+
else: gaia_logger.info(f"RAG Providers: {[p.provider_name for p in providers]}")
|
|
|
|
|
|
|
|
|
|
| 554 |
return providers
|
|
|
|
| 555 |
def search(self, query: str, max_results: Optional[int] = None, force_refresh: bool = False) -> List[Dict]:
|
| 556 |
q, actual_r = query.strip(), max_results if max_results is not None else self._def_max_r
|
| 557 |
+
if not q: return []
|
|
|
|
| 558 |
cache_key = (q, actual_r)
|
| 559 |
+
if not force_refresh and (cached := self.cache.get(cache_key)) is not None: return cached
|
|
|
|
| 560 |
for prov in self.providers:
|
| 561 |
for attempt in range(self._retry_att + 1):
|
| 562 |
+
if not prov.available(): break
|
|
|
|
| 563 |
try:
|
| 564 |
results = prov.search(q, actual_r)
|
| 565 |
+
if results is not None: self.cache.set(cache_key, results); return results
|
| 566 |
+
if attempt < self._retry_att: time.sleep(self._retry_del)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
except Exception as e:
|
| 568 |
+
if attempt < self._retry_att: time.sleep(self._retry_del)
|
|
|
|
|
|
|
|
|
|
| 569 |
self.cache.set(cache_key, [])
|
| 570 |
return []
|
| 571 |
|
| 572 |
+
class GaiaQueryBuilder:
|
| 573 |
def __init__(self, base_query: str, config_dict: Dict):
|
| 574 |
self.base_query = base_query.strip()
|
| 575 |
+
self.config = config_dict
|
|
|
|
|
|
|
| 576 |
def get_queries(self) -> Dict[str, List[Tuple[str, str]]]:
|
| 577 |
+
return {'primary': [(self.base_query, 'GENERAL')]} if self.base_query else {'primary': []}
|
|
|
|
|
|
|
| 578 |
|
| 579 |
+
class ResultProcessor:
|
| 580 |
def __init__(self, config_dict: Dict):
|
| 581 |
self.proc_config = config_dict.get('processing', {})
|
| 582 |
self.trusted_sources = self.proc_config.get('trusted_sources', {})
|
| 583 |
self.seen_urls: Set[str] = set()
|
| 584 |
self.date_pattern = DEFAULT_RAG_CONFIG['processing'].get('date_pattern', r'\b\d{4}\b')
|
|
|
|
|
|
|
| 585 |
def process_batch(self, results: List[Dict], query_tag: str, initial_cat: str='GENERAL') -> List[Dict]:
|
| 586 |
processed: List[Dict] = []
|
| 587 |
+
if not results: return processed
|
|
|
|
| 588 |
for r in results:
|
| 589 |
url = r.get('href')
|
| 590 |
+
if not url or self._normalize_url(url) in self.seen_urls: continue
|
|
|
|
| 591 |
self.seen_urls.add(self._normalize_url(url))
|
| 592 |
+
res_data = {'title': r.get('title',''), 'body': r.get('body',''), 'href': url, 'query_tag': query_tag, 'category': initial_cat, 'source_quality': 0.5, 'temporal_relevance': 0.1, 'combined_score': 0.0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
self._score_result(res_data)
|
| 594 |
processed.append(res_data)
|
|
|
|
| 595 |
return processed
|
| 596 |
+
def _normalize_url(self, url: str) -> str: return re.sub(r'^https?://(?:www\.)?', '', str(url)).rstrip('/') if url else ""
|
|
|
|
|
|
|
|
|
|
| 597 |
def _score_result(self, result: Dict):
|
| 598 |
url, body, title = result.get('href', ''), result.get('body', ''), result.get('title', '')
|
| 599 |
source_q = 0.5
|
| 600 |
+
if domain_match := re.search(r'https?://(?:www\.)?([^/]+)', url or ""): source_q = self.trusted_sources.get(domain_match.group(1), 0.5)
|
|
|
|
| 601 |
result['source_quality'] = source_q
|
| 602 |
+
temporal_r = 0.1; text_combo = (str(title) + ' ' + str(body)).lower()
|
| 603 |
+
if any(k in text_combo for k in ['today', 'current', 'latest']) or re.search(r'\b\d+\s+hours?\s+ago', text_combo): temporal_r = 0.9
|
| 604 |
+
elif re.search(self.date_pattern, text_combo): temporal_r = 0.5
|
|
|
|
|
|
|
|
|
|
| 605 |
result['temporal_relevance'] = temporal_r
|
| 606 |
result['combined_score'] = (source_q * 0.6 + temporal_r * 0.4)
|
| 607 |
|
| 608 |
+
class ContentEnricher:
|
| 609 |
def __init__(self, config_dict: Dict):
|
| 610 |
self.enrich_config = config_dict.get('enrichment', {})
|
| 611 |
self._enabled = self.enrich_config.get('enabled', False) and bool(BeautifulSoup)
|
| 612 |
+
if not self._enabled: return
|
|
|
|
|
|
|
| 613 |
self._timeout = self.enrich_config.get('timeout', 10)
|
| 614 |
self._max_w = self.enrich_config.get('workers', 3)
|
| 615 |
self._min_l, self._max_l = self.enrich_config.get('min_text_length', 200), self.enrich_config.get('max_text_length', 8000)
|
| 616 |
self._skip_ext = tuple(self.enrich_config.get('skip_extensions', []))
|
| 617 |
+
self.cache = CacheManager(ttl=config_dict.get('caching', {}).get('enrich_cache_ttl', 600), max_size=config_dict.get('caching', {}).get('enrich_cache_size', 25), name="EnrichCache")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 618 |
gaia_logger.info(f"RAG ContentEnricher Initialized. Enabled: {self._enabled}")
|
|
|
|
| 619 |
def enrich_batch(self, results: List[Dict], force_refresh: bool = False) -> List[Dict]:
|
| 620 |
+
if not self._enabled or not results: return results
|
|
|
|
| 621 |
updated_res = []
|
| 622 |
with ThreadPoolExecutor(max_workers=self._max_w) as executor:
|
| 623 |
future_map = {executor.submit(self._fetch_single, r, force_refresh): r for r in results}
|
| 624 |
+
for future in as_completed(future_map): updated_res.append(future.result())
|
|
|
|
| 625 |
return updated_res
|
|
|
|
| 626 |
def _fetch_single(self, result: Dict, force_refresh: bool) -> Dict:
|
| 627 |
+
url = result.get('href'); result.setdefault('enriched', False); result.setdefault('enrichment_failed', None); result.setdefault('enrichment_skipped_type', None)
|
| 628 |
+
if not url: result['enrichment_skipped_type'] = 'no_url'; return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 629 |
if not force_refresh and (cached := self.cache.get(url)) is not None:
|
| 630 |
+
if cached: result.update(cached); return result
|
| 631 |
+
if url.lower().endswith(self._skip_ext): result['enrichment_skipped_type'] = 'extension'; return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
try:
|
| 633 |
headers = {'User-Agent': 'Mozilla/5.0 GaiaRAGAgent/1.0'}
|
| 634 |
response = requests.get(url, headers=headers, timeout=self._timeout, allow_redirects=True)
|
| 635 |
response.raise_for_status()
|
| 636 |
+
if 'text/html' not in response.headers.get('Content-Type', '').lower(): result['enrichment_skipped_type'] = 'non-html'; return result
|
|
|
|
|
|
|
| 637 |
soup = BeautifulSoup(response.text, 'lxml')
|
| 638 |
for el_name in ["script", "style", "nav", "header", "footer", "aside", "form", "iframe", "img", "svg", ".ad", ".advertisement"]:
|
| 639 |
+
for el in soup.select(el_name): el.decompose()
|
|
|
|
| 640 |
main_el = soup.select_one('article, main, [role="main"], .entry-content, .post-content, #content, #main') or soup.body
|
| 641 |
text = main_el.get_text(separator='\n', strip=True) if main_el else ""
|
| 642 |
text = re.sub(r'(\s*\n\s*){2,}', '\n\n', text).strip()
|
| 643 |
if len(text) >= self._min_l:
|
| 644 |
result['body'] = text[:self._max_l] + ("..." if len(text) > self._max_l else "")
|
| 645 |
+
result['enriched'] = True; self.cache.set(url, {'body': result['body'], 'enriched': True})
|
| 646 |
+
else: result['enrichment_failed'] = 'too_short'
|
| 647 |
+
except Exception as e: result['enrichment_failed'] = type(e).__name__
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
return result
|
| 649 |
|
| 650 |
+
class GeneralRAGPipeline:
|
| 651 |
def __init__(self, config_dict: Optional[Dict] = None):
|
| 652 |
self.config = config_dict if config_dict is not None else DEFAULT_RAG_CONFIG
|
| 653 |
self.search_client = CompositeSearchClient(self.config)
|
| 654 |
enrich_cfg = self.config.get('enrichment', {})
|
| 655 |
self.enricher = ContentEnricher(self.config) if enrich_cfg.get('enabled', False) and BeautifulSoup else None
|
| 656 |
+
if not self.enricher: gaia_logger.info("RAG Content Enrichment disabled.")
|
| 657 |
+
self.pipeline_cache = CacheManager(ttl=self.config.get('caching', {}).get('analyzer_cache_ttl', 3600), max_size=self.config.get('caching', {}).get('analyzer_cache_size', 30), name="RAGPipelineCache")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 658 |
gaia_logger.info("GeneralRAGPipeline initialized.")
|
|
|
|
| 659 |
def analyze(self, query: str, force_refresh: bool = False) -> List[Dict]:
|
| 660 |
+
q = query.strip();
|
| 661 |
+
if not q: return []
|
|
|
|
| 662 |
cfg_res, cfg_search = self.config.get('results', {}), self.config.get('search', {})
|
| 663 |
total_lim, enrich_cnt = cfg_res.get('total_limit', 3), cfg_res.get('enrich_count', 2)
|
| 664 |
enrich_en = self.config.get('enrichment', {}).get('enabled', False) and bool(self.enricher)
|
| 665 |
max_r_pq = cfg_search.get('default_max_results', 3)
|
| 666 |
cache_key = (q, max_r_pq, total_lim, enrich_en, enrich_cnt)
|
| 667 |
+
if not force_refresh and (cached := self.pipeline_cache.get(cache_key)) is not None: return cached
|
| 668 |
+
if force_refresh: self.search_client.cache.clear();
|
| 669 |
+
if self.enricher: self.enricher.cache.clear()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 670 |
all_res, res_proc = [], ResultProcessor(self.config)
|
| 671 |
staged_qs = GaiaQueryBuilder(q, self.config).get_queries()
|
| 672 |
for stage, qs_in_stage in staged_qs.items():
|
| 673 |
for query_s, cat in qs_in_stage:
|
| 674 |
+
if len(all_res) >= total_lim * 2: break
|
|
|
|
|
|
|
| 675 |
s_res = self.search_client.search(query_s, max_results=max_r_pq, force_refresh=force_refresh)
|
| 676 |
all_res.extend(res_proc.process_batch(s_res or [], query_s, initial_cat=cat))
|
| 677 |
all_res.sort(key=lambda x: x.get('combined_score', 0), reverse=True)
|
| 678 |
if enrich_en and self.enricher and all_res:
|
| 679 |
to_enrich = [r for r in all_res[:enrich_cnt] if r.get('href')]
|
| 680 |
+
enriched_map = {item['href']: item for item in self.enricher.enrich_batch(to_enrich, force_refresh=force_refresh) if item.get('href')}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 681 |
temp_results = [enriched_map.get(r['href'], r) if r.get('href') else r for r in all_res]
|
| 682 |
+
all_res = temp_results; all_res.sort(key=lambda x: x.get('combined_score', 0), reverse=True)
|
|
|
|
| 683 |
final_results = all_res[:total_lim]
|
|
|
|
| 684 |
self.pipeline_cache.set(cache_key, final_results)
|
| 685 |
return final_results
|
| 686 |
|
|
|
|
| 687 |
class GaiaLevel1Agent:
|
| 688 |
def __init__(self, api_url: str = DEFAULT_API_URL):
|
| 689 |
self.api_url = api_url
|
|
|
|
| 693 |
if genai and GOOGLE_GEMINI_API_KEY:
|
| 694 |
try:
|
| 695 |
genai.configure(api_key=GOOGLE_GEMINI_API_KEY)
|
| 696 |
+
model_name = 'gemini-2.0-flash'
|
|
|
|
|
|
|
| 697 |
self.llm_model = genai.GenerativeModel(model_name)
|
| 698 |
gaia_logger.info(f"Gemini LLM ('{model_name}') initialized.")
|
| 699 |
except Exception as e:
|
|
|
|
| 708 |
@lru_cache(maxsize=32)
|
| 709 |
def _fetch_and_process_file_content(self, task_id: str) -> Optional[str]:
|
| 710 |
file_url = f"{self.api_url}/files/{task_id}"
|
|
|
|
| 711 |
for attempt in range(2):
|
| 712 |
try:
|
| 713 |
response = requests.get(file_url, timeout=AGENT_DEFAULT_TIMEOUT)
|
|
|
|
| 721 |
filename = header_filename
|
| 722 |
|
| 723 |
content_type = response.headers.get("Content-Type", "")
|
|
|
|
|
|
|
| 724 |
processed_content = FileProcessor.process(response.content, filename, content_type)
|
| 725 |
return processed_content
|
| 726 |
|
|
|
|
| 737 |
if attempt < 1: time.sleep(1)
|
| 738 |
return None
|
| 739 |
|
| 740 |
+
def _parse_llm_output(self, llm_text: str) -> Dict[str, str]:
|
| 741 |
+
reasoning_trace = ""
|
| 742 |
+
model_answer = ""
|
| 743 |
+
|
| 744 |
+
final_answer_sentinel = "FINAL ANSWER:"
|
| 745 |
+
parts = llm_text.split(final_answer_sentinel, 1)
|
| 746 |
+
|
| 747 |
+
if len(parts) == 2:
|
| 748 |
+
reasoning_trace = parts[0].strip()
|
| 749 |
+
model_answer = parts[1].strip()
|
| 750 |
+
else:
|
| 751 |
+
reasoning_trace = llm_text # Fallback: all text is reasoning
|
| 752 |
+
lines = llm_text.strip().split('\n')
|
| 753 |
+
model_answer = lines[-1].strip() if lines else "Could not parse answer" # Fallback: last line is answer
|
| 754 |
+
gaia_logger.warning(f"LLM output did not contain '{final_answer_sentinel}'. Using fallback parsing.")
|
| 755 |
+
|
| 756 |
+
return {"model_answer": model_answer, "reasoning_trace": reasoning_trace}
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
def _formulate_answer_with_llm(self, question: str, file_context: Optional[str], web_context: Optional[str]) -> Dict[str, str]:
|
| 760 |
+
default_error_answer = "Information not available in provided context"
|
| 761 |
+
default_reasoning = "LLM processing failed or context insufficient."
|
| 762 |
+
|
| 763 |
if not self.llm_model:
|
| 764 |
gaia_logger.warning("LLM model (Gemini) not available for answer formulation.")
|
| 765 |
+
reasoning = "LLM model (Gemini) not available for answer formulation."
|
| 766 |
+
answer = default_error_answer
|
| 767 |
if web_context and file_context:
|
| 768 |
+
reasoning += " Context from file and web was found but not processed by LLM."
|
| 769 |
elif web_context:
|
| 770 |
+
reasoning += f" Web context found: {web_context.splitlines()[0] if web_context.splitlines() else 'No specific snippet found.'}"
|
| 771 |
elif file_context:
|
| 772 |
+
reasoning += f" File context found: {file_context[:100]}..."
|
| 773 |
+
else:
|
| 774 |
+
reasoning += " No context found."
|
| 775 |
+
return {"model_answer": answer, "reasoning_trace": reasoning}
|
| 776 |
|
|
|
|
| 777 |
prompt_parts = [
|
| 778 |
"You are a general AI assistant. Your primary goal is to answer the user's question accurately and concisely based *only* on the provided context (from a document and/or web search results).",
|
| 779 |
"First, think step-by-step and briefly explain your reasoning based on the context. This part is for clarity and should come before your final answer.",
|
|
|
|
| 786 |
"Prioritize information from 'Enriched Content' from web search results if available and relevant over shorter 'Snippets'.",
|
| 787 |
"\nUser Question: ", question
|
| 788 |
]
|
|
|
|
| 789 |
|
| 790 |
current_prompt_text_len = sum(len(p) for p in prompt_parts)
|
| 791 |
|
|
|
|
| 792 |
context_added = False
|
| 793 |
if file_context:
|
| 794 |
file_header = "\n\nContext from Provided Document:\n---"
|
| 795 |
file_footer = "\n---"
|
| 796 |
+
max_len_for_file = MAX_CONTEXT_LENGTH_LLM - current_prompt_text_len - (len(web_context) if web_context else 0) - len(file_header) - len(file_footer) - 500
|
| 797 |
|
| 798 |
+
if max_len_for_file > 100 :
|
| 799 |
truncated_file_context = file_context[:max_len_for_file]
|
| 800 |
if len(file_context) > len(truncated_file_context):
|
| 801 |
truncated_file_context += " ... (file context truncated)"
|
|
|
|
| 809 |
if web_context:
|
| 810 |
web_header = "\n\nContext from Web Search Results:\n---"
|
| 811 |
web_footer = "\n---"
|
| 812 |
+
available_len_for_web = MAX_CONTEXT_LENGTH_LLM - current_prompt_text_len - len(web_header) - len(web_footer) - 300
|
|
|
|
| 813 |
|
| 814 |
+
if available_len_for_web > 100:
|
| 815 |
truncated_web_context = web_context
|
| 816 |
if len(web_context) > available_len_for_web:
|
| 817 |
truncated_web_context = web_context[:available_len_for_web] + "\n... (web context truncated)"
|
|
|
|
| 823 |
gaia_logger.warning("Not enough space for web context in LLM prompt, or web context itself is empty.")
|
| 824 |
|
| 825 |
|
| 826 |
+
if not context_added:
|
| 827 |
prompt_parts.append("\n\nNo document or web context could be provided due to length constraints or availability.")
|
| 828 |
|
| 829 |
+
prompt_parts.append("\n\nReasoning and Final Answer:")
|
| 830 |
final_prompt = "\n".join(prompt_parts)
|
| 831 |
|
| 832 |
gaia_logger.info(f"LLM Prompt (first 300): {final_prompt[:300]}...")
|
|
|
|
| 835 |
|
| 836 |
if not GenerationConfig:
|
| 837 |
gaia_logger.error("GenerationConfig not available. Cannot make LLM call.")
|
| 838 |
+
return {"model_answer": "LLM configuration error", "reasoning_trace": "GenerationConfig not available."}
|
| 839 |
|
| 840 |
try:
|
| 841 |
gen_config = GenerationConfig(
|
| 842 |
+
temperature=0.1,
|
| 843 |
+
top_p=0.95,
|
| 844 |
+
max_output_tokens=2048
|
| 845 |
)
|
|
|
|
| 846 |
safety_set = [{"category": c, "threshold": "BLOCK_MEDIUM_AND_ABOVE"} for c in ["HARM_CATEGORY_HARASSMENT", "HARM_CATEGORY_HATE_SPEECH", "HARM_CATEGORY_SEXUALLY_EXPLICIT", "HARM_CATEGORY_DANGEROUS_CONTENT"]]
|
| 847 |
|
| 848 |
response = self.llm_model.generate_content(
|
|
|
|
| 852 |
)
|
| 853 |
|
| 854 |
if not response.candidates or (hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason):
|
| 855 |
+
reason_text = "Unknown"
|
| 856 |
if hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason:
|
| 857 |
+
reason_text = response.prompt_feedback.block_reason.name
|
| 858 |
+
gaia_logger.warning(f"Gemini response blocked. Reason: {reason_text}.")
|
| 859 |
+
return {"model_answer": "Error processing request", "reasoning_trace": f"My response was blocked (Reason: {reason_text})."}
|
|
|
|
| 860 |
|
| 861 |
+
llm_answer_text = response.text
|
| 862 |
+
gaia_logger.info(f"LLM Raw Full Answer (first 200): {llm_answer_text[:200]}...")
|
| 863 |
|
| 864 |
+
return self._parse_llm_output(llm_answer_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
|
| 866 |
except Exception as e:
|
| 867 |
gaia_logger.error(f"Error calling Gemini API: {e}", exc_info=True)
|
| 868 |
error_type_name = type(e).__name__
|
| 869 |
+
reasoning = f"Error calling Gemini API: {error_type_name} - {str(e)}"
|
| 870 |
+
answer = "LLM API error"
|
| 871 |
if "429" in str(e) or "ResourceExhausted" in error_type_name:
|
| 872 |
+
answer = "LLM rate limit"
|
| 873 |
+
reasoning = "Error: LLM temporarily unavailable (rate limit)."
|
| 874 |
+
return {"model_answer": answer, "reasoning_trace": reasoning}
|
| 875 |
|
| 876 |
+
def __call__(self, question: str, task_id: Optional[str] = None) -> Dict[str, str]:
|
|
|
|
|
|
|
| 877 |
gaia_logger.info(f"Agent processing: '{question[:70]}...', TaskID: {task_id}")
|
| 878 |
q_lower = question.lower().strip()
|
| 879 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 880 |
if "what is your name" in q_lower or "who are you" in q_lower:
|
| 881 |
+
return {"model_answer": "general AI assistant", "reasoning_trace": "User asked for my identity."}
|
| 882 |
|
| 883 |
|
| 884 |
file_ctx_str: Optional[str] = None
|
|
|
|
| 885 |
file_kws = ["document", "file", "text", "provide", "attach", "read", "content", "table", "data", "excel", "pdf", "audio", "code", "script", "log"]
|
| 886 |
+
if task_id and (any(kw in q_lower for kw in file_kws) or "this task involves a file" in q_lower):
|
|
|
|
| 887 |
file_ctx_str = self._fetch_and_process_file_content(task_id)
|
| 888 |
if file_ctx_str:
|
| 889 |
gaia_logger.info(f"Processed file context ({len(file_ctx_str)} chars) for task {task_id}")
|
|
|
|
| 892 |
|
| 893 |
web_ctx_str: Optional[str] = None
|
| 894 |
needs_web = True
|
| 895 |
+
if file_ctx_str and len(file_ctx_str) > 300:
|
|
|
|
|
|
|
| 896 |
web_still_needed_kws = [
|
| 897 |
"what is", "who is", "current", "latest", "news", "public opinion",
|
| 898 |
"recent events", "search for", "find information on", "browse", "look up"
|
| 899 |
]
|
|
|
|
| 900 |
doc_can_answer_kws = ["summarize", "according to the document", "in the provided text"]
|
| 901 |
|
| 902 |
if any(kw in q_lower for kw in doc_can_answer_kws) and not any(kw in q_lower for kw in web_still_needed_kws):
|
|
|
|
| 912 |
|
| 913 |
if needs_web:
|
| 914 |
search_q = question.replace("?", "").strip()
|
|
|
|
|
|
|
| 915 |
gaia_logger.info(f"RAG Pipeline initiated for query: {search_q[:70]}")
|
| 916 |
+
rag_res = self.rag_pipeline.analyze(query=search_q, force_refresh=False)
|
| 917 |
if rag_res:
|
| 918 |
snippets = []
|
| 919 |
for i, res_item in enumerate(rag_res):
|
|
|
|
| 922 |
href = res_item.get('href','#')
|
| 923 |
provider = res_item.get('query_tag','WebSearch')
|
| 924 |
prefix = "EnrichedContent" if res_item.get('enriched') else "Snippet"
|
|
|
|
|
|
|
| 925 |
body_preview = (body[:1500] + "...") if len(body) > 1500 else body
|
|
|
|
| 926 |
snippets.append(f"Source [{i+1} - {provider}]: {title}\nURL: {href}\n{prefix}: {body_preview}\n---")
|
| 927 |
web_ctx_str = "\n\n".join(snippets)
|
| 928 |
gaia_logger.info(f"RAG processed {len(rag_res)} sources, total web context length for LLM (pre-truncation): {len(web_ctx_str)} chars.")
|
| 929 |
else:
|
| 930 |
gaia_logger.warning("RAG pipeline yielded no web results for the query.")
|
| 931 |
|
| 932 |
+
agent_response_dict = self._formulate_answer_with_llm(question, file_ctx_str, web_ctx_str)
|
| 933 |
+
gaia_logger.info(f"LLM-based model_answer (first 70): {agent_response_dict.get('model_answer', '')[:70]}...")
|
| 934 |
+
return agent_response_dict
|
|
|
|
|
|
|
| 935 |
|
| 936 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 937 |
space_id = os.getenv("SPACE_ID")
|
| 938 |
+
if profile: username = f"{profile.username}"
|
| 939 |
+
else: return "Please Login to Hugging Face.", None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 940 |
questions_url, submit_url = f"{DEFAULT_API_URL}/questions", f"{DEFAULT_API_URL}/submit"
|
| 941 |
+
try: agent = GaiaLevel1Agent(api_url=DEFAULT_API_URL)
|
| 942 |
+
except Exception as e: return f"Error initializing agent: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 943 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code link unavailable"
|
|
|
|
| 944 |
try:
|
| 945 |
+
response = requests.get(questions_url, timeout=15); response.raise_for_status()
|
|
|
|
| 946 |
questions_data = response.json()
|
| 947 |
+
if not questions_data or not isinstance(questions_data, list): return "Questions list empty/invalid.", None
|
| 948 |
+
except Exception as e: return f"Error fetching questions: {e}", None
|
| 949 |
+
|
| 950 |
+
results_log, answers_payload_for_submission = [], []
|
| 951 |
+
GEMINI_RPM_LIMIT = int(os.getenv("GEMINI_RPM_LIMIT", "60"))
|
| 952 |
+
sleep_llm = (60.0 / GEMINI_RPM_LIMIT) + 0.5 if GEMINI_RPM_LIMIT > 0 else 0.2
|
| 953 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 954 |
for i, item in enumerate(questions_data):
|
| 955 |
task_id, q_text = item.get("task_id"), item.get("question")
|
| 956 |
if not task_id or q_text is None:
|
| 957 |
+
results_log.append({"Task ID": task_id, "Question": q_text, "Model Answer": "SKIPPED", "Reasoning Trace": ""})
|
| 958 |
continue
|
| 959 |
gaia_logger.info(f"Q {i+1}/{len(questions_data)} - Task: {task_id}")
|
| 960 |
+
model_answer_val = "AGENT ERROR"
|
| 961 |
+
reasoning_trace_val = "Agent error occurred."
|
| 962 |
try:
|
| 963 |
+
agent_response_dict = agent(question=q_text, task_id=task_id)
|
| 964 |
+
model_answer_val = agent_response_dict.get("model_answer", "Error: No model_answer key")
|
| 965 |
+
reasoning_trace_val = agent_response_dict.get("reasoning_trace", "")
|
| 966 |
+
|
| 967 |
+
answers_payload_for_submission.append({
|
| 968 |
+
"task_id": task_id,
|
| 969 |
+
"model_answer": model_answer_val,
|
| 970 |
+
"reasoning_trace": reasoning_trace_val
|
| 971 |
+
})
|
| 972 |
+
results_log.append({"Task ID": task_id, "Question": q_text, "Model Answer": model_answer_val, "Reasoning Trace": reasoning_trace_val[:500] + "..." if len(reasoning_trace_val)>500 else reasoning_trace_val})
|
| 973 |
except Exception as e:
|
| 974 |
+
reasoning_trace_val = f"AGENT ERROR: {type(e).__name__} - {e}"
|
| 975 |
+
answers_payload_for_submission.append({
|
| 976 |
+
"task_id": task_id,
|
| 977 |
+
"model_answer": model_answer_val, # "AGENT ERROR"
|
| 978 |
+
"reasoning_trace": reasoning_trace_val
|
| 979 |
+
})
|
| 980 |
+
results_log.append({"Task ID": task_id, "Question": q_text, "Model Answer": model_answer_val, "Reasoning Trace": reasoning_trace_val})
|
| 981 |
+
if i < len(questions_data) - 1: time.sleep(sleep_llm)
|
| 982 |
+
|
| 983 |
+
if not answers_payload_for_submission: return "Agent produced no answers.", pd.DataFrame(results_log or [{"Info": "No questions processed"}])
|
| 984 |
+
|
| 985 |
+
submission_content_lines = []
|
| 986 |
+
for ans_item in answers_payload_for_submission:
|
| 987 |
+
submission_entry = {"task_id": ans_item["task_id"], "model_answer": ans_item["model_answer"]}
|
| 988 |
+
if ans_item.get("reasoning_trace"): # Add reasoning_trace only if it exists and is not empty
|
| 989 |
+
submission_entry["reasoning_trace"] = ans_item["reasoning_trace"]
|
| 990 |
+
submission_content_lines.append(json.dumps(submission_entry))
|
| 991 |
+
|
| 992 |
+
submission_json_lines = "\n".join(submission_content_lines)
|
| 993 |
+
|
| 994 |
+
submission_payload_for_api = {
|
| 995 |
+
"username": username.strip(),
|
| 996 |
+
"agent_code": agent_code,
|
| 997 |
+
"answers_jsonl_string": submission_json_lines
|
| 998 |
+
}
|
| 999 |
+
gaia_logger.info(f"Submitting {len(answers_payload_for_submission)} answers for '{username}'...")
|
| 1000 |
+
gaia_logger.debug(f"Submission payload sample for API: {json.dumps(submission_payload_for_api)[:500]}")
|
| 1001 |
+
|
| 1002 |
try:
|
| 1003 |
+
response = requests.post(submit_url, json=submission_payload_for_api, timeout=60);
|
| 1004 |
response.raise_for_status()
|
| 1005 |
result_data = response.json()
|
| 1006 |
status = (f"Submission Successful!\nUser: {result_data.get('username')}\nScore: {result_data.get('score','N/A')}% "
|
| 1007 |
f"({result_data.get('correct_count','?')}/{result_data.get('total_attempted','?')} correct)\n"
|
| 1008 |
f"Msg: {result_data.get('message','No message.')}")
|
|
|
|
| 1009 |
return status, pd.DataFrame(results_log)
|
| 1010 |
except requests.exceptions.HTTPError as e:
|
| 1011 |
err_detail = f"Server: {e.response.status_code}. Detail: {e.response.text[:200]}"
|
|
|
|
| 1012 |
return f"Submission Failed: {err_detail}", pd.DataFrame(results_log)
|
| 1013 |
+
except Exception as e: return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
| 1014 |
|
| 1015 |
+
with gr.Blocks(title="GAIA RAG Agent - Advanced") as demo:
|
| 1016 |
gr.Markdown("# Gaia Level 1 Agent (RAG & FileProcessor) Evaluation Runner")
|
| 1017 |
gr.Markdown(
|
| 1018 |
"""
|
|
|
|
| 1021 |
2. Click 'Run Evaluation & Submit All Answers'.
|
| 1022 |
---
|
| 1023 |
Agent uses RAG, advanced File Processing, and LLM.
|
| 1024 |
+
**Remember to add `tabulate` to your requirements.txt!**
|
| 1025 |
"""
|
| 1026 |
)
|
| 1027 |
gr.LoginButton()
|
|
|
|
| 1030 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 1031 |
run_button.click(fn=run_and_submit_all, inputs=[], outputs=[status_output, results_table])
|
| 1032 |
|
| 1033 |
+
if __name__ == "__main__":
|
| 1034 |
print("\n" + "-"*30 + " RAG & FileProcessor Agent App Starting " + "-"*30)
|
| 1035 |
+
required_env = {"GOOGLE_GEMINI_API_KEY": GOOGLE_GEMINI_API_KEY, "GOOGLE_API_KEY": GOOGLE_CUSTOM_SEARCH_API_KEY, "GOOGLE_CSE_ID": GOOGLE_CUSTOM_SEARCH_CSE_ID, "TAVILY_API_KEY": TAVILY_API_KEY,}
|
| 1036 |
+
missing_keys = [k for k, v in required_env.items() if not v]
|
| 1037 |
+
for k, v in required_env.items(): print(f"✅ {k} found." if v else f"⚠️ WARNING: {k} not set.")
|
| 1038 |
+
for lib_name, lib_var in [("transformers", hf_transformers_pipeline), ("torch", torch), ("librosa", librosa), ("openpyxl", openpyxl), ("pdfplumber", pdfplumber)]:
|
| 1039 |
+
print(f"✅ {lib_name} lib found." if lib_var else f"⚠️ WARNING: {lib_name} lib missing (some file types may not be processed).")
|
| 1040 |
+
print("👉 REMEMBER TO INSTALL 'tabulate' if you haven't: pip install tabulate")
|
| 1041 |
+
if missing_keys: print(f"\n--- PLEASE SET MISSING ENV VARS: {', '.join(missing_keys)} ---\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1042 |
print("-"*(60 + len(" RAG & FileProcessor Agent App Starting ")) + "\n")
|
| 1043 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, debug=False, share=False)
|
|
|