Spaces:
Sleeping
Sleeping
sync
Browse filesFiles changed (8)
- .DS_StoreAdded
- config.py+4-3
- demo_final_answers.pyAdded+64
- demo_logging.pyAdded+42
- hf_agent.py+527-32
- local_config.json+4
- questions.mdAdded+285
- test_answer_extraction.pyAdded+81
33 unmodified lines343536373839404114 unmodified lines5657585960616239 unmodified lines10210310410510610733 unmodified lines# Ollama models (local inference server)"ollama_models": {"llm_model": "phi4:latest", # Main reasoning model"fallback_model": "gemma3:12b", # Same model as fallback"embedding_model": "nomic-embed-text", # Ollama embedding model"base_url": "http://localhost:11434", # Default Ollama server URL},14 unmodified lines# Generation parameters"temperature": 0.7,"max_new_tokens": 512,"top_p": 0.9,# Local model specific parameters39 unmodified lines"Provide accurate, comprehensive, and concise answers. ""Use available tools to gather current information or perform calculations. ""Focus on precision and exactness in your responses.")}33 unmodified lines343536373839404114 unmodified lines5657585960616239 unmodified lines10210310410510610710833 unmodified lines# Ollama models (local inference server)"ollama_models": {"llm_model": "qwen3:32b", # Main reasoning model"fallback_model": "qwen3:14b", # Fallback model"embedding_model": "nomic-embed-text", # Ollama embedding model"base_url": "http://localhost:11434", # Default Ollama server URL},14 unmodified lines# Generation parameters"temperature": 0.7,"max_new_tokens": 8192,"top_p": 0.9,# Local model specific parameters39 unmodified lines"Provide accurate, comprehensive, and concise answers. ""Use available tools to gather current information or perform calculations. ""Focus on precision and exactness in your responses.""Penguins are birds.")}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364#!/usr/bin/env python3"""Demo script showing final answer extraction for GAIA submissionThe agent now returns only clean, concise answers while logging full responses"""
from hf_agent import SmolagentsGAIAAgent
def test_answer_format(question, expected_format="number/text"): """Test a question and show the answer format""" agent = SmolagentsGAIAAgent() print(f"\n📝 Question: {question}") print(f"🎯 Expected format: {expected_format}") print("-" * 60) result = agent(question) print(f"✅ FINAL ANSWER FOR SUBMISSION: '{result}'") print(f"📊 Length: {len(result)} characters") print(f"📝 Type: {'Number' if result.isdigit() else 'Text'}") return result
def main(): print("🎯 GAIA Final Answer Extraction Demo") print("="*70) print("This demo shows how answers are extracted for submission") print("Full responses are logged to questions.md, but only clean answers are returned") print("="*70) # Test different question types test_cases = [ ("What is 15 + 25?", "number"), ("When was the Eiffel Tower built?", "year"), ("When was Shakespeare born?", "year"), ("Who invented the telephone?", "name"), ("What is the square root of 64?", "number"), ] results = [] for question, expected in test_cases: try: result = test_answer_format(question, expected) results.append((question, result)) except Exception as e: print(f"❌ Error: {e}") results.append((question, f"ERROR: {e}")) print(f"\n{'='*70}") print("📋 SUMMARY - Final Answers for GAIA Submission:") print("="*70) for i, (question, answer) in enumerate(results, 1): print(f"{i:2d}. Q: {question}") print(f" A: '{answer}'") print() print("💾 Full responses with context are saved in questions.md") print("🎯 Only clean answers shown above would be submitted to GAIA")
if __name__ == "__main__": main() 123456789101112131415161718192021222324252627282930313233343536373839404142#!/usr/bin/env python3"""Demo script showing comprehensive agent flow loggingRun with: python demo_logging.py"""
from hf_agent import SmolagentsGAIAAgent
def main(): print("🚀 GAIA Agent Flow Logging Demo") print("="*60) # Initialize agent print("Initializing agent...") agent = SmolagentsGAIAAgent() # Test different types of questions test_questions = [ "What is 25 + 17?", # Math question "When was Shakespeare born?", # Research question "Calculate the square root of 144", # Calculator question "Who invented the telephone?", # Wikipedia research ] print(f"\n🧪 Running {len(test_questions)} test questions...\n") for i, question in enumerate(test_questions, 1): print(f"\n{'='*20} TEST {i}/{len(test_questions)} {'='*20}") print(f"Question: {question}") try: result = agent(question) print(f"✅ SUCCESS: {result}") except Exception as e: print(f"❌ ERROR: {e}") print(f"\n{'='*60}") print("🎯 Demo completed! Check questions.md for full Q&A log") print("📊 All agent flows, tool usage, and model interactions logged")
if __name__ == "__main__": main() 8 unmodified lines91011121314199 unmodified lines21421521621721821922022122222322422522622722822923023123223323423523623716 unmodified lines2542552562572582595 unmodified lines2652662672682692702712722732742754 unmodified lines280281282283284285286287288289290158 unmodified lines44945045145245345445545645745845950 unmodified lines5105115125135145155165175181 unmodified line5205215225235245255265275285295305315325335345355363 unmodified lines54054154254354454532 unmodified lines57857958058158258358436 unmodified lines62162262362462562662775 unmodified lines70370470570670770870971071171271371471571615 unmodified lines7327337347357367377387397407417427437447457467477487497507518 unmodified lines7607617627637647657 unmodified lines7737747757767777782 unmodified lines78178278378478578616 unmodified lines803804805806807808809122 unmodified lines93293393493593693793893994047 unmodified lines9889899909919929939949959967 unmodified lines10041005100610071008100910108 unmodified linesimport requestsfrom typing import Anyimport pandas as pdimport pdfplumberfrom docx import Documentfrom PIL import Image199 unmodified linesclass OllamaModel:"""Wrapper for Ollama models to be compatible with smolagents Model interface"""def __init__(self, model_id, base_url="http://localhost:11434"):self.model_id = model_idself.base_url = base_urlself.last_input_token_count = 0self.last_output_token_count = 0print(f"Initialized Ollama model: {model_id} at {base_url}")# Test connectiontry:import requestsresponse = requests.get(f"{base_url}/api/tags", timeout=5)if response.status_code == 200:print("✓ Ollama server connection successful")else:print("⚠ Ollama server connection failed")except Exception as e:print(f"⚠ Could not connect to Ollama server: {e}")def __call__(self, messages, **kwargs):"""Main interface method expected by smolagents"""16 unmodified lineselse:prompt = str(messages)# Prepare Ollama API requestpayload = {"model": self.model_id,5 unmodified lines}}# Make request to Ollamaresponse = requests.post(f"{self.base_url}/api/generate",json=payload,timeout=60)if response.status_code == 200:4 unmodified linesself.last_input_token_count = len(prompt.split())self.last_output_token_count = len(generated_text.split())return ChatMessage(generated_text, self.last_input_token_count, self.last_output_token_count)else:error_msg = f"Ollama API error: {response.status_code}"return ChatMessage(error_msg, 0, 0)except Exception as e:print(f"Error in Ollama generation: {e}")return ChatMessage(f"Ollama error: {str(e)}", 0, 0)158 unmodified linessearch_result = wikipedia_search_tool(question)# If Wikipedia doesn't have good results, try web searchif "not found" in search_result.lower() or "no wikipedia" in search_result.lower():search_result = web_search_tool(question)# Extract specific answer from search resultsanswer = self._extract_specific_answer(question, search_result)return answerexcept Exception as e:50 unmodified lines# For "when" questions, look for years or dateselif "when" in question.lower():year_match = re.search(r'(19\d\d|20\d\d)', search_content)if year_match:return year_match.group(1)# For "who" questions, look for names (capitalized words)elif "who" in question.lower():1 unmodified lineif name_match:return name_match.group(1)# If no specific pattern found, try to extract the most relevant sentencesentences = search_content.split('.')for sentence in sentences:if any(word in sentence.lower() for word in question.lower().split()[:3]):return sentence.strip()# Fallback: return a shortened version of the search resultsif len(search_content) > 200:return search_content[:200] + "..."return search_contentclass SmolagentsGAIAAgent:"""GAIA Evaluation Agent using Smolagents framework with local/remote model support"""3 unmodified linesself.model_config = get_model_config()self.tools_config = get_tools_config()self.supported_file_types = get_supported_file_types()# Initialize the model (local or remote)self.llm_engine = self._initialize_model()32 unmodified lines# Use Ollama modelreturn OllamaModel(model_id=self.model_config["llm_model"],base_url=self.model_config.get("base_url", "http://localhost:11434"))elif model_type == "openai":36 unmodified linesprint(f"Using Ollama fallback model: {self.model_config['fallback_model']}")return OllamaModel(model_id=self.model_config["fallback_model"],base_url=self.model_config.get("base_url", "http://localhost:11434"))elif model_type == "openai":75 unmodified lines# Create agent based on model capabilitiesmodel_type = self.model_config.get("model_type", "remote")if model_type in ["local", "local_light"]:# For local models like DialoGPT, create a simple conversation-based agentself.agent = SimpleConversationAgent(tools=tools,model=self.llm_engine)elif model_type in ["ollama", "openai", "remote"]:# For Ollama, OpenAI, and remote models, use CodeAgent for better reasoningtry:self.agent = CodeAgent(tools=tools,15 unmodified linesdef __call__(self, question, files=None):"""Main interface for the agent"""try:# Process files if providedfile_context = ""if files:file_context = self._process_files(files)if file_context:question = f"Context from uploaded files:\n{file_context}\n\nQuestion: {question}"# Run the agentresult = self.agent.run(question)return resultexcept Exception as e:return f"I encountered an error while processing your question: {str(e)}. Please try rephrasing your question."def _process_files(self, files):"""Process uploaded files and extract context"""8 unmodified linescontext_parts.append(f"File: {file.name}\nError processing file: {str(e)}")return "\n\n".join(context_parts)# Custom Tools for Smolagents7 unmodified linesReturns:Search results formatted as text"""try:tools_config = get_tools_config()ddgs = DDGS()2 unmodified lines# Clean and optimize querycleaned_query = query.strip()if len(cleaned_query) < 3:return "Query too short. Please provide a more specific search term."16 unmodified linesformatted_results.append(f"**{i}. {title}**\n{snippet}\nSource: {url}")search_summary = f"Found {len(results)} results for '{cleaned_query}':\n\n"return search_summary + "\n\n".join(formatted_results)except Exception as e:return f"Web search failed: {str(e)}. Please try rephrasing your query."122 unmodified linesReturns:Wikipedia article summary and information"""try:# Truncate query to avoid Wikipedia API length limits (max 300 characters)if len(query) > 250:# Extract the most important keywordsimport rewords = query.split()47 unmodified linesReturns:Result of the calculation"""try:# Basic safety checkif any(dangerous in expression.lower() for dangerous in ['import', 'exec', 'eval', '__', 'open', 'file']):return "Error: Unsafe expression detected"# Allow basic math operations and functions7 unmodified lines}result = eval(expression, safe_dict, {})return f"Calculation: {expression} = {result}"except Exception as e:return f"Calculation error: {str(e)}"8 unmodified lines9101112131415199 unmodified lines21521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029116 unmodified lines3083093103113123133143153165 unmodified lines3223233243253263273283293303313324 unmodified lines337338339340341342343344345346347348349350351352353354355356158 unmodified lines51551651751851952052152252352452552652752852953053153253353453553653753850 unmodified lines5895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486491 unmodified line6516526536546556566576586596606616626636646656666676686696706716723 unmodified lines67667767867968068168232 unmodified lines71571671771871972072172236 unmodified lines75976076176276376476576675 unmodified lines84284384484584684784884985085185285385485515 unmodified lines8718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319328 unmodified lines941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912507 unmodified lines12581259126012611262126312642 unmodified lines126712681269127012711272127316 unmodified lines129012911292129312941295129612971298122 unmodified lines1421142214231424142514261427142814291430143147 unmodified lines147914801481148214831484148514861487148814897 unmodified lines1497149814991500150115021503150415058 unmodified linesimport requestsfrom typing import Anyimport pandas as pdfrom datetime import datetimeimport pdfplumberfrom docx import Documentfrom PIL import Image199 unmodified linesclass OllamaModel:"""Wrapper for Ollama models to be compatible with smolagents Model interface"""def __init__(self, model_id, base_url="http://localhost:11434", warmup=True):self.model_id = model_idself.base_url = base_urlself.warmup = warmupself.last_input_token_count = 0self.last_output_token_count = 0print(f"Initialized Ollama model: {model_id} at {base_url}")# Test connection and model availabilitytry:import requestsresponse = requests.get(f"{base_url}/api/tags", timeout=5)if response.status_code == 200:models_data = response.json()available_models = [model['name'] for model in models_data.get('models', [])]if model_id in available_models:print(f"✓ Ollama server connection successful, model '{model_id}' available")# Check if model is already loadedps_response = requests.get(f"{base_url}/api/ps", timeout=5)if ps_response.status_code == 200:loaded_models = [m['name'] for m in ps_response.json().get('models', [])]if model_id in loaded_models:print(f"✓ Model '{model_id}' is already loaded in memory")else:print(f"⚠ Model '{model_id}' not loaded yet - will load on first use")if self.warmup:self._warm_up_model()else:print(" Skipping warmup - model will load on first inference")else:print(f"⚠ Model '{model_id}' not found. Available models: {available_models}")print(f" Run: ollama pull {model_id}")else:print("⚠ Ollama server connection failed")except Exception as e:print(f"⚠ Could not connect to Ollama server: {e}")print(" Make sure Ollama is running: ollama serve")def _warm_up_model(self):"""Warm up the model by sending a simple request to load it into memory"""print(f"🔥 Warming up model '{self.model_id}'... (this may take a few minutes for large models)")try:import requestswarmup_payload = {"model": self.model_id,"prompt": "Hello","stream": False,"options": {"num_predict": 1 # Minimal response to just load the model}}# Send warmup request with extended timeoutresponse = requests.post(f"{self.base_url}/api/generate",json=warmup_payload,timeout=600 # 10 minutes for model loading)if response.status_code == 200:print(f"✓ Model '{self.model_id}' loaded and ready")else:print(f"⚠ Warmup failed: {response.status_code}")except requests.exceptions.Timeout:print(f"⚠ Model loading timeout - model '{self.model_id}' may be too large for available resources")except Exception as e:print(f"⚠ Warmup error: {e}")def __call__(self, messages, **kwargs):"""Main interface method expected by smolagents"""16 unmodified lineselse:prompt = str(messages)print(f"🧠 MODEL: Ollama {self.model_id} generating response...")print(f"📤 Input: {len(prompt)} characters")# Prepare Ollama API requestpayload = {"model": self.model_id,5 unmodified lines}}# Make request to Ollama with extended timeout for large modelsresponse = requests.post(f"{self.base_url}/api/generate",json=payload,timeout=1200 # 20 minutes for large models and slower hardware)if response.status_code == 200:4 unmodified linesself.last_input_token_count = len(prompt.split())self.last_output_token_count = len(generated_text.split())print(f"📥 MODEL: Generated {len(generated_text)} chars, ~{self.last_output_token_count} tokens")print(f"🎯 Response preview: {generated_text[:100]}{'...' if len(generated_text) > 100 else ''}")return ChatMessage(generated_text, self.last_input_token_count, self.last_output_token_count)else:error_msg = f"Ollama API error: {response.status_code}"return ChatMessage(error_msg, 0, 0)except requests.exceptions.Timeout:print(f"Ollama timeout: Model {self.model_id} took too long to respond")return ChatMessage("The model is taking too long to respond. Try a smaller model or increase timeout.", 0, 0)except requests.exceptions.ConnectionError:print("Ollama connection error: Server not reachable")return ChatMessage("Cannot connect to Ollama server. Make sure it's running with 'ollama serve'.", 0, 0)except Exception as e:print(f"Error in Ollama generation: {e}")return ChatMessage(f"Ollama error: {str(e)}", 0, 0)158 unmodified linessearch_result = wikipedia_search_tool(question)# If Wikipedia doesn't have good results, try web searchif ("not found" in search_result.lower() or"no wikipedia" in search_result.lower() or"search result incomplete" in search_result.lower() orsearch_result.startswith("**Wikipedia:") and len(search_result) < 200):print(f"🔄 Wikipedia result incomplete, trying web search...")search_result = web_search_tool(question)# Extract specific answer from search resultsanswer = self._extract_specific_answer(question, search_result)# If no answer was extracted and we haven't tried web search yet, try itif (answer is None andsearch_result.startswith("**Wikipedia:") and"web search" not in locals().get('tried_methods', [])):print(f"🔄 No date found in Wikipedia, trying web search...")search_result = web_search_tool(question)answer = self._extract_specific_answer(question, search_result)return answerexcept Exception as e:50 unmodified lines# For "when" questions, look for years or dateselif "when" in question.lower():# Look for creation/development dates for programming languages, technologiesif "created" in question.lower() or "developed" in question.lower() or "invented" in question.lower():creation_patterns = [r'created in (\d{4})',r'developed in (\d{4})',r'invented in (\d{4})',r'first (?:appeared|released) in (\d{4})',r'(?:created|developed|invented).*?(\d{4})',r'(\d{4}).*?(?:created|developed|invented)',r'since (\d{4})',r'from (\d{4})']for pattern in creation_patterns:match = re.search(pattern, search_content, re.IGNORECASE)if match:return match.group(1)# Look for construction/building dates specificallyif "built" in question.lower() or "constructed" in question.lower():# Look for patterns like "built in 1889", "constructed from 1887 to 1889"built_patterns = [r'built in (\d{4})',r'constructed in (\d{4})',r'built from \d{4} to (\d{4})',r'constructed from \d{4} to (\d{4})',r'construction.*?(\d{4})',r'(\d{4}).*?built',r'(\d{4}).*?constructed']for pattern in built_patterns:match = re.search(pattern, search_content, re.IGNORECASE)if match:return match.group(1)# Look for birth datesif "born" in question.lower():birth_patterns = [r'born.*?(\d{4})',r'(\d{4}).*?born',r'birth.*?(\d{4})']for pattern in birth_patterns:match = re.search(pattern, search_content, re.IGNORECASE)if match:return match.group(1)# General year extraction - look for first reasonable yearyears = re.findall(r'(18\d\d|19\d\d|20\d\d)', search_content)if years:# Filter out obviously wrong years for programming languages (too early)if "programming" in question.lower() or "language" in question.lower():valid_years = [year for year in years if int(year) >= 1950]if valid_years:return valid_years[0]return years[0]# For "who" questions, look for names (capitalized words)elif "who" in question.lower():1 unmodified lineif name_match:return name_match.group(1)# If no specific pattern found, try to extract the most relevant sentencesentences = search_content.split('.')for sentence in sentences:if any(word in sentence.lower() for word in question.lower().split()[:3]):return sentence.strip()# Check if this is a Wikipedia header response - try to get better contentif search_content.startswith("**Wikipedia:"):# Return a message indicating we need better search resultsreturn "Search result incomplete - title only"# Fallback: return a shortened version of the search resultsif len(search_content) > 200:return search_content[:200] + "..."return search_contentclass SmolagentsGAIAAgent:"""GAIA Evaluation Agent using Smolagents framework with local/remote model support"""3 unmodified linesself.model_config = get_model_config()self.tools_config = get_tools_config()self.supported_file_types = get_supported_file_types()self.log_file = "questions.md"# Initialize the model (local or remote)self.llm_engine = self._initialize_model()32 unmodified lines# Use Ollama modelreturn OllamaModel(model_id=self.model_config["llm_model"],base_url=self.model_config.get("base_url", "http://localhost:11434"),warmup=self.model_config.get("warmup", True))elif model_type == "openai":36 unmodified linesprint(f"Using Ollama fallback model: {self.model_config['fallback_model']}")return OllamaModel(model_id=self.model_config["fallback_model"],base_url=self.model_config.get("base_url", "http://localhost:11434"),warmup=self.model_config.get("warmup", True))elif model_type == "openai":75 unmodified lines# Create agent based on model capabilitiesmodel_type = self.model_config.get("model_type", "remote")if model_type in ["local", "local_light", "ollama"]:# For local models and Ollama, create a simple conversation-based agentself.agent = SimpleConversationAgent(tools=tools,model=self.llm_engine)elif model_type in ["openai", "remote"]:# For OpenAI and remote models, use CodeAgent for better reasoningtry:self.agent = CodeAgent(tools=tools,15 unmodified linesdef __call__(self, question, files=None):"""Main interface for the agent"""print(f"\n{'='*60}")print(f"🤖 AGENT FLOW: NEW TASK RECEIVED")print(f"{'='*60}")print(f"📝 Question: {question[:100]}{'...' if len(question) > 100 else ''}")print(f"📁 Files: {len(files) if files else 0} file(s)")print(f"⚙️ Agent Type: {type(self.agent).__name__}")print(f"🧠 Model: {self.model_config.get('llm_model', 'unknown')}")try:# Process files if providedfile_context = ""if files:print(f"\n📂 PROCESSING {len(files)} FILE(S)...")file_context = self._process_files(files)if file_context:print(f"✅ File context extracted: {len(file_context)} characters")question = f"Context from uploaded files:\n{file_context}\n\nQuestion: {question}"else:print(f"⚠️ No content extracted from files")print(f"\n🔄 AGENT EXECUTION STARTING...")print(f"📤 Input to agent: {len(question)} characters")# Run the agent with flow trackingresult = self._run_agent_with_logging(question)print(f"\n✅ AGENT EXECUTION COMPLETED")print(f"📥 Raw output: {len(str(result))} characters")print(f"🎯 Raw result preview: {str(result)[:100]}{'...' if len(str(result)) > 100 else ''}")# Extract final answer for submissionfinal_answer = self._extract_final_answer(result, question)print(f"🎯 Final answer extracted: {final_answer}")# Log the full response (not just the final answer)self._log_qa(question, result)print(f"💾 Q&A logged to {self.log_file}")print(f"{'='*60}\n")return final_answerexcept Exception as e:print(f"\n❌ AGENT ERROR:")print(f" Error type: {type(e).__name__}")print(f" Error message: {str(e)}")print(f" Traceback logged")error_result = f"I encountered an error while processing your question: {str(e)}. Please try rephrasing your question."final_error = self._extract_final_answer(error_result, question)# Log the full error (not just the final answer)self._log_qa(question, error_result)print(f"{'='*60}\n")return final_errordef _process_files(self, files):"""Process uploaded files and extract context"""8 unmodified linescontext_parts.append(f"File: {file.name}\nError processing file: {str(e)}")return "\n\n".join(context_parts)def _run_agent_with_logging(self, question):"""Run the agent with detailed flow logging"""agent_type = type(self.agent).__name__print(f"🔍 Agent Type: {agent_type}")if agent_type == "SimpleConversationAgent":return self._run_simple_agent_with_logging(question)elif agent_type == "CodeAgent":return self._run_code_agent_with_logging(question)else:# Fallback to basic loggingprint(f"⚠️ Unknown agent type: {agent_type}, using basic logging")return self.agent.run(question)def _run_simple_agent_with_logging(self, question):"""Run SimpleConversationAgent with detailed logging"""print(f"🔄 Running SimpleConversationAgent...")# Check if it's a math questionif any(op in question.lower() for op in ['+', '-', '*', '/', 'calculate', 'math', 'what is']):print(f"🔢 Detected math question - trying direct calculation")if '2+2' in question or '2 + 2' in question:print(f"✅ Simple math: 2+2 = 4")return "4"import remath_match = re.search(r'(\d+\s*[+\-*/]\s*\d+)', question)if math_match:print(f"🧮 Found math expression: {math_match.group(1)}")try:result = eval(math_match.group(1))print(f"✅ Calculated result: {result}")return str(result)except Exception as e:print(f"❌ Math calculation failed: {e}")# Check if it needs researchresearch_keywords = ['who', 'what', 'when', 'where', 'how many', 'albums', 'discography', 'born', 'died']if any(keyword in question.lower() for keyword in research_keywords):print(f"🔍 Detected research question - using research and extraction")print(f"🔍 Keywords found: {[kw for kw in research_keywords if kw in question.lower()]}")try:result = self.agent._research_and_extract_answer(question)print(f"📊 Research completed, result length: {len(str(result))} chars")return resultexcept Exception as e:print(f"❌ Research failed: {e}, falling back to model")# Fallback to modelprint(f"🧠 Falling back to model generation...")try:# Try with message format firstmessages = [{"role": "user", "content": question}]print(f"📤 Sending to model: {len(messages)} message(s)")result = self.agent.model(messages)print(f"📥 Model response received")if hasattr(result, 'content'):return result.contentelse:return str(result)except Exception as e:print(f"❌ Message format failed: {e}, trying plain string")try:result = self.agent.model(question)print(f"📥 Plain string response received")return str(result)except Exception as e2:print(f"❌ Plain string also failed: {e2}")raise e2def _run_code_agent_with_logging(self, question):"""Run CodeAgent with detailed logging"""print(f"🔄 Running CodeAgent...")print(f"🛠️ Available tools: {[tool.name for tool in self.agent.tools if hasattr(tool, 'name')]}")try:# CodeAgent handles its own tool selection and executionprint(f"🧠 CodeAgent processing with tool selection...")result = self.agent.run(question)print(f"✅ CodeAgent execution completed")return resultexcept Exception as e:print(f"❌ CodeAgent execution failed: {e}")raise edef _create_answer_extraction_agent(self):"""Create a specialized agent for answer extraction"""try:# Just use the model directly for extraction instead of creating another agentreturn self.llm_engineexcept Exception as e:print(f"⚠️ Failed to create answer extraction agent: {e}")return Nonedef _extract_with_agent(self, response, question):"""Use the model to extract just the answer"""try:model = self._create_answer_extraction_agent()if not model:return Noneextraction_prompt = f"""Given this response to the question "{question}", extract ONLY the final answer.Remove any thinking process, explanations, or extra context.Return only the direct answer (number, year, name, or short phrase).Response: {response}Final answer only:"""print(f"🤖 Using model to extract clean answer...")# Use the model directlyif hasattr(model, '__call__'):extracted = model([{"role": "user", "content": extraction_prompt}])else:extracted = model.generate_response([{"role": "user", "content": extraction_prompt}])if hasattr(extracted, 'content'):result = extracted.content.strip()else:result = str(extracted).strip()# Additional cleaningresult = result.split('\n')[0].strip() # First line onlyresult = re.sub(r'^[*\-\s]+', '', result) # Remove bulletsresult = re.sub(r'<think>.*?</think>', '', result, flags=re.DOTALL | re.IGNORECASE) # Remove any remaining think tagsif len(result) > 0 and len(result) < 100:print(f"🎯 Model extracted: '{result}'")return resultelse:print(f"⚠️ Model extraction result too long or empty: '{result[:50]}...'")return Noneexcept Exception as e:print(f"❌ Model extraction failed: {e}")return Nonedef _extract_final_answer(self, response, question=None):"""Extract the final answer from agent response for submission"""try:response_str = str(response)# Look for **Answer:** pattern (case insensitive)import re# First, remove <think> tags and their content completelycleaned_response = re.sub(r'<think>.*?</think>', '', response_str, flags=re.DOTALL | re.IGNORECASE)print(f"🧹 Cleaned response (removed <think> tags): {len(cleaned_response)} chars")# Try different answer patterns on cleaned responsepatterns = [r'\*\*Answer:\*\*\s*(.*?)(?:\n|$)', # **Answer:** followed by contentr'\*\*Answer\*\*\s*(.*?)(?:\n|$)', # **Answer** followed by contentr'Answer:\s*(.*?)(?:\n|$)', # Answer: followed by contentr'The answer is:?\s*(.*?)(?:\n|$)', # The answer is: followed by contentr'Final answer:?\s*(.*?)(?:\n|$)', # Final answer: followed by content]for pattern in patterns:match = re.search(pattern, cleaned_response, re.IGNORECASE | re.DOTALL)if match:answer = match.group(1).strip()# Clean up common artifactsanswer = re.sub(r'^[*\-\s]+', '', answer) # Remove leading bullets/dashesanswer = re.sub(r'[*\-\s]+$', '', answer) # Remove trailing bullets/dashesanswer = answer.split('\n')[0].strip() # Take only first lineprint(f"🎯 Found answer pattern: {pattern[:20]}... -> '{answer}'")return answer# If no pattern found, process the cleaned responselines = cleaned_response.strip().split('\n')# Filter out empty lines and clean each lineclean_lines = [line.strip() for line in lines if line.strip()]if not clean_lines:print(f"⚠️ No clean lines found after removing <think> tags")# Try agent extraction as fallbackif question:agent_result = self._extract_with_agent(response_str, question)if agent_result:return agent_resultreturn "No clear answer found"# Check if the first clean line is a simple direct answerfirst_clean_line = clean_lines[0]# If it's very short and looks like a direct answer, use itif len(first_clean_line) < 100 and not first_clean_line.startswith(('Found', 'Search', 'Results', 'Error', '**Wikipedia:', '**Article:', 'Hi there!')):print(f"🎯 Using first clean line as answer: '{first_clean_line}'")return first_clean_line# If the response seems conversational or complex, try agent extractionif any(conv in cleaned_response.lower() for conv in ['hi there', 'how can i', 'assist you', 'help you']):print(f"🔄 Detected conversational response, trying agent extraction...")# For simple greetings, return a standard responseif question and question.lower().strip() in ['hi', 'hello', 'hey']:print(f"🎯 Simple greeting detected, returning standard response")return "Hello"if question:agent_result = self._extract_with_agent(response_str, question)if agent_result and len(agent_result) < 200:return agent_result# Look for the most relevant line that looks like an answerfor line in clean_lines:# Skip obviously non-answer linesif line.startswith(('Found', 'Search', 'Results', 'Error', 'Source:', '**Wikipedia:', '**Article:', 'Hi there!', 'How can I')):continue# Skip lines with obvious non-answer contentif any(skip in line.lower() for skip in ['results for', 'wikipedia', 'search', 'tool:', 'error', 'tower (', 'french:', 'assist you', 'help you']):continue# If line is reasonable length and doesn't look like noiseif 3 <= len(line) <= 200:# Look for specific patterns like years for date questionsif re.search(r'\b(18|19|20)\d{2}\b', line):year_match = re.search(r'\b(18|19|20)\d{2}\b', line)if year_match:print(f"🎯 Found year in line: '{year_match.group()}'")return year_match.group()# Look for simple numbersif line.isdigit():print(f"🎯 Found number answer: '{line}'")return line# Use this line if it seems reasonableprint(f"🎯 Using content line: '{line}'")return line# Try agent extraction before giving upif question:print(f"🔄 No clear pattern found, trying agent extraction...")agent_result = self._extract_with_agent(response_str, question)if agent_result:return agent_result# Last resort: return first reasonable chunkif clean_lines:fallback = clean_lines[0][:100].strip()print(f"⚠️ Using fallback from first line: '{fallback}'")return fallbackelse:print(f"⚠️ No usable content found")return "No answer found"except Exception as e:print(f"❌ Answer extraction failed: {e}")# Fallback: try to remove <think> tags manually and return first 100 charstry:import recleaned = re.sub(r'<think>.*?</think>', '', str(response), flags=re.DOTALL | re.IGNORECASE)return cleaned.strip()[:100]except:return str(response)[:100].strip()def _log_qa(self, question, answer):"""Log question and answer to markdown file"""try:timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# Add header if file doesn't exist or is emptyif not os.path.exists(self.log_file) or os.path.getsize(self.log_file) == 0:header = f"""# GAIA Agent Q&A LogThis file contains all questions and answers processed by the GAIA evaluation agent.**Model Configuration:** {self.model_config.get('model_type', 'unknown')} - {self.model_config.get('llm_model', 'unknown')}**Started:** {timestamp}---"""with open(self.log_file, "w", encoding="utf-8") as f:f.write(header)# Create a clean, readable formatlog_entry = f"""## Question ({timestamp})**Q:** {question}**A:** {answer}---"""# Append to log filewith open(self.log_file, "a", encoding="utf-8") as f:f.write(log_entry)except Exception as e:print(f"Failed to log Q&A: {e}")# Custom Tools for Smolagents7 unmodified linesReturns:Search results formatted as text"""print(f"🌐 TOOL: web_search_tool called with query: '{query[:50]}{'...' if len(query) > 50 else ''}'")try:tools_config = get_tools_config()ddgs = DDGS()2 unmodified lines# Clean and optimize querycleaned_query = query.strip()print(f"🔍 Searching with cleaned query: '{cleaned_query}', max_results: {max_results}")if len(cleaned_query) < 3:return "Query too short. Please provide a more specific search term."16 unmodified linesformatted_results.append(f"**{i}. {title}**\n{snippet}\nSource: {url}")search_summary = f"Found {len(results)} results for '{cleaned_query}':\n\n"result = search_summary + "\n\n".join(formatted_results)print(f"✅ TOOL: web_search_tool returned {len(results)} results, {len(result)} chars")return resultexcept Exception as e:return f"Web search failed: {str(e)}. Please try rephrasing your query."122 unmodified linesReturns:Wikipedia article summary and information"""print(f"📚 TOOL: wikipedia_search_tool called with query: '{query[:50]}{'...' if len(query) > 50 else ''}'")try:# Truncate query to avoid Wikipedia API length limits (max 300 characters)if len(query) > 250:print(f"⚠️ Query too long ({len(query)} chars), truncating...")# Extract the most important keywordsimport rewords = query.split()47 unmodified linesReturns:Result of the calculation"""print(f"🧮 TOOL: calculator_tool called with expression: '{expression}'")try:# Basic safety checkif any(dangerous in expression.lower() for dangerous in ['import', 'exec', 'eval', '__', 'open', 'file']):print(f"⚠️ Unsafe expression detected: {expression}")return "Error: Unsafe expression detected"# Allow basic math operations and functions7 unmodified lines}result = eval(expression, safe_dict, {})output = f"Calculation: {expression} = {result}"print(f"✅ TOOL: calculator_tool calculated: {expression} = {result}")return outputexcept Exception as e:return f"Calculation error: {str(e)}"
8 unmodified lines9101112138 unmodified lines"llm_model": "./models/DialoGPT-medium","fallback_model": "./models/Qwen2.5-7B-Instruct","embedding_model": "./models/all-MiniLM-L6-v2"}}8 unmodified lines910111213141516178 unmodified lines"llm_model": "./models/DialoGPT-medium","fallback_model": "./models/Qwen2.5-7B-Instruct","embedding_model": "./models/all-MiniLM-L6-v2"},"ollama_models": {"llm_model": "qwen3:32b","fallback_model": "qwen3:14b"}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285# GAIA Agent Q&A Log
This file contains all questions and answers processed by the GAIA evaluation agent.
**Model Configuration:** ollama - qwen3:32b **Started:** 2025-07-29 01:43:34
---
## Question (2025-07-29 01:43:34)
**Q:** When was Python programming language created?
**A:** 1991
---
## Question (2025-07-29 01:45:21)
**Q:** How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.
**A:** 1
---
## Question (2025-07-29 01:45:22)
**Q:** In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?
**A:** None
---
## Question (2025-07-29 01:46:32)
**Q:** How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.
**A:** 1
---
## Question (2025-07-29 01:46:34)
**Q:** In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?
**A:** None
---
## Question (2025-07-29 01:47:57)
**Q:** .rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI
**A:** <think>Okay, so the user wants me to reverse the word "tfel" and write the opposite of the resulting word in the sentence. Let's break this down step by step.
First, the word given is "tfel". If I reverse it, I need to take each letter and flip their order. Let me write it out: t-f-e-l. Reversing the letters would give me l-e-f-t, which spells "left". Hmm, that's interesting because "tfel" is actually "left" spelled backward. So reversing "tfel" brings it back to "left".
Now, the next part is to write the opposite of that word in the sentence. The original sentence is "If you understand this sentence, write the opposite of the word 'tfel'." So replacing "tfel" with "left" gives us "the opposite of the word 'left'". The opposite of "left" is "right".
Putting it all together, the instruction is to write the opposite of "left", which is "right". So the corrected sentence should be "If you understand this sentence, write the opposite of the word 'left'."
Wait, but the user mentioned the word "tfel" first. So the process is: reverse "tfel" to get "left", then find the opposite of "left", which is "right". Therefore, the answer should be "right". Let me double-check. Reverse "tfel" gives "left", opposite is "right". Yes, that seems correct. I don't think I made any mistakes here. The key was recognizing that "tfel" is just "left" backwards. Then the opposite is straightforward.</think>
If you understand this sentence, write the opposite of the word "left", which is **right**.
The reversed word "tfel" becomes "left", and its opposite is "right".
---
## Question (2025-07-29 01:49:39)
**Q:** Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.
**A:** <think>Okay, let's see. I need to figure out the correct next move for Black that guarantees a win. The problem is that I don't have the actual chess position image, so I can't see the current state of the board. That's a bit of a problem because without knowing where the pieces are, it's impossible to determine the correct move. Hmm.
Wait, maybe the user expects me to explain the process? But the instruction says to provide the correct next move in algebraic notation. Without the position, I can't do that. Maybe there's a standard position or a common puzzle that's implied here? Sometimes, people might refer to well-known positions, like the Scholar's Mate or other common tactical patterns.
Alternatively, perhaps the user made a mistake and forgot to include the image. But assuming that's the case, how should I respond? I can't just guess the position. Maybe I should explain that the image is necessary to provide an accurate answer. However, the user might be testing if I can recognize that the input is missing crucial information.
In any case, the correct approach here is to inform the user that without the chess position image, I can't analyze the move. But since the user might be expecting a placeholder or a hypothetical answer, maybe I should mention that I need more details. But according to the problem, I have to provide the correct move in algebraic notation. If I can't see the board, I have to say I can't do it.
Alternatively, maybe it's a trick question where the position is a forced win for Black regardless, but that seems unlikely. For example, if Black has a queen and the king is in check, but without the actual position, I can't be sure. Maybe the user is using an example from a known puzzle, but I don't have access to that image.
I think the best response is to explain that the image is required to determine the correct move. However, the user might have intended to include the image but forgot. If I proceed without it, my answer would be incorrect. Therefore, I should state that the chess position is needed to provide the correct move in algebraic notation.</think>
The correct next move for Black cannot be determined without the chess position image. Please provide the board configuration or describe the position to enable accurate analysis.
---
## Question (2025-07-29 01:49:41)
**Q:** Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?
**A:** Walt Disney
---
## Question (2025-07-29 01:51:34)
**Q:** Given this table defining * on the set S = {a, b, c, d, e}
|*|a|b|c|d|e||---|---|---|---|---|---||a|a|b|c|b|d||b|b|c|a|e|c||c|c|a|b|b|a||d|b|e|b|e|d||e|d|b|a|d|c|
provide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.
**A:** <think>Okay, so I need to figure out if the operation * defined by this table is commutative or not. If it's not commutative, I need to find the subset of elements involved in any possible counter-examples. The answer should be a comma-separated list of elements in alphabetical order. Alright, let's start by recalling what commutative means. An operation * is commutative if for all x and y in the set, x * y = y * x. So, if there exists even one pair where x * y ≠ y * x, then the operation isn't commutative. My job is to check the table for such pairs and then list the elements involved in those pairs.
First, let me look at the table. The set S is {a, b, c, d, e}. The table has rows labeled a through e, and columns also labeled a through e. The entry in row x and column y gives the value of x * y. To check commutativity, I need to compare x * y with y * x for each pair x, y in S. If they are not equal for some pair, then that pair is a counter-example. Then I need to collect all elements involved in such counter-examples.
Let me start by checking pairs systematically. Maybe I can go through each possible ordered pair (x, y) where x ≠ y and see if x * y equals y * x. If they don't, then note the elements involved.
Let me start with x = a. Since the first row is for a * y, and the first column is for y * a. But since when x = a, comparing with y * a for each y. Wait, maybe it's better to go through all pairs step by step.
Let me create a list of pairs (x, y) where x * y ≠ y * x. Let me check each pair one by one.
Starting with a and b:
a * b is b (from row a, column b). Then b * a is b (from row b, column a). So a * b = b and b * a = b. They are equal. So no problem here.
Next, a and c: a * c is c, and c * a is c. Equal again.
a and d: a * d is b, and d * a is b. Equal.
a and e: a * e is d, and e * a is d. Equal
---
## Question (2025-07-29 01:51:35)
**Q:** Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.
What does Teal'c say in response to the question "Isn't that hot?"
**A:** None
---
## Question (2025-07-29 01:51:37)
**Q:** What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?
**A:** None
---
## Question (2025-07-29 01:51:39)
**Q:** I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:
milk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts
I need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.
**A:** 2025
---
## Question (2025-07-29 01:51:41)
**Q:** Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.
In your response, please only list the ingredients, not any measurements. So if the recipe calls for "a pinch of salt" or "two cups of ripe strawberries" the ingredients on the list would be "salt" and "ripe strawberries".
Please format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.
**A:** None
---
## Question (2025-07-29 01:51:43)
**Q:** Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.
**A:** Everybody Loves
---
## Question (2025-07-29 01:51:47)
**Q:** What is the final numeric output from the attached Python code?
**A:** None
---
## Question (2025-07-29 01:51:49)
**Q:** How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?
**A:** 6
---
## Question (2025-07-29 01:51:52)
**Q:** Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(
Could you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.
**A:** None
---
## Question (2025-07-29 01:51:55)
**Q:** On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?
**A:** None
---
## Question (2025-07-29 01:51:56)
**Q:** Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.
**A:** None
---
## Question (2025-07-29 01:51:57)
**Q:** What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.
**A:** None
---
## Question (2025-07-29 01:51:59)
**Q:** Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.
**A:** Pitcher Before
---
## Question (2025-07-29 01:52:01)
**Q:** The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.
**A:** None
---
## Question (2025-07-29 01:52:02)
**Q:** What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?
**A:** Malko Competition
---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081#!/usr/bin/env python3"""Comprehensive test for answer extraction functionalityShows how <think> tags are removed and clean answers are extracted"""
from hf_agent import SmolagentsGAIAAgent
def test_extraction(): """Test the complete answer extraction pipeline""" agent = SmolagentsGAIAAgent() print("🧪 Testing Answer Extraction for GAIA Submission") print("="*60) # Test cases with different response formats test_cases = [ # Math questions (should be clean already) ("What is 144 / 12?", "number"), # Research questions (should extract years/dates) ("When was Python created?", "year"), ("When was the Eiffel Tower built?", "year"), # Simple greetings (should be handled appropriately) ("hi", "greeting"), # Complex questions that might generate <think> tags ("Who invented the telephone?", "name"), ] results = [] for question, expected_type in test_cases: print(f"\n📝 Testing: {question}") print(f"🎯 Expected type: {expected_type}") print("-" * 40) try: # Get the answer answer = agent(question) # Show the result print(f"✅ FINAL ANSWER: '{answer}'") print(f"📏 Length: {len(answer)} characters") # Analyze the answer is_clean = not any(tag in answer for tag in ['<think>', '</think>', 'Hi there!', 'How can I']) has_year = any(year in answer for year in ['1887', '1889', '1991', '1876']) is_number = answer.isdigit() print(f"🧹 Clean (no <think> tags): {'✅' if is_clean else '❌'}") print(f"🔢 Is number: {'✅' if is_number else '❌'}") print(f"📅 Contains year: {'✅' if has_year else '❌'}") results.append((question, answer, is_clean)) except Exception as e: print(f"❌ ERROR: {e}") results.append((question, f"ERROR: {e}", False)) print(f"\n{'='*60}") print("📋 SUMMARY - All Extracted Answers") print("="*60) clean_count = 0 for i, (question, answer, is_clean) in enumerate(results, 1): status = "✅" if is_clean else "❌" print(f"{i:2d}. {status} Q: {question}") print(f" A: '{answer}'") if is_clean: clean_count += 1 print() success_rate = (clean_count / len(results)) * 100 print(f"🎯 Clean extraction rate: {clean_count}/{len(results)} ({success_rate:.0f}%)") print(f"💾 Full responses logged in questions.md") print(f"🎉 Ready for GAIA evaluation!")
if __name__ == "__main__": test_extraction() .DS_StoreAdded
config.py+4-3
demo_final_answers.pyAdded+64
demo_logging.pyAdded+42
hf_agent.py+527-32
local_config.json+4
questions.mdAdded+285
test_answer_extraction.pyAdded+81