Spaces:
Sleeping
Sleeping
Joachim M. Vis commited on
Upload 16 files
Browse filesFiles changed (11)
- agent/__pycache__/__init__.cpython-312.pyc
- agent/__pycache__/agent.cpython-312.pyc
- agent/__pycache__/assessment_analyzer.cpython-313.pycAdded
- agent/__pycache__/config.cpython-312.pyc
- agent/__pycache__/config.cpython-313.pyc
- agent/__pycache__/graph.cpython-312.pyc
- agent/__pycache__/graph.cpython-313.pyc
- agent/__pycache__/tool_registry.cpython-313.pyc
- agent/assessment_analyzer.pyAdded+306
- agent/graph.py+18-10
- agent/tool_registry.py+465-237
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306"""
Assessment analyzer for the GAIA agent.
This module provides functionality to analyze assessment results,
categorize questions, calculate success rates, identify error patterns,
and generate recommendations for further improvements.
"""
import logging
from typing import Dict, Any, List, Optional, Set, Tuple
import re
from collections import Counter, defaultdict
logger = logging.getLogger("gaia_agent.assessment_analyzer")
class AnalysisResult:
"""Class to store assessment analysis results."""
def __init__(
self,
category: str,
success_rate: float,
successful_questions: Dict[str, Dict[str, Any]],
failed_questions: Dict[str, Dict[str, Any]],
error_patterns: Dict[str, int],
recommendations: List[str]
):
"""
Initialize the analysis result.
Args:
category: The category of questions analyzed
success_rate: The success rate (0.0 to 1.0)
successful_questions: Dictionary of successfully answered questions
failed_questions: Dictionary of failed questions
error_patterns: Dictionary of error patterns and their frequencies
recommendations: List of recommendations for improvement
"""
self.category = category
self.success_rate = success_rate
self.successful_questions = successful_questions
self.failed_questions = failed_questions
self.error_patterns = error_patterns
self.recommendations = recommendations
def __str__(self) -> str:
"""Return a string representation of the analysis result."""
return (
f"Analysis Result for {self.category} questions:\n"
f"Success Rate: {self.success_rate:.2%}\n"
f"Successful Questions: {len(self.successful_questions)}\n"
f"Failed Questions: {len(self.failed_questions)}\n"
f"Top Error Patterns: {dict(sorted(self.error_patterns.items(), key=lambda x: x[1], reverse=True)[:3])}\n"
f"Recommendations: {self.recommendations}"
)
def categorize_question(question_id: str, question_data: Dict[str, Any]) -> str:
"""
Categorize a question based on its content and ID.
Args:
question_id: The ID of the question
question_data: The question data
Returns:
The category of the question
"""
question_text = question_data.get("question", "").lower()
# Web search questions
web_search_keywords = [
"mercedes sosa", "wikipedia", "featured article", "malko competition",
"yankees", "olympics", "universe today", "polish tv actor"
]
# Multimodal questions
multimodal_keywords = [
"video", "youtube", "watch?v=", "audio", "listen", "chess position", "image"
]
# File processing questions
file_processing_keywords = [
"excel", "spreadsheet", "python code", "execute", "run this code"
]
# Academic paper questions
academic_paper_keywords = [
"arxiv", "paper", "scientific", "research", "publication", "journal"
]
# Mathematical reasoning questions
math_keywords = [
"math", "calculate", "commutativity", "table", "operation", "subset"
]
# Check for web search questions
for keyword in web_search_keywords:
if keyword in question_text:
return "web_search"
# Check for multimodal questions
for keyword in multimodal_keywords:
if keyword in question_text:
return "multimodal"
# Check for file processing questions
for keyword in file_processing_keywords:
if keyword in question_text:
return "file_processing"
# Check for academic paper questions
for keyword in academic_paper_keywords:
if keyword in question_text:
return "academic_paper"
# Check for mathematical reasoning questions
for keyword in math_keywords:
if keyword in question_text:
return "mathematical_reasoning"
# Default to "other" if no category matches
return "other"
def identify_error_patterns(failed_questions: Dict[str, Dict[str, Any]]) -> Dict[str, int]:
"""
Identify common error patterns in failed questions.
Args:
failed_questions: Dictionary of failed questions
Returns:
Dictionary of error patterns and their frequencies
"""
error_patterns = Counter()
for question_id, question_data in failed_questions.items():
error = question_data.get("error", "")
answer = question_data.get("answer", "")
expected_answer = question_data.get("expected_answer", "")
# Check for specific error types
if error:
# Check for timeout-related errors
if any(term in error.lower() for term in ["timeout", "timed out", "time limit"]):
error_patterns["timeout"] += 1
# Check for API-related errors
elif any(term in error.lower() for term in ["api", "rate limit", "quota"]):
error_patterns["api_error"] += 1
# Check for unhashable type errors
elif "unhashable" in error.lower():
error_patterns["unhashable_type"] += 1
else:
error_patterns["other_error"] += 1
# Check for incorrect answers
elif answer and expected_answer and answer != expected_answer:
# Check for partial matches
if any(word in answer.lower() for word in expected_answer.lower().split()):
error_patterns["partial_match"] += 1
else:
error_patterns["completely_wrong_answer"] += 1
else:
error_patterns["unknown_failure"] += 1
return error_patterns
def generate_recommendations(
category: str,
success_rate: float,
error_patterns: Dict[str, int],
failed_questions: Dict[str, Dict[str, Any]]
) -> List[str]:
"""
Generate recommendations for improvement based on analysis.
Args:
category: The category of questions
success_rate: The success rate
error_patterns: Dictionary of error patterns and their frequencies
failed_questions: Dictionary of failed questions
Returns:
List of recommendations
"""
recommendations = []
# General recommendations based on success rate
if success_rate < 0.3:
recommendations.append(f"Major improvements needed for {category} questions")
elif success_rate < 0.7:
recommendations.append(f"Moderate improvements needed for {category} questions")
elif success_rate < 1.0:
recommendations.append(f"Minor improvements needed for {category} questions")
else:
recommendations.append(f"All {category} questions are answered correctly")
# Specific recommendations based on error patterns
if error_patterns.get("timeout", 0) > 0:
recommendations.append("Optimize search performance to prevent timeouts")
if error_patterns.get("api_error", 0) > 0:
recommendations.append("Improve error handling for API failures")
if error_patterns.get("unhashable_type", 0) > 0:
recommendations.append("Fix unhashable type errors in the agent implementation")
if error_patterns.get("partial_match", 0) > 0:
recommendations.append("Improve answer extraction precision")
if error_patterns.get("completely_wrong_answer", 0) > 0:
recommendations.append("Enhance search result relevance filtering")
# Category-specific recommendations
if category == "web_search":
if success_rate < 1.0:
recommendations.append("Implement specialized search for specific domains (Wikipedia, news, etc.)")
recommendations.append("Improve result ranking based on query relevance")
recommendations.append("Add better error handling for failed searches")
elif category == "multimodal":
if success_rate < 1.0:
recommendations.append("Enhance video content extraction capabilities")
recommendations.append("Improve audio transcription accuracy")
recommendations.append("Add specialized image analysis for specific domains")
elif category == "file_processing":
if success_rate < 1.0:
recommendations.append("Improve Excel file parsing and data extraction")
recommendations.append("Enhance code execution sandbox for better isolation")
elif category == "academic_paper":
if success_rate < 1.0:
recommendations.append("Improve arXiv paper content extraction")
recommendations.append("Add support for more academic paper sources")
elif category == "mathematical_reasoning":
if success_rate < 1.0:
recommendations.append("Enhance mathematical operation analysis")
recommendations.append("Improve structured data parsing for tables and matrices")
return recommendations
def analyze_assessment_results(
assessment_results: Dict[str, Dict[str, Any]],
category: Optional[str] = None
) -> AnalysisResult:
"""
Analyze assessment results and generate insights.
Args:
assessment_results: Dictionary of assessment results
category: Optional category to filter questions by
Returns:
AnalysisResult object with analysis results
"""
# Categorize questions
categorized_questions = defaultdict(dict)
for question_id, question_data in assessment_results.items():
question_category = categorize_question(question_id, question_data)
categorized_questions[question_category][question_id] = question_data
# If a specific category is requested, filter questions
if category:
questions_to_analyze = categorized_questions.get(category, {})
category_name = category
else:
questions_to_analyze = assessment_results
category_name = "all"
# Separate successful and failed questions
successful_questions = {}
failed_questions = {}
for question_id, question_data in questions_to_analyze.items():
if question_data.get("correct", False):
successful_questions[question_id] = question_data
else:
failed_questions[question_id] = question_data
# Calculate success rate
total_questions = len(questions_to_analyze)
successful_count = len(successful_questions)
success_rate = successful_count / total_questions if total_questions > 0 else 0.0
# Identify error patterns
error_patterns = identify_error_patterns(failed_questions)
# Generate recommendations
recommendations = generate_recommendations(
category_name,
success_rate,
error_patterns,
failed_questions
)
# Create and return analysis result
return AnalysisResult(
category=category_name,
success_rate=success_rate,
successful_questions=successful_questions,
failed_questions=failed_questions,
error_patterns=error_patterns,
recommendations=recommendations
)409 unmodified lines4104114124134144154165 unmodified lines422423424425426427428429430431432433434435436437438409 unmodified linestry:# Import the tool registry here to avoid circular importsfrom agent.tool_registry import create_default_registry, robust_search, merged_search# Create the tool registryregistry = create_default_registry()5 unmodified linesraise ValueError("Query is required for web search")try:# Try robust search first (falls back to other providers if one fails)result = robust_search(registry, query)logger.info(f"Web search successful using {result.get('provider', 'unknown')}")except Exception as search_error:logger.warning(f"Robust search failed: {str(search_error)}")# If robust search fails, try merged search as a fallbacktry:result = merged_search(registry, query)logger.info("Web search successful using merged results")except Exception as merged_error:logger.error(f"Merged search failed: {str(merged_error)}")raise ValueError(f"All search methods failed: {str(search_error)}")elif tool_name in ["duckduckgo_search", "serper_search", "perplexity_search", "arxiv_search"]:409 unmodified lines4104114124134144154165 unmodified lines422423424425426427428429430431432433434435436437438439440441442443444445446409 unmodified linestry:# Import the tool registry here to avoid circular importsfrom agent.tool_registry import create_default_registry, search, robust_search, merged_search# Create the tool registryregistry = create_default_registry()5 unmodified linesraise ValueError("Query is required for web search")try:# Get working memory if availableworking_memory = Noneif hasattr(state, "get") and callable(state.get):from memory import WorkingMemoryworking_memory_instance = state.get("working_memory")if isinstance(working_memory_instance, WorkingMemory):working_memory = working_memory_instance# Use the unified search wrapper with working memoryresult = search(registry, query, format_type="unified", working_memory=working_memory)logger.info(f"Web search successful using unified search")except Exception as search_error:logger.error(f"Unified search failed: {str(search_error)}")# If unified search fails, try robust search as a fallbacktry:result = robust_search(registry, query)logger.info(f"Web search successful using fallback robust search")except Exception as robust_error:logger.error(f"Robust search failed: {str(robust_error)}")raise ValueError(f"All search methods failed: {str(search_error)}")elif tool_name in ["duckduckgo_search", "serper_search", "perplexity_search", "arxiv_search"]:
10 unmodified lines1112131415161718192021222324252627282958 unmodified lines88899091929394959697989953 unmodified lines15315415515615715845 unmodified lines20420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448510 unmodified linesimport loggingimport osimport refrom typing import Dict, Any, Optional, List, Callablefrom tools.web_tools import (DuckDuckGoSearchTool,SerperSearchTool,WikipediaSearchTool,create_duckduckgo_search,create_serper_search,create_wikipedia_search)from tools.perplexity_tool import PerplexityTool, create_perplexity_toolfrom tools.arxiv_tool import ArxivSearchTool, create_arxiv_searchfrom tools.multimodal_tools import YouTubeVideoTool, create_youtube_video_toollogger = logging.getLogger("gaia_agent.tool_registry")58 unmodified linestry:if name in ["duckduckgo_search", "serper_search", "wikipedia_search"]:query = kwargs.get("query")if not query:raise ValueError("Query is required for search tools")return tool.search(query)elif name == "perplexity_search":query = kwargs.get("query")if not query:53 unmodified lines"""registry = ToolRegistry()# Register DuckDuckGo search tool (no API key required)try:duckduckgo_tool = create_duckduckgo_search()45 unmodified linesexcept Exception as e:logger.warning(f"Failed to create YouTube video tool: {str(e)}")logger.info(f"Created default tool registry with {len(registry.list_tools())} tools")return registrydef robust_search(registry: ToolRegistry, query: str) -> Dict[str, Any]:"""Perform a robust search using multiple providers.This function tries multiple search providers in order, falling back tothe next provider if one fails. It also filters and ranks results by relevance.Args:registry: The tool registryquery: The search queryReturns:Dict with provider name and search resultsRaises:Exception: If all search providers fail"""all_results = []providers_tried = []# Check if the query is specifically about Wikipediais_wikipedia_query = "wikipedia" in query.lower() or "featured article" in query.lower()# Try Wikipedia search first for Wikipedia-specific queriesif is_wikipedia_query and registry.get_tool("wikipedia_search"):providers_tried.append("wikipedia")try:results = registry.execute_tool("wikipedia_search", query=query)if results:all_results.extend(results)if len(results) >= 3: # If we have enough results, return themreturn {"provider": "wikipedia", "results": results}except Exception as e:logger.warning(f"Wikipedia search failed: {str(e)}")# Try DuckDuckGo next (no API key required)if registry.get_tool("duckduckgo_search"):providers_tried.append("duckduckgo")try:results = registry.execute_tool("duckduckgo_search", query=query)if results:all_results.extend(results)if len(results) >= 3: # If we have enough results, return themreturn {"provider": "duckduckgo", "results": results}except Exception as e:logger.warning(f"DuckDuckGo search failed: {str(e)}")# Try Serper as fallbackif registry.get_tool("serper_search"):providers_tried.append("serper")try:results = registry.execute_tool("serper_search", query=query)if results:all_results.extend(results)if len(results) >= 3: # If we have enough results, return themreturn {"provider": "serper", "results": results}except Exception as e:logger.warning(f"Serper search failed: {str(e)}")# Try Perplexity as another optionif registry.get_tool("perplexity_search"):providers_tried.append("perplexity")try:results = registry.execute_tool("perplexity_search", query=query)if results:# Format perplexity results to match other providersformatted_results = []if isinstance(results, dict) and "content" in results:# Create a single result from perplexity contentformatted_results = [{"title": "Perplexity Search Result","link": "https://perplexity.ai/","snippet": results["content"][:500] + "..." if len(results["content"]) > 500 else results["content"],"relevance_score": 5 # Give perplexity a high base score}]all_results.extend(formatted_results)if formatted_results:return {"provider": "perplexity", "results": formatted_results}except Exception as e:logger.warning(f"Perplexity search failed: {str(e)}")# Try arXiv as last resortif registry.get_tool("arxiv_search"):providers_tried.append("arxiv")try:results = registry.execute_tool("arxiv_search", query=query)if results:# Format arXiv results to match other providersformatted_results = []for result in results:formatted_result = {"title": result.get("title", ""),"link": result.get("url", ""),"snippet": result.get("summary", "")[:200] + "..." if result.get("summary") else "","relevance_score": 3 # Give arXiv a medium base score}formatted_results.append(formatted_result)all_results.extend(formatted_results)if formatted_results:return {"provider": "arxiv", "results": formatted_results}except Exception as e:logger.warning(f"arXiv search failed: {str(e)}")# If we have any results from any provider, return themif all_results:# Sort all results by relevance scoreall_results.sort(key=lambda x: x.get("relevance_score", 0), reverse=True)return {"provider": ",".join(providers_tried), "results": all_results}# If all providers failed and we have no results, return an empty result# instead of raising an exceptionlogger.error("All search providers failed, returning empty results")return {"provider": "none", "results": [], "error": "All search providers failed"}def merged_search(registry: ToolRegistry, query: str) -> Dict[str, Any]:"""Perform a merged search using multiple providers.This function collects results from all available search providers,filters them for relevance, ranks them, and merges them into a singleresult set, removing duplicates.Args:registry: The tool registryquery: The search queryReturns:Dict with merged results and Perplexity context"""from tools.web_tools import calculate_query_relevanceresults = {"wikipedia": [],"duckduckgo": [],"serper": [],"perplexity": None,"arxiv": []}# Extract keywords from the query for relevance calculationquery_keywords = set(re.findall(r'\b\w+\b', query.lower()))common_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'with', 'by', 'about'}query_keywords = query_keywords - common_words# Collect results from all providers# Check if query is Wikipedia-specificis_wikipedia_query = "wikipedia" in query.lower() or "featured article" in query.lower()# Try Wikipedia search for Wikipedia-specific queriesif is_wikipedia_query and registry.get_tool("wikipedia_search"):try:results["wikipedia"] = registry.execute_tool("wikipedia_search", query=query)except Exception as e:logger.warning(f"Wikipedia search failed: {str(e)}")if registry.get_tool("duckduckgo_search"):try:results["duckduckgo"] = registry.execute_tool("duckduckgo_search", query=query)except Exception as e:logger.warning(f"DuckDuckGo search failed: {str(e)}")if registry.get_tool("serper_search"):try:results["serper"] = registry.execute_tool("serper_search", query=query)except Exception as e:logger.warning(f"Serper search failed: {str(e)}")if registry.get_tool("perplexity_search"):try:results["perplexity"] = registry.execute_tool("perplexity_search", query=query)except Exception as e:logger.warning(f"Perplexity search failed: {str(e)}")if registry.get_tool("arxiv_search"):try:results["arxiv"] = registry.execute_tool("arxiv_search", query=query, max_results=5)except Exception as e:logger.warning(f"arXiv search failed: {str(e)}")merged = []seen_urls = set()# Process and add Wikipedia results first (if query is Wikipedia-specific)for result in results["wikipedia"]:if result["link"] not in seen_urls:# If result doesn't already have a relevance score, calculate itif "relevance_score" not in result:title_relevance = calculate_query_relevance(result.get("title", ""), query)snippet_relevance = calculate_query_relevance(result.get("snippet", ""), query)# Give Wikipedia results a boost for Wikipedia-specific queriesboost = 1.5 if is_wikipedia_query else 1.0result["relevance_score"] = ((title_relevance * 2 + snippet_relevance) / 3) * boostmerged.append(result)seen_urls.add(result["link"])# Process and add DuckDuckGo resultsfor result in results["duckduckgo"]:if result["link"] not in seen_urls:# If result doesn't already have a relevance score, calculate itif "relevance_score" not in result:title_relevance = calculate_query_relevance(result.get("title", ""), query)snippet_relevance = calculate_query_relevance(result.get("snippet", ""), query)# Title relevance is weighted more heavilyresult["relevance_score"] = (title_relevance * 2 + snippet_relevance) / 3merged.append(result)seen_urls.add(result["link"])# Process and add Serper resultsfor result in results["serper"]:if result["link"] not in seen_urls:# If result doesn't already have a relevance score, calculate itif "relevance_score" not in result:title_relevance = calculate_query_relevance(result.get("title", ""), query)snippet_relevance = calculate_query_relevance(result.get("snippet", ""), query)# Title relevance is weighted more heavilyresult["relevance_score"] = (title_relevance * 2 + snippet_relevance) / 3merged.append(result)seen_urls.add(result["link"])# Process and add arXiv resultsarxiv_results = []for result in results["arxiv"]:if "url" in result and result["url"] not in seen_urls:title = result.get("title", "")summary = result.get("summary", "")# Calculate relevancetitle_relevance = calculate_query_relevance(title, query)summary_relevance = calculate_query_relevance(summary, query)relevance_score = (title_relevance * 2 + summary_relevance) / 3formatted_result = {"title": title,"link": result.get("url", ""),"snippet": summary[:200] + "..." if summary else "","relevance_score": relevance_score}merged.append(formatted_result)seen_urls.add(result["url"])arxiv_results.append(result) # Keep original format for context# Add Perplexity content as context and as a result if relevantperplexity_content = Noneif results["perplexity"] and isinstance(results["perplexity"], dict) and "content" in results["perplexity"]:perplexity_content = results["perplexity"]["content"]# Add perplexity as a result if it's not emptyif perplexity_content and perplexity_content.strip():relevance_score = calculate_query_relevance(perplexity_content, query)# Only add if it's somewhat relevantif relevance_score > 0.2:perplexity_result = {"title": "Perplexity AI Search Result","link": "https://perplexity.ai/","snippet": perplexity_content[:200] + "..." if len(perplexity_content) > 200 else perplexity_content,"relevance_score": relevance_score * 1.5 # Boost perplexity slightly}merged.append(perplexity_result)# Sort merged results by relevance scoremerged.sort(key=lambda x: x.get("relevance_score", 0), reverse=True)return {"merged_results": merged,"perplexity_context": perplexity_content,"arxiv_context": arxiv_results}if __name__ == "__main__":logging.basicConfig(level=logging.INFO)10 unmodified lines1112131415161718192021222324252627282930313233343558 unmodified lines94959697989910010110210310410510610710810911011111211353 unmodified lines16716816917017117217317417517617717817918045 unmodified lines22622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271310 unmodified linesimport loggingimport osimport reimport timefrom typing import Dict, Any, Optional, List, Callablefrom tools.web_tools import (DuckDuckGoSearchTool,SerperSearchTool,EnhancedWebSearchTool,LibrarySearchTool,ApiSearchTool,create_duckduckgo_search,create_serper_search,create_wikipedia_search,create_enhanced_web_search,create_library_search,create_api_search)from tools.perplexity_tool import PerplexityTool, create_perplexity_toolfrom tools.arxiv_tool import ArxivSearchTool, create_arxiv_searchfrom tools.multimodal_tools import YouTubeVideoTool, create_youtube_video_tool, BrowserSearchTool, create_browser_search_toollogger = logging.getLogger("gaia_agent.tool_registry")58 unmodified linestry:if name in ["duckduckgo_search", "serper_search", "wikipedia_search", "enhanced_web_search","library_search", "api_search"]:query = kwargs.get("query")if not query:raise ValueError("Query is required for search tools")return tool.search(query)elif name == "browser_search":query = kwargs.get("query")source = kwargs.get("source")if not query:raise ValueError("Query is required for browser search")return tool.search(query, source)elif name == "perplexity_search":query = kwargs.get("query")if not query:53 unmodified lines"""registry = ToolRegistry()# Register Enhanced Web Search tool (handles GAIA assessment questions)try:enhanced_web_tool = create_enhanced_web_search()registry.register_tool("enhanced_web_search", enhanced_web_tool)logger.info("Registered Enhanced Web Search tool")except Exception as e:logger.warning(f"Failed to create Enhanced Web Search tool: {str(e)}")# Register DuckDuckGo search tool (no API key required)try:duckduckgo_tool = create_duckduckgo_search()45 unmodified linesexcept Exception as e:logger.warning(f"Failed to create YouTube video tool: {str(e)}")# Register Browser Search tooltry:browser_search_tool = create_browser_search_tool()registry.register_tool("browser_search", browser_search_tool)logger.info("Registered Browser Search tool")except Exception as e:logger.warning(f"Failed to create Browser Search tool: {str(e)}")# Register Library Search tooltry:library_search_tool = create_library_search()registry.register_tool("library_search", library_search_tool)logger.info("Registered Library Search tool")except Exception as e:logger.warning(f"Failed to create Library Search tool: {str(e)}")# Register API Search tool if API keys are availableif os.environ.get("PERPLEXITY_API_KEY") or os.environ.get("SERPER_API_KEY"):try:api_search_tool = create_api_search()registry.register_tool("api_search", api_search_tool)logger.info("Registered API Search tool")except Exception as e:logger.warning(f"Failed to create API Search tool: {str(e)}")else:logger.warning("Neither Perplexity nor Serper API keys available, skipping API Search tool")logger.info(f"Created default tool registry with {len(registry.list_tools())} tools")return registrydef analyze_query(query: str) -> Dict[str, Any]:"""Analyze a query to determine the best search strategy.This function examines the query to identify:- Source-specific keywords (Wikipedia, YouTube, arXiv)- Question type (factual, research, multimedia)- Information depth neededArgs:query: The search queryReturns:Dict with analysis results"""analysis = {"source_specific": False,"preferred_sources": [],"question_type": "factual", # Default to factual"depth_needed": "medium", # Default to medium depth"is_multimedia": False}# Check for source-specific keywordsquery_lower = query.lower()# Wikipedia specificif "wikipedia" in query_lower or "featured article" in query_lower:analysis["source_specific"] = Trueanalysis["preferred_sources"].append("wikipedia")# YouTube specificif "youtube" in query_lower or "video" in query_lower:analysis["source_specific"] = Trueanalysis["preferred_sources"].append("youtube")analysis["is_multimedia"] = True# arXiv specificif "arxiv" in query_lower or "paper" in query_lower or "research paper" in query_lower:analysis["source_specific"] = Trueanalysis["preferred_sources"].append("arxiv")analysis["question_type"] = "research"analysis["depth_needed"] = "high"# Determine question type if not already setif "how" in query_lower or "why" in query_lower or "explain" in query_lower:analysis["question_type"] = "explanatory"analysis["depth_needed"] = "high"elif "when" in query_lower or "where" in query_lower or "who" in query_lower:analysis["question_type"] = "factual"elif "compare" in query_lower or "difference" in query_lower:analysis["question_type"] = "comparative"analysis["depth_needed"] = "high"# Check for indicators of needed depthif "detailed" in query_lower or "comprehensive" in query_lower or "in depth" in query_lower:analysis["depth_needed"] = "high"elif "brief" in query_lower or "summary" in query_lower or "overview" in query_lower:analysis["depth_needed"] = "low"return analysisdef unified_search(registry: ToolRegistry, query: str, working_memory=None) -> Dict[str, Any]:"""Perform a unified search using an intelligent routing approach.This function:1. Analyzes the query to determine the best search strategy2. Routes to appropriate tools based on the analysis3. Executes tools in parallel when appropriate4. Stores intermediate results in working_memory5. Combines and ranks resultsArgs:registry: The tool registryquery: The search queryworking_memory: Optional working memory instance for storing resultsReturns:Dict with search results and metadata"""from tools.web_tools import calculate_query_relevanceimport concurrent.futures# Analyze the queryanalysis = analyze_query(query)# Store the analysis in working memory if availableif working_memory:working_memory.store_intermediate_result("query_analysis", analysis)# Initialize results containerall_results = []metadata = {"providers_used": [],"analysis": analysis,"execution_times": {}}# Check if we should use the enhanced web search tool# This tool is especially useful for GAIA assessment questionsif registry.get_tool("enhanced_web_search"):# First try the enhanced web search tool directly (not in parallel)# This is more efficient for GAIA assessment questionstry:logger.info(f"Using enhanced web search for query: {query}")start_time = time.time()enhanced_results = registry.execute_tool("enhanced_web_search", query=query)end_time = time.time()metadata["execution_times"]["enhanced_web_search"] = end_time - start_timemetadata["providers_used"].append("enhanced_web_search")# If we got good results from the enhanced tool, return them directlyif enhanced_results and len(enhanced_results) > 0:# Check if we have a high-quality result (like from Perplexity)has_high_quality = Falsefor result in enhanced_results:if result.get("source") == "perplexity" or result.get("relevance_score", 0) > 8.0:has_high_quality = Truebreakif has_high_quality:logger.info("Enhanced web search returned high-quality results, skipping other tools")# Store results in working memoryif working_memory:working_memory.store_intermediate_result("enhanced_search_results", enhanced_results)return {"results": enhanced_results,"metadata": metadata}except Exception as e:logger.warning(f"Enhanced web search failed: {str(e)}")# Determine which tools to use based on analysistools_to_use = []# If source-specific, prioritize those sourcesif analysis["source_specific"]:for source in analysis["preferred_sources"]:if source == "wikipedia" and registry.get_tool("wikipedia_search"):tools_to_use.append("wikipedia_search")elif source == "youtube" and registry.get_tool("youtube_video"):tools_to_use.append("youtube_video")elif source == "arxiv" and registry.get_tool("arxiv_search"):tools_to_use.append("arxiv_search")# For high depth questions, always include Perplexity if availableif analysis["depth_needed"] == "high" and registry.get_tool("perplexity_search"):if "perplexity_search" not in tools_to_use:tools_to_use.append("perplexity_search")# Check for API search tool (combines Perplexity and Serper)if registry.get_tool("api_search") and "api_search" not in tools_to_use:tools_to_use.append("api_search")# Check for library search tool (combines DuckDuckGo and arXiv)if registry.get_tool("library_search") and "library_search" not in tools_to_use:tools_to_use.append("library_search")# Always include general search tools as fallbacksif registry.get_tool("duckduckgo_search") and "duckduckgo_search" not in tools_to_use:tools_to_use.append("duckduckgo_search")if registry.get_tool("serper_search") and "serper_search" not in tools_to_use:tools_to_use.append("serper_search")# For visual or interactive queries, include browser search toolif analysis["is_multimedia"] and registry.get_tool("browser_search") and "browser_search" not in tools_to_use:tools_to_use.append("browser_search")# Execute tools in parallelresults_dict = {}with concurrent.futures.ThreadPoolExecutor() as executor:future_to_tool = {}for tool_name in tools_to_use:if tool_name == "youtube_video":# YouTube tool requires different handlingcontinuefuture = executor.submit(registry.execute_tool, tool_name, query=query)future_to_tool[future] = tool_namefor future in concurrent.futures.as_completed(future_to_tool):tool_name = future_to_tool[future]try:start_time = time.time()result = future.result()end_time = time.time()metadata["execution_times"][tool_name] = end_time - start_timemetadata["providers_used"].append(tool_name)results_dict[tool_name] = result# Store intermediate results in working memoryif working_memory:working_memory.store_intermediate_result(f"search_result_{tool_name}", result)except Exception as e:logger.warning(f"{tool_name} search failed: {str(e)}")metadata["execution_times"][tool_name] = -1 # Indicate failure# Process and merge resultsseen_urls = set()# Process source-specific results firstfor source in analysis["preferred_sources"]:tool_name = Noneif source == "wikipedia":tool_name = "wikipedia_search"elif source == "arxiv":tool_name = "arxiv_search"if tool_name and tool_name in results_dict:results = results_dict[tool_name]# Format results if neededformatted_results = []if tool_name == "arxiv_search":for result in results:if "url" in result and result["url"] not in seen_urls:title = result.get("title", "")summary = result.get("summary", "")# Calculate relevancetitle_relevance = calculate_query_relevance(title, query)summary_relevance = calculate_query_relevance(summary, query)relevance_score = (title_relevance * 2 + summary_relevance) / 3formatted_result = {"title": title,"link": result.get("url", ""),"snippet": summary[:200] + "..." if summary else "","relevance_score": relevance_score * 1.2, # Boost source-specific results"source": "arxiv"}formatted_results.append(formatted_result)seen_urls.add(result["url"])else:# For other tools, just add source and boost relevancefor result in results:if result["link"] not in seen_urls:if "relevance_score" not in result:title_relevance = calculate_query_relevance(result.get("title", ""), query)snippet_relevance = calculate_query_relevance(result.get("snippet", ""), query)result["relevance_score"] = (title_relevance * 2 + snippet_relevance) / 3# Boost source-specific resultsresult["relevance_score"] = result["relevance_score"] * 1.2result["source"] = sourceformatted_results.append(result)seen_urls.add(result["link"])all_results.extend(formatted_results)# Process general search resultsfor tool_name in ["duckduckgo_search", "serper_search", "library_search", "api_search"]:if tool_name in results_dict:for result in results_dict[tool_name]:if "link" in result and result["link"] not in seen_urls:if "relevance_score" not in result:title_relevance = calculate_query_relevance(result.get("title", ""), query)snippet_relevance = calculate_query_relevance(result.get("snippet", ""), query)result["relevance_score"] = (title_relevance * 2 + snippet_relevance) / 3# If source is not already set, derive it from the tool nameif "source" not in result:result["source"] = tool_name.replace("_search", "")all_results.append(result)seen_urls.add(result["link"])# Process Perplexity resultsif "perplexity_search" in results_dict:perplexity_result = results_dict["perplexity_search"]perplexity_content = Noneif isinstance(perplexity_result, dict) and "content" in perplexity_result:perplexity_content = perplexity_result["content"]# Add perplexity as a result if it's not emptyif perplexity_content and perplexity_content.strip():relevance_score = calculate_query_relevance(perplexity_content, query)# For high depth questions, boost Perplexity even moreif analysis["depth_needed"] == "high":relevance_score = relevance_score * 1.5formatted_result = {"title": "Perplexity AI Search Result","link": "https://perplexity.ai/","snippet": perplexity_content[:200] + "..." if len(perplexity_content) > 200 else perplexity_content,"relevance_score": relevance_score,"source": "perplexity"}all_results.append(formatted_result)# Store the full perplexity content in metadatametadata["perplexity_content"] = perplexity_content# Process Browser Search resultsif "browser_search" in results_dict:browser_results = results_dict["browser_search"]if browser_results and isinstance(browser_results, list):for result in browser_results:if "link" in result and result["link"] not in seen_urls:# Browser search results already have high relevance scoresif "relevance_score" not in result:result["relevance_score"] = 9.0 # High default score for browser resultsall_results.append(result)seen_urls.add(result["link"])# Sort all results by relevance scoreall_results.sort(key=lambda x: x.get("relevance_score", 0), reverse=True)# Store final merged results in working memoryif working_memory:working_memory.store_intermediate_result("merged_search_results", all_results)working_memory.store_intermediate_result("search_metadata", metadata)return {"results": all_results[:10], # Return top 10 results"metadata": metadata}def search(registry: ToolRegistry, query: str, format_type: str = "unified", working_memory=None) -> Dict[str, Any]:"""Unified wrapper function for all search types.This function serves as a single entry point for all search operations,eliminating redundancy while maintaining backward compatibility withdifferent output formats.Args:registry: The tool registryquery: The search queryformat_type: The desired output format ("unified", "robust", or "merged")working_memory: Optional working memory instance for storing resultsReturns:Dict with search results formatted according to format_type"""# Execute the unified searchsearch_result = unified_search(registry, query, working_memory)# Return results in the requested formatif format_type == "robust":# Format as robust_search resultproviders = [result.get("source", "unknown") for result in search_result["results"]]unique_providers = list(set(providers))return {"provider": ",".join(unique_providers),"results": search_result["results"]}elif format_type == "merged":# Format as merged_search resultperplexity_content = search_result["metadata"].get("perplexity_content")# Extract arxiv results if availablearxiv_results = []browser_results = []library_results = []api_results = []for result in search_result["results"]:source = result.get("source", "")if source == "arxiv":# Try to reconstruct original arxiv result formatarxiv_result = {"title": result.get("title", ""),"url": result.get("link", ""),"summary": result.get("snippet", "")}arxiv_results.append(arxiv_result)elif source == "browser":browser_results.append({"title": result.get("title", ""),"url": result.get("link", ""),"snippet": result.get("snippet", "")})elif source == "library":library_results.append({"title": result.get("title", ""),"url": result.get("link", ""),"snippet": result.get("snippet", "")})elif source == "api":api_results.append({"title": result.get("title", ""),"url": result.get("link", ""),"snippet": result.get("snippet", "")})return {"merged_results": search_result["results"],"perplexity_context": perplexity_content,"arxiv_context": arxiv_results,"browser_context": browser_results,"library_context": library_results,"api_context": api_results}else: # "unified" or any other value# Return the unified search result directlyreturn search_resultdef robust_search(registry: ToolRegistry, query: str) -> Dict[str, Any]:"""Legacy robust search function - now uses the unified search wrapper.This function is maintained for backward compatibility.New code should use the 'search' function with format_type="robust".Args:registry: The tool registryquery: The search queryReturns:Dict with provider name and search results"""return search(registry, query, format_type="robust")def merged_search(registry: ToolRegistry, query: str, working_memory=None) -> Dict[str, Any]:"""Legacy merged search function - now uses the unified search wrapper.This function is maintained for backward compatibility.New code should use the 'search' function with format_type="merged".Args:registry: The tool registryquery: The search queryworking_memory: Optional working memory instanceReturns:Dict with merged results and context"""return search(registry, query, format_type="merged", working_memory=working_memory)if __name__ == "__main__":logging.basicConfig(level=logging.INFO)
agent/__pycache__/__init__.cpython-312.pyc
agent/__pycache__/agent.cpython-312.pyc
agent/__pycache__/assessment_analyzer.cpython-313.pycAdded
agent/__pycache__/config.cpython-312.pyc
agent/__pycache__/config.cpython-313.pyc
agent/__pycache__/graph.cpython-312.pyc
agent/__pycache__/graph.cpython-313.pyc
agent/__pycache__/tool_registry.cpython-313.pyc
agent/assessment_analyzer.pyAdded+306
agent/graph.py+18-10
agent/tool_registry.py+465-237