Update app.py
Browse files12343 unmodified lines8910111213141516171819202122232425262728291 unmodified line3132333435363738394041424344454647483 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353 unmodified lines33934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447511 unmodified lines487488489490491492493494495496497498499500501502503504505506507508509510511512import osimport gradio as grimport pandas as pd3 unmodified linesCodeAgent,DuckDuckGoSearchTool,InferenceClientModel,)# ---------------------------------------------------------# Configuration# ---------------------------------------------------------DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# ---------------------------------------------------------# Agent# ---------------------------------------------------------class BasicAgent:def __init__(self):print("Initializing GAIA agent...")hf_token = os.getenv("HF_TOKEN")1 unmodified lineif not hf_token:raise RuntimeError("HF_TOKEN is missing. ""Add it in Space -> Settings -> Variables and secrets.")self.model = InferenceClientModel(token=hf_token)self.agent = CodeAgent(tools=[DuckDuckGoSearchTool(),],model=self.model,additional_authorized_imports=["requests","re",3 unmodified lines"statistics","collections","itertools",],max_steps=12,)print("GAIA agent initialized successfully.")def __call__(self, question: str) -> str:print("\n" + "=" * 80)print("QUESTION:")print(question)print("=" * 80)prompt = f"""You are an autonomous agent solving a GAIA benchmark question.Your objective is to determine the exact final answer.You may use:- web search- Python/code- HTTP requests- calculations- text processingInstructions:1. Read the question extremely carefully.2. Determine whether the answer can be derived directly or whetherexternal research is necessary.3. When current or factual information is required, use web search.4. When calculations, transformations, counting, decoding, reversingtext, parsing, or similar operations are required, use Python.5. Verify important facts whenever possible.6. Pay very close attention to requested formatting.7. The final response MUST contain ONLY the answer.Do NOT include:- explanations- reasoning- citations- "FINAL ANSWER:"- introductory textExamples of valid final responses:7Mercedes SosaParis12, 15, 18The answer should be as short and exact as possible.QUESTION:{question}"""try:result = self.agent.run(prompt)answer = str(result).strip()# Some models may still prepend FINAL ANSWER.prefixes = ["FINAL ANSWER:","Final Answer:","Final answer:",]for prefix in prefixes:if answer.startswith(prefix):answer = answer[len(prefix):].strip()print("\nAGENT FINAL ANSWER:")print(answer)return answerexcept Exception as e:print(f"Agent error: {e}")return ""# ---------------------------------------------------------# Evaluation# ---------------------------------------------------------def run_and_submit_all(profile: gr.OAuthProfile | None):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.", Noneapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# -----------------------------------------------------# Initialize agent# -----------------------------------------------------try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return (f"Error initializing agent: {e}",None,)# Public link to your agent source codeagent_code = (f"https://huggingface.co/spaces/"f"{space_id}/tree/main")print(f"Agent code: {agent_code}")# -----------------------------------------------------# Fetch questions# -----------------------------------------------------print(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url,timeout=30,)response.raise_for_status()questions_data = response.json()if not questions_data:return ("Fetched questions list is empty or invalid.",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"Unexpected error fetching questions: {e}")return (f"Unexpected error fetching questions: {e}",None,)# -----------------------------------------------------# Run agent# -----------------------------------------------------results_log = []answers_payload = []print(f"Running agent on "f"{len(questions_data)} questions...")for index, item in enumerate(questions_data,start=1,):task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:print(f"Skipping invalid question: {item}")continueprint("\n" + "#" * 80)print(f"QUESTION "f"{index}/{len(questions_data)}")print(f"Task ID: {task_id}")try:submitted_answer = agent(question_text)except Exception as e:print(f"Error running agent on "f"{task_id}: {e}")submitted_answer = ""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,})# -----------------------------------------------------# Ensure answers exist# -----------------------------------------------------if not answers_payload:return ("Agent did not produce any answers.",pd.DataFrame(results_log),)# -----------------------------------------------------# Submission payload# -----------------------------------------------------submission_data = {"username": username.strip(),"agent_code": agent_code,"answers": answers_payload,}print(f"Agent finished. Submitting "f"{len(answers_payload)} answers "f"for user '{username}'...")# -----------------------------------------------------# Submit# -----------------------------------------------------try:response = requests.post(submit_url,3 unmodified linesresponse.raise_for_status()result_data = response.json()final_status = ("Submission Successful!\n"f"User: "f"{result_data.get('username')}\n"f"Overall Score: "f"{result_data.get('score', 'N/A')}% "f"("f"{result_data.get('correct_count', '?')}/"f"{result_data.get('total_attempted', '?')}"f" correct)\n"f"Message: "f"{result_data.get('message', 'No message received.')}")print(final_status)return (final_status,pd.DataFrame(results_log),)except requests.exceptions.HTTPError as e:error_detail = (f"Server responded with status "f"{e.response.status_code}.")try:error_json = e.response.json()error_detail += (f" Detail: "f"{error_json.get('detail', e.response.text)}")except Exception:error_detail += (f" Response: "f"{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: "f"Network error - {e}")print(status_message)return (status_message,pd.DataFrame(results_log),)except Exception as e:status_message = (f"Unexpected submission error: {e}")print(status_message)return (status_message,pd.DataFrame(results_log),)# ---------------------------------------------------------# Gradio UI# ---------------------------------------------------------with gr.Blocks() as demo:gr.Markdown("# GAIA Agent Evaluation Runner")gr.Markdown("""### Instructions1. Log in with your Hugging Face account.2. Click **Run Evaluation & Submit All Answers**.3. The agent will fetch the GAIA questions.4. It will solve each question.5. Answers will automatically be submitted.6. Your score will appear below.The evaluation can take several minutes.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result",lines=6,interactive=False,)11 unmodified lines)# ---------------------------------------------------------# Start# ---------------------------------------------------------if __name__ == "__main__":print("\n" + "=" * 80)print("Starting GAIA Agent Space")print(f"SPACE_ID: "f"{os.getenv('SPACE_ID', 'not found')}")print(f"SPACE_HOST: "f"{os.getenv('SPACE_HOST', 'not found')}")print("=" * 80 + "\n")demo.launch(1234563 unmodified lines1011121314151617181920212223242526272829303132333435361 unmodified line383940414243444546474849505152535455565758596061626364653 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743 unmodified lines37837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446511 unmodified lines477478479480481482483484485486487488489490491492493import osimport reimport tracebackimport gradio as grimport pandas as pd3 unmodified linesCodeAgent,DuckDuckGoSearchTool,InferenceClientModel,VisitWebpageTool,)# =========================================================# CONFIG# =========================================================DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# Explicit model instead of relying on a changing default.MODEL_ID = "Qwen/Qwen3-Next-80B-A3B-Thinking"# =========================================================# AGENT# =========================================================class BasicAgent:def __init__(self):print("=" * 80)print("Initializing GAIA agent...")hf_token = os.getenv("HF_TOKEN")1 unmodified lineif not hf_token:raise RuntimeError("HF_TOKEN is missing. ""Add HF_TOKEN in Space -> Settings -> Variables and secrets.")print(f"Using model: {MODEL_ID}")self.model = InferenceClientModel(model_id=MODEL_ID,token=hf_token,timeout=180,)self.agent = CodeAgent(model=self.model,tools=[DuckDuckGoSearchTool(max_results=10,rate_limit=1.0,),VisitWebpageTool(max_output_length=30000,),],additional_authorized_imports=["requests","re",3 unmodified lines"statistics","collections","itertools","urllib.parse",],max_steps=15,)print("GAIA agent initialized successfully.")print("=" * 80)def clean_answer(self, value) -> str:if value is None:return ""answer = str(value).strip()# Remove common prefixes if model ignored instructions.answer = re.sub(r"^\s*(FINAL\s+ANSWER|Final\s+Answer|Final\s+answer)\s*:\s*","",answer,flags=re.IGNORECASE,)# Remove surrounding whitespace/newlines.answer = answer.strip()return answerdef __call__(self, question: str) -> str:print("\n" + "=" * 80)print("QUESTION")print("=" * 80)print(question)print("=" * 80)prompt = f"""You are solving one GAIA benchmark question.Your goal is to obtain the exact answer, not merely explain how tofind it.You have web-search and webpage-reading tools. You can also executePython code.Work autonomously.Rules:1. Carefully determine exactly what the question asks.2. If the question requires factual information, search the web.3. Do not trust only a search-result snippet when the underlying pagecan be inspected. Open relevant pages and verify the information.4. If Wikipedia is explicitly mentioned, search for the relevantWikipedia page and inspect the required information.5. For counting, arithmetic, dates, string transformations, reversingtext, decoding, sorting, comparison, or other deterministic work,use Python when useful.6. Cross-check ambiguous information when possible.7. Pay extremely close attention to the requested output format.8. Your final answer must be minimal. Examples:7ParisMercedes Sosa12, 15, 18Qh49. Do NOT put explanations, citations, reasoning, Markdown, or"FINAL ANSWER:" in the final answer.10. If the question contains a URL, investigate that URL or search forinformation related to it when useful.QUESTION:{question}Solve the problem and return only the exact final answer."""result = self.agent.run(prompt)answer = self.clean_answer(result)if not answer:raise RuntimeError("The agent completed without returning a final answer.")print("\n" + "-" * 80)print("FINAL ANSWER:")print(answer)print("-" * 80)return answer# =========================================================# FETCH QUESTIONS# =========================================================def fetch_questions():questions_url = f"{DEFAULT_API_URL}/questions"print(f"Fetching questions from: {questions_url}")response = requests.get(questions_url,timeout=30,)response.raise_for_status()data = response.json()if not isinstance(data, list) or not data:raise RuntimeError("The scoring API returned an empty or invalid questions list.")print(f"Fetched {len(data)} questions.")return data# =========================================================# EVALUATION# =========================================================def run_and_submit_all(profile: gr.OAuthProfile | None):if not profile:return ("Please log in to Hugging Face first.",pd.DataFrame(),)username = str(profile.username).strip()print("\n" + "#" * 80)print(f"USER: {username}")print("#" * 80)space_id = os.getenv("SPACE_ID")if not space_id:return ("SPACE_ID environment variable is missing.",pd.DataFrame(),)agent_code = (f"https://huggingface.co/spaces/{space_id}/tree/main")# -----------------------------------------------------# Initialize agent# -----------------------------------------------------try:agent = BasicAgent()except Exception as e:traceback.print_exc()return (f"Error initializing agent:\n{type(e).__name__}: {e}",pd.DataFrame(),)# -----------------------------------------------------# Fetch questions# -----------------------------------------------------try:questions_data = fetch_questions()except Exception as e:traceback.print_exc()return (f"Error fetching questions:\n{type(e).__name__}: {e}",pd.DataFrame(),)# -----------------------------------------------------# Solve# -----------------------------------------------------results_log = []answers_payload = []success_count = 0error_count = 0total = len(questions_data)for index, item in enumerate(questions_data, start=1):task_id = item.get("task_id")question = item.get("question")if not task_id or question is None:print(f"Skipping malformed task: {item}")continueprint("\n" + "#" * 80)print(f"TASK {index}/{total}")print(f"TASK ID: {task_id}")print("#" * 80)try:answer = agent(question)success_count += 1answers_payload.append({"task_id": task_id,"submitted_answer": answer,})results_log.append({"Task ID": task_id,"Question": question,"Submitted Answer": answer,"Status": "OK",})except Exception as e:error_count += 1traceback.print_exc()error_message = (f"{type(e).__name__}: {str(e)}")print(f"\nERROR ON TASK {task_id}: "f"{error_message}")# IMPORTANT:# Do NOT send an empty answer to the scoring API.results_log.append({"Task ID": task_id,"Question": question,"Submitted Answer": "","Status": error_message,})results_df = pd.DataFrame(results_log)# -----------------------------------------------------# Prevent another useless 0/20 submission# -----------------------------------------------------if success_count == 0:return ("Evaluation stopped.\n\n"f"Successful answers: 0/{total}\n"f"Errors: {error_count}/{total}\n\n""Nothing was submitted because the model failed to ""produce any answers.\n\n""Open Logs and inspect the Status column below.",results_df,)print("\n" + "=" * 80)print("AGENT RUN COMPLETE")print(f"Successful answers: {success_count}")print(f"Errors: {error_count}")print("=" * 80)# -----------------------------------------------------# Submit only successfully generated answers# -----------------------------------------------------submission_data = {"username": username,"agent_code": agent_code,"answers": answers_payload,}submit_url = f"{DEFAULT_API_URL}/submit"print(f"Submitting {len(answers_payload)} answers "f"to {submit_url}")try:response = requests.post(submit_url,3 unmodified linesresponse.raise_for_status()result = response.json()score = result.get("score", "N/A")correct = result.get("correct_count", "?")attempted = result.get("total_attempted", "?")message = result.get("message","No message received.",)status = ("Submission Successful!\n\n"f"User: {result.get('username', username)}\n"f"Generated answers: {success_count}/{total}\n"f"Agent errors: {error_count}/{total}\n"f"Score: {score}%\n"f"Correct: {correct}/{attempted}\n\n"f"{message}")print(status)return status, results_dfexcept requests.exceptions.HTTPError as e:traceback.print_exc()try:detail = e.response.json()except Exception:detail = e.response.text[:1000]return ("Submission failed.\n\n"f"HTTP {e.response.status_code}\n"f"{detail}",results_df,)except Exception as e:traceback.print_exc()return ("Submission failed.\n\n"f"{type(e).__name__}: {e}",results_df,)# =========================================================# UI# =========================================================with gr.Blocks() as demo:gr.Markdown("""# GAIA Agent Evaluation Runner### Instructions1. Log in with your Hugging Face account.2. Click **Run Evaluation & Submit All Answers**.3. The agent will fetch the course questions.4. It will research and solve them.5. Successful answers will be submitted to the course scoring API.6. Errors will be displayed in the table instead of silentlysubmitting blank answers.Evaluation may take several minutes.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers",variant="primary",)status_output = gr.Textbox(label="Run Status / Submission Result",lines=10,interactive=False,)11 unmodified lines)# =========================================================# START# =========================================================if __name__ == "__main__":print("\n" + "=" * 80)print("STARTING GAIA AGENT SPACE")print(f"SPACE_ID: {os.getenv('SPACE_ID', 'NOT FOUND')}")print(f"SPACE_HOST: {os.getenv('SPACE_HOST', 'NOT FOUND')}")print(f"HF_TOKEN configured: {bool(os.getenv('HF_TOKEN'))}")print(f"MODEL: {MODEL_ID}")print("=" * 80 + "\n")demo.launch(
app.py+269-288