maribiel's picture
Deploy GAIA Agent to HuggingFace Space - Final Assignment
65a2540 verified
Raw History Blame Contribute Delete
26.3 kB
"""
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