Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288import osimport reimport jsonimport mathimport spacesimport requestsimport pandas as pdimport gradio as grfrom io import BytesIOfrom smolagents import CodeAgent, OpenAIModel, DuckDuckGoSearchToolDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):groq_key = os.environ.get("GROQ_API_KEY")if not groq_key:raise ValueError("GROQ_API_KEY missing")# Verify the API key and model BEFORE running GAIAcheck = requests.get("https://api.groq.com/openai/v1/models",headers={"Authorization": f"Bearer {groq_key}"},timeout=20)check.raise_for_status()available = [m["id"] for m in check.json()["data"]]model_id = "openai/gpt-oss-20b"if model_id not in available:raise ValueError(f"Model unavailable. Available models: {available}")model = OpenAIModel(model_id=model_id,api_base="https://api.groq.com/openai/v1",api_key=groq_key,max_tokens=2048)self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()],model=model,max_steps=8,verbosity_level=0,additional_authorized_imports=["requests", "bs4", "json", "re", "math","statistics", "datetime", "collections"])print("GROQ INITIALIZED AND MODEL VERIFIED")def __call__(self, question: str) -> str:prompt = f"""You are an advanced autonomous research agentsolving GAIA benchmark questions.Your task:{question}Instructions:1. Understand the question carefully.2. Identify what information is needed.3. Use web search when factual research is needed.4. Prefer reliable and authoritative sources.5. Cross-check important facts.6. Use Python for calculations when necessary.7. Pay attention to dates, units, names and exact wording.8. If the question contains reversed text, decode it.9. If the question requires research, do not guess.10. Return ONLY the final answer.GAIA ANSWER RULES:- No explanations.- No citations.- No markdown.- No introductory text.- No "FINAL ANSWER" prefix.- Be concise and precise."""try:result = self.agent.run(prompt)answer = str(result).strip()answer = re.sub(r"^(final answer|answer)\s*:\s*","",answer,flags=re.IGNORECASE)return answer.strip()except Exception as e:import tracebackprint("AGENT EXECUTION ERROR:")traceback.print_exc()return f"AGENT ERROR: {type(e).__name__}: {str(e)}"@spaces.GPU(duration=60)def run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif 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"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)# 2. Fetch Questionsprint(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.", Noneprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")print(f"Response text: {response.text[:500]}")return f"Error decoding server response for questions: {e}", Noneexcept Exception as e:print(f"An unexpected error occurred fetching questions: {e}")return f"An unexpected error occurred fetching questions: {e}", None# 3. Run your Agentresults_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}")continuetry: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. Prepare Submissionsubmission_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. Submitprint(f"Submitting {len(answers_payload)} 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.')}")print("Submission successful.")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept 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)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.Timeout:status_message = "Submission Failed: The request timed out."print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.RequestException as e:status_message = f"Submission Failed: Network error - {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept Exception as e:status_message = f"An unexpected error occurred during submission: {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_df# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:gr.Markdown("# Basic Agent Evaluation Runner")gr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**Disclaimers:**Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)# Removed max_rows=10 from DataFrame constructorresults_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)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")print(f" Runtime URL should be: https://{space_host_startup}.hf.space")else:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")print("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419import osimport reimport tracebackimport requestsimport pandas as pdimport gradio as grfrom smolagents import CodeAgent, OpenAIModel, DuckDuckGoSearchTool# =========================================================# CONFIGURATION# =========================================================GROQ_API_URL = "https://api.groq.com/openai/v1"GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"MODEL_ID = "openai/gpt-oss-20b"REQUEST_TIMEOUT = 60# =========================================================# AGENT# =========================================================class BasicAgent:def __init__(self):api_key = os.environ.get("GROQ_API_KEY")if not api_key:raise RuntimeError("GROQ_API_KEY is missing. Add it in Space Secrets.")self.api_key = api_key# 1. Verify that the model exists on Groqprint("Checking Groq API and model...")response = requests.get(f"{GROQ_API_URL}/models",headers={"Authorization": f"Bearer {api_key}"},timeout=REQUEST_TIMEOUT)response.raise_for_status()available_models = [item["id"] for item in response.json().get("data", [])]if MODEL_ID not in available_models:raise RuntimeError(f"{MODEL_ID} is not available. "f"Check the Groq model catalog.")# 2. Test an actual model responseprint("Testing Groq chat completion...")test_response = requests.post(f"{GROQ_API_URL}/chat/completions",headers={"Authorization": f"Bearer {api_key}","Content-Type": "application/json"},json={"model": MODEL_ID,"messages": [{"role": "user","content": "Reply with exactly: OK"}],"max_completion_tokens": 20},timeout=REQUEST_TIMEOUT)test_response.raise_for_status()test_answer = (test_response.json()["choices"][0]["message"]["content"])if not test_answer:raise RuntimeError("Groq returned an empty test response.")print(f"Groq test successful: {test_answer}")# 3. Initialize the modelmodel = OpenAIModel(model_id=MODEL_ID,api_base=GROQ_API_URL,api_key=api_key,max_tokens=2048,client_kwargs={"timeout": 120, "max_retries": 2})# 4. Initialize the research agentself.agent = CodeAgent(tools=[DuckDuckGoSearchTool()],model=model,max_steps=8,verbosity_level=1,additional_authorized_imports=["requests","bs4","json","re","math","statistics","datetime","collections","urllib","csv","xml"])print("GROQ AGENT INITIALIZED SUCCESSFULLY")def __call__(self, question: str) -> str:prompt = f"""You are an autonomous research agent solving a GAIA benchmark question.QUESTION:{question}INSTRUCTIONS:1. Understand exactly what the question asks.2. Identify the information required to answer it.3. Use web search when external information is needed.4. Prefer reliable and authoritative sources.5. Cross-check important facts when possible.6. Use Python calculations when necessary.7. Respect dates, units, names, spelling and exact wording.8. Decode reversed text or unusual formatting when necessary.9. Never invent facts or pretend to have accessed unavailable information.10. Follow the question's requested answer format exactly.FINAL RESPONSE:Return only the answer.Do not add explanations, citations, markdown or introductory text.Be concise and precise."""result = self.agent.run(prompt)answer = str(result).strip()answer = re.sub(r"^(final answer|answer)\s*:\s*","",answer,flags=re.IGNORECASE)if not answer:raise RuntimeError("Agent returned an empty answer.")if answer.upper().startswith("AGENT ERROR"):raise RuntimeError(answer)return answer# =========================================================# GAIA EVALUATION# =========================================================def run_and_submit_all(profile, progress=gr.Progress()):if profile is None:return ("Please log in to Hugging Face first.",pd.DataFrame())username = profile.usernamespace_id = os.getenv("SPACE_ID","mohamedazelmad/Final_Assignment_Template")agent_code = (f"https://huggingface.co/spaces/{space_id}/tree/main")questions_url = f"{GAIA_API_URL}/questions"submit_url = f"{GAIA_API_URL}/submit"print(f"Logged in as: {username}")print("Initializing agent...")# 1. Initialize and test agent BEFORE fetching questionstry:agent = BasicAgent()except Exception as error:traceback.print_exc()return (f"MODEL INITIALIZATION FAILED:\n"f"{type(error).__name__}: {error}\n\n"f"No answers were submitted.",pd.DataFrame())# 2. Fetch GAIA questionsprint("Fetching GAIA questions...")try:response = requests.get(questions_url,timeout=REQUEST_TIMEOUT)response.raise_for_status()questions = response.json()if not isinstance(questions, list) or not questions:raise RuntimeError("GAIA returned an empty or invalid question list.")except Exception as error:traceback.print_exc()return (f"QUESTION FETCH FAILED:\n{type(error).__name__}: {error}",pd.DataFrame())print(f"Fetched {len(questions)} questions.")# 3. Solve all questionsanswers_payload = []results_log = []failed_tasks = []for index, item in enumerate(questions):task_id = item.get("task_id")question = item.get("question")if not task_id or not question:failed_tasks.append(f"Question {index + 1}: invalid data")continueprint(f"\nSolving question {index + 1}/{len(questions)}")print(f"Task ID: {task_id}")progress((index + 1) / len(questions),desc=f"Solving question {index + 1}/{len(questions)}")try:answer = agent(question)answers_payload.append({"task_id": task_id,"submitted_answer": answer})results_log.append({"Task ID": task_id,"Question": question,"Submitted Answer": answer,"Status": "Answered"})print(f"Answer: {answer[:250]}")except Exception as error:traceback.print_exc()failed_tasks.append(f"{task_id}: {type(error).__name__}: {error}")results_log.append({"Task ID": task_id,"Question": question,"Submitted Answer": str(error),"Status": "FAILED"})# Do not submit an incomplete or error-filled evaluationbreakresults_df = pd.DataFrame(results_log)# 4. Stop if any question failedif failed_tasks or len(answers_payload) != len(questions):message = ("EVALUATION STOPPED — NO SUBMISSION WAS SENT.\n\n"f"Successfully answered: {len(answers_payload)}"f"/{len(questions)}\n"f"Failed tasks: {len(failed_tasks)}\n\n""Check the Space logs for the exact error. ""Fix it before running the evaluation again.")print(message)return message, results_df# 5. Submit only when all answers were generatedprint("All questions answered. Preparing submission...")submission_data = {"username": username,"agent_code": agent_code,"answers": answers_payload}try:progress(1.0, desc="Submitting answers to GAIA...")response = requests.post(submit_url,json=submission_data,timeout=120)response.raise_for_status()result = response.json()score = result.get("score", "N/A")correct = result.get("correct_count", "N/A")total = result.get("total_attempted", len(answers_payload))message = ("SUBMISSION SUCCESSFUL!\n\n"f"Username: {result.get('username', username)}\n"f"Score: {score}%\n"f"Correct answers: {correct}/{total}\n"f"Message: {result.get('message', 'Evaluation completed.')}")print(message)for row in results_log:row["Status"] = "Submitted"return message, pd.DataFrame(results_log)except Exception as error:traceback.print_exc()return (f"SUBMISSION FAILED:\n"f"{type(error).__name__}: {error}\n\n""The answers were generated, but submission was not confirmed.",results_df)# =========================================================# GRADIO INTERFACE# =========================================================with gr.Blocks(title="GAIA Agent Evaluation") as demo:gr.Markdown("""# GAIA Final Assignment — Research AgentThis agent uses Groq GPT-OSS 20B and DuckDuckGo search.**Before running:**- Log in with your Hugging Face account.- Ensure GROQ_API_KEY is configured in Space Secrets.- The model connection is tested before evaluation.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers",variant="primary")status_output = gr.Textbox(label="Evaluation Status",lines=8,interactive=False)results_table = gr.DataFrame(label="GAIA Questions and Answers",wrap=True)run_button.click(fn=run_and_submit_all,outputs=[status_output, results_table],concurrency_limit=1)if __name__ == "__main__":print("=" * 50)print("GAIA RESEARCH AGENT STARTING")print("=" * 50)print(f"Space ID: {os.getenv('SPACE_ID', 'Unknown')}")demo.queue().launch(server_name="0.0.0.0",server_port=7860)
app.py+355-224