File size: 26,270 Bytes
3f1068e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | """
Main GAIA Agent implementation
Orchestrates tools, reasoning, and answer extraction
"""
import logging
import json
import os
import time
from typing import Optional, Dict, Any, List, Tuple
from enum import Enum
from dataclasses import dataclass
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
from .claude_client import ClaudeClient
from .answer_extractor import GAIAAnswerExtractor
from .tools import ToolRegistry
from .question_analyzer import GAIAQuestionAnalyzer
from .utils import ResponseCache, PerformanceMonitor, with_retry, get_performance_monitor
from .config import config, is_cache_enabled, is_monitoring_enabled
from . import prompts
logger = logging.getLogger(__name__)
class QuestionType(Enum):
"""Types of GAIA questions"""
MATH = "MATH"
FACTUAL = "FACTUAL"
TEMPORAL = "TEMPORAL"
COMPARISON = "COMPARISON"
MULTI_STEP = "MULTI_STEP"
YES_NO = "YES_NO"
@dataclass
class AgentResponse:
"""Response from GAIA agent"""
answer: str
reasoning: str
tools_used: List[str]
confidence: float
raw_response: str
was_cached: bool = False
response_time: float = 0.0
class GAIAAgent:
"""Main agent for solving GAIA benchmark questions"""
def __init__(self, api_key: Optional[str] = None, verbose: bool = False,
cache_enabled: Optional[bool] = None, cache_ttl: Optional[int] = None):
"""
Initialize GAIA agent with configuration-driven setup
Args:
api_key: Anthropic API key (overrides config)
verbose: Enable verbose logging
cache_enabled: Enable response cache (overrides config if provided)
cache_ttl: Cache TTL in seconds (overrides config if provided)
"""
self.claude = ClaudeClient(api_key=api_key or config.ANTHROPIC_API_KEY)
self.extractor = GAIAAnswerExtractor()
self.tools = ToolRegistry()
self.analyzer = GAIAQuestionAnalyzer()
self.verbose = verbose
# Cache configuration - use config defaults unless overridden
self.cache_enabled = cache_enabled if cache_enabled is not None else is_cache_enabled()
cache_ttl = cache_ttl if cache_ttl is not None else config.CACHE_TTL_SECONDS
# Initialize cache and monitoring based on config
self.cache = ResponseCache(
ttl=cache_ttl,
max_size=config.CACHE_MAX_SIZE
) if self.cache_enabled else None
self.monitor = get_performance_monitor() if is_monitoring_enabled() else None
if verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=getattr(logging, config.LOG_LEVEL, logging.INFO))
logger.info(f"GAIAAgent initialized with:")
logger.info(f" Cache: {'enabled' if self.cache_enabled else 'disabled'}")
logger.info(f" Monitoring: {'enabled' if is_monitoring_enabled() else 'disabled'}")
if self.cache_enabled:
logger.info(f" Cache TTL: {cache_ttl}s, Max Size: {config.CACHE_MAX_SIZE}")
# Log configuration summary in debug mode
if verbose:
logger.debug("\n" + config.summary())
def __call__(self, question: str) -> str:
"""
Simple interface for answering questions
Args:
question: The question to answer
Returns:
The answer string
"""
response = self.answer(question)
return response.answer
def answer(self, question: str, max_retries: int = 2) -> AgentResponse:
"""
Answer a GAIA benchmark question with caching and monitoring.
Args:
question: The question to answer
max_retries: Maximum number of retry attempts
Returns:
AgentResponse with answer and metadata
"""
start_time = time.time()
logger.info(f"Processing question: {question[:100]}...")
# Check cache first
if self.cache_enabled and self.cache:
cached_entry = self.cache.get(question)
if cached_entry:
response_time = time.time() - start_time
logger.info(f"Cache HIT - returning cached answer in {response_time:.3f}s")
# Record cache hit in monitoring (if enabled)
if self.monitor:
self.monitor.record_question(
question=question,
answer=cached_entry.answer,
time_taken=response_time,
tools_used=cached_entry.tools_used or [],
question_type=cached_entry.question_type,
confidence=cached_entry.confidence,
was_cached=True
)
return AgentResponse(
answer=cached_entry.answer,
reasoning="Cached response",
tools_used=cached_entry.tools_used or [],
confidence=cached_entry.confidence or 0.8,
raw_response="[CACHED]",
was_cached=True,
response_time=response_time
)
# Process question normally with retry logic
try:
response = self._answer_with_retry(question, max_retries, start_time)
return response
except Exception as e:
response_time = time.time() - start_time
logger.error(f"Final error processing question after all retries: {e}")
# Record error in monitoring (if enabled)
if self.monitor:
self.monitor.record_error(e, question)
# Last resort - return empty answer
error_response = AgentResponse(
answer="",
reasoning=f"Error: {str(e)}",
tools_used=[],
confidence=0.0,
raw_response="",
was_cached=False,
response_time=response_time
)
# Still record for monitoring (if enabled)
if self.monitor:
self.monitor.record_question(
question=question,
answer="",
time_taken=response_time,
tools_used=[],
confidence=0.0,
was_cached=False
)
return error_response
def _answer_with_retry(self, question: str, max_retries: int, start_time: float) -> AgentResponse:
"""
Process question with retry logic and caching.
Args:
question: The question to answer
max_retries: Maximum retry attempts
start_time: Processing start time
Returns:
AgentResponse with processing results
"""
for attempt in range(max_retries + 1):
try:
# Analyze question
analysis = self.analyzer.analyze(question)
question_type = self._map_to_enum(analysis.question_type)
logger.debug(f"Attempt {attempt + 1}: Question analysis: {analysis.question_type} "
f"(confidence: {analysis.confidence:.2f}, "
f"complexity: {analysis.complexity}, "
f"tools: {analysis.requires_tools})")
# Execute strategy with retry wrapper
response = self._execute_strategy_with_retry(question, question_type, analysis)
# Extract and validate answer
question_type_map = {
QuestionType.MATH: 'math',
QuestionType.YES_NO: 'yes_no',
QuestionType.FACTUAL: 'factual',
QuestionType.COMPARISON: 'factual',
QuestionType.TEMPORAL: 'factual',
QuestionType.MULTI_STEP: 'factual'
}
mapped_type = question_type_map.get(question_type, 'factual')
answer = self.extractor.extract(response, mapped_type)
# Validate answer format if needed
if self._needs_validation(answer, question_type):
answer = self._validate_answer(question, answer)
response_time = time.time() - start_time
confidence = self._calculate_confidence(response, answer)
tools_used = analysis.requires_tools if analysis else self._get_tools_used(question_type)
# Cache successful response
if self.cache_enabled and self.cache and answer:
self.cache.set(
question=question,
answer=answer,
question_type=analysis.question_type,
confidence=confidence,
tools_used=tools_used
)
logger.debug(f"Cached response for question: {question[:50]}...")
# Record in monitoring (if enabled)
if self.monitor:
self.monitor.record_question(
question=question,
answer=answer,
time_taken=response_time,
tools_used=tools_used,
question_type=analysis.question_type,
confidence=confidence,
was_cached=False
)
# Store analysis for potential recovery use
self._current_analysis = analysis
return AgentResponse(
answer=answer,
reasoning=response,
tools_used=tools_used,
confidence=confidence,
raw_response=response,
was_cached=False,
response_time=response_time
)
except Exception as e:
logger.warning(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries:
# Wait before retry with exponential backoff
wait_time = 2 ** attempt
logger.info(f"Retrying in {wait_time}s... ({max_retries - attempt} attempts left)")
time.sleep(wait_time)
else:
# Final attempt failed
raise e
def _execute_strategy_with_retry(self, question: str, question_type: QuestionType, analysis=None) -> str:
"""Execute strategy with retry wrapper."""
@with_retry(max_attempts=2, backoff=1.0, exceptions=(Exception,))
def _execute():
return self._execute_strategy(question, question_type, analysis)
return _execute()
def get_cache_stats(self) -> Dict[str, Any]:
"""Get cache statistics."""
if not self.cache_enabled or not self.cache:
return {"cache_enabled": False}
return {
"cache_enabled": True,
**self.cache.get_stats()
}
def get_performance_stats(self) -> Dict[str, Any]:
"""Get performance statistics."""
if not self.monitor:
return {"monitoring_enabled": False}
return self.monitor.get_stats()
def get_performance_summary(self) -> str:
"""Get formatted performance summary."""
if not self.monitor:
return "Performance monitoring is disabled."
return self.monitor.get_summary()
def clear_cache(self):
"""Clear response cache."""
if self.cache_enabled and self.cache:
self.cache.clear()
logger.info("Response cache cleared")
def reset_metrics(self):
"""Reset performance metrics."""
if self.monitor:
self.monitor.reset()
logger.info("Performance metrics reset")
else:
logger.warning("Performance monitoring is disabled - no metrics to reset")
def _map_to_enum(self, question_type: str) -> QuestionType:
"""Map analyzer question type to enum"""
mapping = {
'math': QuestionType.MATH,
'yes_no': QuestionType.YES_NO,
'factual': QuestionType.FACTUAL,
'comparison': QuestionType.COMPARISON,
'temporal': QuestionType.TEMPORAL,
'list': QuestionType.FACTUAL, # Treat lists as factual
'multi_step': QuestionType.MULTI_STEP
}
return mapping.get(question_type, QuestionType.FACTUAL)
def _execute_strategy(self, question: str, question_type: QuestionType, analysis=None) -> str:
"""Execute strategy based on question type"""
strategies = {
QuestionType.MATH: self._solve_math,
QuestionType.FACTUAL: self._lookup_fact,
QuestionType.TEMPORAL: self._solve_temporal,
QuestionType.COMPARISON: self._compare,
QuestionType.MULTI_STEP: self._multi_step_reasoning,
QuestionType.YES_NO: self._answer_yes_no
}
strategy = strategies.get(question_type, self._multi_step_reasoning)
# Pass analysis to strategy if available
if analysis and hasattr(strategy, '__code__') and 'analysis' in strategy.__code__.co_varnames:
return strategy(question, analysis)
else:
return strategy(question)
def _solve_math(self, question: str) -> str:
"""Solve mathematical question"""
try:
# Get Claude to break down the problem
math_prompt = prompts.MATH_PROMPT.format(question=question)
response = self.claude.query(
math_prompt,
system_prompt=prompts.GAIA_SYSTEM_PROMPT,
temperature=0.1
)
# Extract mathematical expressions
expressions = self._extract_math_expressions(response)
# Calculate each expression
for expr in expressions:
try:
result = self.tools.calculator.calculate(expr)
response += f"\nCalculation: {expr} = {result}"
except:
continue
# Get final answer
final_prompt = f"{response}\n\nBased on these calculations, what is the final answer?\n[ANSWER]"
final_response = self.claude.query(final_prompt, temperature=0.1)
return final_response
except Exception as e:
logger.error(f"Math solving error: {e}")
return self._fallback_approach(question)
def _lookup_fact(self, question: str) -> str:
"""Look up factual information"""
try:
# Try Wikipedia first
wiki_result = self.tools.wikipedia.search(question)
if wiki_result:
prompt = f"Question: {question}\n\nWikipedia says: {wiki_result}\n\n[ANSWER]"
return self.claude.query(prompt, temperature=0.1)
# Try web search
search_results = self.tools.web_search.search(question, max_results=3)
if search_results:
context = "\n".join([r['snippet'] for r in search_results[:2]])
prompt = f"Question: {question}\n\nSearch results:\n{context}\n\n[ANSWER]"
return self.claude.query(prompt, temperature=0.1)
# Fall back to Claude's knowledge
return self._fallback_approach(question)
except Exception as e:
logger.error(f"Factual lookup error: {e}")
return self._fallback_approach(question)
def _solve_temporal(self, question: str) -> str:
"""Solve date/time related question"""
try:
# Check for specific date operations
if "leap year" in question.lower():
# Extract year
import re
year_match = re.search(r'\b(19|20)\d{2}\b', question)
if year_match:
year = int(year_match.group())
is_leap = self.tools.datetime_tool.is_leap_year(year)
return f"[ANSWER]{'yes' if is_leap else 'no'}[/ANSWER]"
# General temporal reasoning
temporal_prompt = prompts.TEMPORAL_PROMPT.format(question=question)
response = self.claude.query(
temporal_prompt,
system_prompt=prompts.GAIA_SYSTEM_PROMPT,
temperature=0.1
)
return response
except Exception as e:
logger.error(f"Temporal solving error: {e}")
return self._fallback_approach(question)
def _compare(self, question: str) -> str:
"""Handle comparison questions"""
try:
# Extract entities to compare
comparison_prompt = prompts.COMPARISON_PROMPT.format(question=question)
# Get information about each entity
response = self.claude.query(
comparison_prompt,
system_prompt=prompts.GAIA_SYSTEM_PROMPT,
temperature=0.3
)
# Search for additional information if needed
if "taller" in question.lower() or "higher" in question.lower():
# Search for height information
entities = self._extract_entities(question)
for entity in entities:
search_result = self.tools.web_search.quick_answer(f"{entity} height")
if search_result:
response += f"\n{entity}: {search_result}"
# Get final answer
final_prompt = f"{response}\n\nBased on this information, answer: {question}\n[ANSWER]"
return self.claude.query(final_prompt, temperature=0.1)
except Exception as e:
logger.error(f"Comparison error: {e}")
return self._fallback_approach(question)
def _multi_step_reasoning(self, question: str) -> str:
"""Handle complex multi-step questions"""
try:
# Use chain of thought
cot_prompt = prompts.CHAIN_OF_THOUGHT_PROMPT.format(question=question)
planning = self.claude.query(cot_prompt, temperature=0.3)
# Execute plan with tools
multi_prompt = prompts.MULTI_STEP_PROMPT.format(question=question)
response = self.claude.query(
multi_prompt,
system_prompt=prompts.GAIA_SYSTEM_PROMPT,
temperature=0.3
)
# Enhance with tool usage based on plan
if "search" in planning.lower():
search_terms = self._extract_search_terms(question)
for term in search_terms[:2]: # Limit searches
results = self.tools.web_search.search(term, max_results=2)
if results:
response += f"\nSearch for '{term}': {results[0]['snippet']}"
# Get final answer
final_prompt = f"{response}\n\nNow provide the final answer to: {question}\n[ANSWER]"
return self.claude.query(final_prompt, temperature=0.1)
except Exception as e:
logger.error(f"Multi-step reasoning error: {e}")
return self._fallback_approach(question)
def _answer_yes_no(self, question: str) -> str:
"""Answer yes/no question"""
try:
response = self.claude.query(
f"Answer this yes/no question: {question}\n\nAnswer with only 'yes' or 'no'.\n[ANSWER]",
system_prompt=prompts.GAIA_SYSTEM_PROMPT,
temperature=0.1
)
return response
except Exception as e:
logger.error(f"Yes/no answer error: {e}")
return self._fallback_approach(question)
def _fallback_approach(self, question: str) -> str:
"""Fallback approach when specific strategy fails"""
try:
prompt = f"""Answer this question as accurately and concisely as possible:
{question}
Remember to follow GAIA format requirements:
- Numbers without units
- Yes/no in lowercase
- Exact names without titles
- Lists with commas, no spaces
[ANSWER]"""
return self.claude.query(
prompt,
system_prompt=prompts.GAIA_SYSTEM_PROMPT,
temperature=0.2
)
except:
return ""
def _recover_from_error(self, question: str, error: str, retries_left: int) -> AgentResponse:
"""Recover from error with alternative approach"""
try:
recovery_prompt = prompts.ERROR_RECOVERY_PROMPT.format(
question=question,
error=error
)
response = self.claude.query(
recovery_prompt,
system_prompt=prompts.GAIA_SYSTEM_PROMPT,
temperature=0.4
)
answer = self.extractor.extract(response, 'factual')
return AgentResponse(
answer=answer,
reasoning=response,
tools_used=["error_recovery"],
confidence=0.5,
raw_response=response
)
except:
if retries_left > 0:
return self.answer(question, max_retries=retries_left)
return AgentResponse(
answer="",
reasoning="Failed to recover from error",
tools_used=[],
confidence=0.0,
raw_response=""
)
def _validate_answer(self, question: str, answer: str) -> str:
"""Validate and correct answer format"""
try:
validation_prompt = prompts.VALIDATION_PROMPT.format(
question=question,
answer=answer
)
response = self.claude.query(validation_prompt, temperature=0.1)
# Extract corrected answer if provided
if "[ANSWER]" in response:
return self.extractor.extract(response, 'factual')
return answer
except:
return answer
def _needs_validation(self, answer: str, question_type: QuestionType) -> bool:
"""Check if answer needs validation"""
# Always validate multi-step and comparison answers
if question_type in [QuestionType.MULTI_STEP, QuestionType.COMPARISON]:
return True
# Validate if answer seems to have extra text
if len(answer) > 50:
return True
# Validate if answer has common issues
if any(word in answer.lower() for word in ['the answer is', 'therefore', 'thus']):
return True
return False
def _extract_math_expressions(self, text: str) -> List[str]:
"""Extract mathematical expressions from text"""
# Simple regex for math expressions
patterns = [
r'\d+\s*[\+\-\*/]\s*\d+', # Basic operations
r'\d+%\s*of\s*\d+', # Percentages
r'\d+\s*\^\s*\d+', # Powers
]
expressions = []
for pattern in patterns:
import re
matches = re.findall(pattern, text)
expressions.extend(matches)
return expressions
def _extract_entities(self, text: str) -> List[str]:
"""Extract entities from text for comparison"""
# Simple extraction - could be enhanced with NER
import re
# Look for capitalized phrases
entities = re.findall(r'[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*', text)
return list(set(entities))
def _extract_search_terms(self, text: str) -> List[str]:
"""Extract search terms from question"""
# Remove common words
stopwords = {'what', 'which', 'who', 'when', 'where', 'how', 'is', 'are', 'was', 'were', 'the', 'a', 'an'}
words = text.lower().split()
terms = [w for w in words if w not in stopwords and len(w) > 3]
# Also extract quoted phrases
import re
quoted = re.findall(r'"([^"]+)"', text)
terms.extend(quoted)
return terms[:5] # Limit to 5 terms
def _get_tools_used(self, question_type: QuestionType) -> List[str]:
"""Get list of tools used for question type"""
tool_map = {
QuestionType.MATH: ["calculator"],
QuestionType.FACTUAL: ["web_search", "wikipedia"],
QuestionType.TEMPORAL: ["datetime"],
QuestionType.COMPARISON: ["web_search"],
QuestionType.MULTI_STEP: ["web_search", "calculator"],
QuestionType.YES_NO: []
}
return tool_map.get(question_type, [])
def _calculate_confidence(self, response: str, answer: str) -> float:
"""Calculate confidence score for answer"""
if not answer:
return 0.0
# Higher confidence if answer was explicitly marked
if "[ANSWER]" in response:
return 0.9
# Lower confidence for long answers (might have extra text)
if len(answer) > 50:
return 0.5
# Medium confidence for short, clean answers
if len(answer) < 20:
return 0.8
return 0.7 |