import os import gradio as gr import requests import pandas as pd from smolagents import ( CodeAgent, InferenceClientModel, DuckDuckGoSearchTool, VisitWebpageTool, PythonInterpreterTool, ) # --- Constants --- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" # Modell-ID: starkes, gratis nutzbares Modell ueber die HF Inference API. # Falls es ueberlastet ist, hier ein anderes eintragen, z.B.: # "meta-llama/Llama-3.3-70B-Instruct" MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct") # GAIA wird per EXACT MATCH bewertet -> der Agent darf NUR die nackte Antwort # zurueckgeben. Diese Anweisung wird jeder Frage vorangestellt. GAIA_INSTRUCTIONS = """You are a general AI assistant. Answer the question below. Use the tools available to you (web search, visiting webpages, running Python) when needed. VERY IMPORTANT - how to format your FINAL answer: - Output ONLY the answer itself. No explanation, no full sentence, no "FINAL ANSWER" prefix. - If the answer is a number: write digits only, no commas, no units (unless the unit is explicitly requested). - If the answer is a string: use as few words as possible, no articles, no abbreviations, write digits in plain text unless told otherwise. - If the answer is a comma separated list: apply the rules above to each element and separate with ", ". Question: """ # --- Agent Definition --- class GAIAAgent: def __init__(self): print("GAIAAgent initializing...") token = os.getenv("HF_TOKEN") # in deinem Space als Secret setzen model = InferenceClientModel(model_id=MODEL_ID, token=token) self.agent = CodeAgent( model=model, tools=[ DuckDuckGoSearchTool(), VisitWebpageTool(), PythonInterpreterTool(), ], max_steps=8, verbosity_level=1, add_base_tools=False, ) print(f"GAIAAgent ready (model={MODEL_ID}).") def __call__(self, question: str) -> str: print(f"Agent received question (first 60 chars): {question[:60]}...") try: prompt = GAIA_INSTRUCTIONS + question answer = self.agent.run(prompt) answer = str(answer).strip() # Sicherheitsnetz: ein evtl. vorangestelltes "FINAL ANSWER:" entfernen. for prefix in ("FINAL ANSWER:", "Final answer:", "Answer:"): if answer.startswith(prefix): answer = answer[len(prefix):].strip() print(f"Agent answer: {answer}") return answer except Exception as e: print(f"Agent error: {e}") return f"AGENT ERROR: {e}" def run_and_submit_all(profile: gr.OAuthProfile | None): """ Holt alle Fragen, laesst den Agenten laufen, sendet die Antworten und zeigt das Ergebnis. """ space_id = os.getenv("SPACE_ID") if profile: username = f"{profile.username}" print(f"User logged in: {username}") else: print("User not logged in.") return "Please Login to Hugging Face with the button.", None api_url = DEFAULT_API_URL questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit" # 1. Agent instanziieren try: agent = GAIAAgent() except Exception as e: print(f"Error instantiating agent: {e}") return f"Error initializing agent: {e}", None agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" print(agent_code) # 2. Fragen holen 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: print("Fetched questions list is empty.") return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.") except requests.exceptions.RequestException as e: print(f"Error fetching questions: {e}") return f"Error fetching questions: {e}", None except Exception as e: print(f"An unexpected error occurred fetching questions: {e}") return f"An unexpected error occurred fetching questions: {e}", None # 3. Agent laufen lassen 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: print(f"Skipping item with missing task_id or question: {item}") 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: print(f"Error running agent on task {task_id}: {e}") results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"}) if not answers_payload: print("Agent did not produce any answers to submit.") return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) # 4. Submission vorbereiten submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." print(status_update) # 5. Senden print(f"Submitting {len(answers_payload)} answers to: {submit_url}") try: response = requests.post(submit_url, json=submission_data, timeout=120) 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.')}" ) print("Submission successful.") results_df = pd.DataFrame(results_log) return final_status, results_df except requests.exceptions.HTTPError as e: error_detail = f"Server responded with status {e.response.status_code}." try: error_json = e.response.json() error_detail += f" Detail: {error_json.get('detail', e.response.text)}" except requests.exceptions.JSONDecodeError: error_detail += f" Response: {e.response.text[:500]}" status_message = f"Submission Failed: {error_detail}" print(status_message) return status_message, pd.DataFrame(results_log) except requests.exceptions.Timeout: status_message = "Submission Failed: The request timed out." print(status_message) return status_message, pd.DataFrame(results_log) except requests.exceptions.RequestException as e: status_message = f"Submission Failed: Network error - {e}" print(status_message) return status_message, pd.DataFrame(results_log) except Exception as e: status_message = f"An unexpected error occurred during submission: {e}" print(status_message) return status_message, pd.DataFrame(results_log) # --- Gradio Interface --- with gr.Blocks() as demo: gr.Markdown("# GAIA Agent Evaluation Runner") gr.Markdown( """ **Anleitung:** 1. Logge dich mit dem Button unten bei Hugging Face ein. 2. Klicke auf 'Run Evaluation & Submit All Answers'. 3. Der Agent beantwortet die 20 GAIA-Fragen und sendet sie automatisch ein. --- Hinweis: Der Durchlauf kann mehrere Minuten dauern (der Agent geht alle Fragen einzeln durch). Setze in den Space-Settings das Secret **HF_TOKEN** (dein Hugging Face Access Token), damit das Modell laeuft. """ ) 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__": print("\n" + "-" * 30 + " App Starting " + "-" * 30) space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") if space_host_startup: print(f"SPACE_HOST found: {space_host_startup}") else: print("SPACE_HOST not found (running locally?).") if space_id_startup: print(f"SPACE_ID found: {space_id_startup}") print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main") else: print("SPACE_ID not found (running locally?).") print("-" * 74 + "\n") print("Launching Gradio Interface for GAIA Agent Evaluation...") demo.launch(debug=True, share=False)