import os import gradio as gr import pandas as pd import requests # Use LiteLLMModel to natively route through Gemini's endpoint matrix from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" def _clean_answer(text: str) -> str: text = text.strip() prefixes = [ "FINAL ANSWER:", "Final Answer:", "Answer:", "ANSWER:", ] for prefix in prefixes: if text.startswith(prefix): text = text[len(prefix) :].strip() break return text class BasicAgent: """Automated Agent running on Google Gemini using Space repository secrets.""" def __init__(self, gemini_key: str): print("Initializing smolagents CodeAgent via Google Gemini endpoint...") if not gemini_key: raise ValueError("GEMINI_API_KEY environment secret is missing from Space Settings.") # Connect straight to Gemini without routing through Hugging Face's credit pool self.model = LiteLLMModel( model_id="gemini/gemini-2.5-flash", api_key=gemini_key ) # Equip with Web Search capabilities for GAIA questions self.search_tool = DuckDuckGoSearchTool() # Initialize CodeAgent engine self.agent = CodeAgent( model=self.model, tools=[self.search_tool], additional_authorized_imports=["math", "json", "re", "collections", "datetime", "urllib"] ) def __call__(self, question: str) -> str: print(f"Agent processing question (first 50 chars): {question[:50]}...") gaia_prompt = ( f"You are an elite agent solving a precise GAIA benchmark question.\n" f"Question: {question}\n\n" f"Execute any python reasoning code or search queries required to find the exact answer. " f"Provide your final answer clearly and concisely at the very end." ) try: output = self.agent.run(gaia_prompt) answer = _clean_answer(str(output)) except Exception as e: print(f"Internal execution pipeline error: {e}") answer = f"ERROR: {e}" print(f"Agent returning answer: {answer}") return answer def run_and_submit_all(profile: gr.OAuthProfile | None): """Fetch all benchmark questions, pull key from background secrets, and submit answers.""" space_id = os.getenv("SPACE_ID") gemini_key = os.getenv("GEMINI_API_KEY") if not gemini_key: return "Error: GEMINI_API_KEY environment secret not found. Please add it to your Space Settings tab.", None if profile: username = f"{profile.username}" print(f"User logged in: {username}") else: print("User not logged in.") return "Please log in to Hugging Face with the button below.", None api_url = DEFAULT_API_URL questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit" try: agent = BasicAgent(gemini_key=gemini_key) except Exception as e: print(f"Error instantiating agent: {e}") return f"Error initializing agent: {str(e)}", None if space_id: agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" else: agent_code = "https://huggingface.co/spaces//tree/main" print(f"Fetching questions from: {questions_url}") try: response = requests.get(questions_url, timeout=15) response.raise_for_status() questions_data = response.json() if not questions_data: return "Fetched questions list is empty or invalid format.", None except Exception as e: return f"Error fetching questions: {e}", None results_log = [] answers_payload = [] print(f"Running agent on {len(questions_data)} questions...") for item in questions_data: task_id = item.get("task_id") question_text = item.get("question") if not task_id or question_text is None: continue try: submitted_answer = agent(question_text) answers_payload.append( {"task_id": task_id, "submitted_answer": submitted_answer} ) results_log.append( { "Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer, } ) except Exception as e: results_log.append( { "Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}", } ) if not answers_payload: return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) submission_data = { "username": username.strip(), "agent_code": agent_code, "answers": answers_payload, } print(f"Submitting answers to: {submit_url}") try: response = requests.post(submit_url, json=submission_data, timeout=60) response.raise_for_status() result_data = response.json() final_status = ( f"Submission Successful!\n" f"User: {result_data.get('username')}\n" f"Overall Score: {result_data.get('score', 'N/A')}% " f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" f"Message: {result_data.get('message', 'No message received.')}" ) return final_status, pd.DataFrame(results_log) except Exception as e: return f"Submission Failed: {e}", pd.DataFrame(results_log) with gr.Blocks() as demo: gr.Markdown("# Fully Automated GAIA Agent Runner (Gemini Mode)") gr.Markdown( """ **Instructions:** 1. Ensure your `GEMINI_API_KEY` is added to your Space's Settings tab. 2. Click the Hugging Face Login Button to authorize your identity. 3. Click **Run Evaluation & Submit All Answers** to process automatically. """ ) gr.LoginButton() run_button = gr.Button("Run Evaluation & Submit All Answers") status_output = gr.Textbox( label="Run Status / Submission Result", lines=5, interactive=False ) results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table] ) if __name__ == "__main__": # Force explicit server network binding to prevent Space hanging on 'Starting' demo.launch(server_name="0.0.0.0", server_port=7860)