Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768691 unmodified line71727374757677783 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified line1171181191201211221231241251261271281291301311321331341351361371381391401411423 unmodified linesimport pandas as pdfrom dotenv import load_dotenvimport tracebackfrom typing import Optional # Make sure this import is present# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Agent Integration ---# 1. IMPORT your main agent functiontry:# Ensure this matches the filename and function name exactlyfrom final_agent import answer_gaia_taskprint("Successfully imported answer_gaia_task from final_agent.py")AGENT_AVAILABLE = Trueexcept ImportError as e:print(f"ERROR: Could not import answer_gaia_task from final_agent.py: {e}")print("Ensure final_agent.py exists and has no syntax errors.")AGENT_AVAILABLE = Falseexcept Exception as e:print(f"ERROR during import or initial setup in final_agent.py: {e}")traceback.print_exc()AGENT_AVAILABLE = False# Define a dummy function if import fails, so Gradio app can still loadif not AGENT_AVAILABLE:def answer_gaia_task(question: str, file_path: Optional[str] = None) -> str:return "ERROR: Agent function could not be loaded. Check Space logs."# 2. Define a Runner Class to use the imported functionclass AgentRunner:def __init__(self):print("AgentRunner initialized.")if not AGENT_AVAILABLE:print("WARNING: Agent function failed to load during startup.")# Optional: Add environment variable checks if needed# if not os.getenv("GROQ_API_KEY") or not os.getenv("TAVILY_API_KEY"):# print("WARNING: Required API keys might not be set in Space secrets.")def __call__(self, question: str) -> str:"""Runs the imported agent function on a single question."""print(f"AgentRunner received question (first 50 chars): {question[:50]}...")if not AGENT_AVAILABLE:return "ERROR: Agent function could not be loaded."try:# Call the imported functionfinal_answer = answer_gaia_task(question=question, file_path=None)# Ensure result is always a stringfinal_answer_str = str(final_answer)print(f"Agent function returned answer: {final_answer_str}")return final_answer_strexcept Exception as e:print(f"ERROR calling answer_gaia_task: {e}")traceback.print_exc()return f"ERROR: Agent failed during execution - {e}"# --- Submission Logic (Mostly unchanged) ---def run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches questions, runs agent, submits answers."""space_id = os.getenv("SPACE_ID")if not profile:print("User not logged in."); return "Please Login to Hugging Face.", Noneusername= f"{profile.username}"; print(f"User logged in: {username}")api_url = DEFAULT_API_URL; questions_url = f"{api_url}/questions"; submit_url = f"{api_url}/submit"1 unmodified line# 1. Instantiate Agent Runnertry:agent = AgentRunner()except Exception as e:print(f"Error instantiating AgentRunner: {e}"); return f"Error initializing agent runner: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code URL N/A"print(f"Agent code reference: {agent_code}")3 unmodified linestry:response = requests.get(questions_url, timeout=30); response.raise_for_status()questions_data = response.json()if not questions_data: print("Fetched questions list is empty."); return "Questions list empty.", Noneprint(f"Fetched {len(questions_data)} questions.")except Exception as e: print(f"Error fetching questions: {e}"); return f"Error fetching questions: {e}", None# 3. Run Agent on each questionresults_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: {item}"); continuetry:submitted_answer = agent(question_text) # Calls AgentRunner.__call__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}"); traceback.print_exc()results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT RUN ERROR: {e}"})answers_payload.append({"task_id": task_id, "submitted_answer": f"AGENT RUN ERROR: {e}"})if not answers_payload: print("Agent produced no answers."); return "Agent produced no answers.", pd.DataFrame(results_log)# 4. Prepare Submissionsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}print(f"Submitting {len(answers_payload)} answers for user '{username}'...")# 5. Submittry:response = requests.post(submit_url, json=submission_data, timeout=60); response.raise_for_status()result_data = response.json()final_status = (f"Submission Successful!\nUser: {result_data.get('username')}\n"f"Overall Score: {result_data.get('score', 'N/A')}% "1 unmodified linef"Message: {result_data.get('message', 'N/A')}")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[:200]}"status_message = f"Submission Failed: {error_detail}"except Exception as e: status_message = f"Submission Failed: Unexpected error - {e}"print(status_message); traceback.print_exc(); results_df = pd.DataFrame(results_log); return status_message, results_df# --- Build Gradio Interface (Unchanged) ---with gr.Blocks() as demo:gr.Markdown("# GAIA Agent Evaluation Runner"); gr.Markdown("...") # Keep markdown contentgr.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])# --- Main execution block (Unchanged) ---if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# ... Keep startup checks ...print("Launching Gradio Interface for GAIA Agent Evaluation...")demo.launch(debug=True, share=False) # debug=True helps during development3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172731 unmodified line757677787980818283843 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241 unmodified line1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621633 unmodified linesimport pandas as pdfrom dotenv import load_dotenvimport tracebackfrom typing import Optional # <<< MAKE SURE THIS IMPORT IS PRESENT <<<# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Agent Integration ---AGENT_AVAILABLE = FalseAGENT_LOAD_ERROR = ""try:# Ensure this matches the filename and function name exactlyfrom final_agent import answer_gaia_taskprint("Successfully imported answer_gaia_task from final_agent.py")AGENT_AVAILABLE = Trueexcept ImportError as e:error_msg = f"ERROR: Could not import answer_gaia_task from final_agent.py: {e}"print(error_msg)AGENT_LOAD_ERROR = error_msgexcept Exception as e:# Catch errors during the global setup within final_agent.pyerror_msg = f"ERROR during import or initial setup in final_agent.py: {e}"print(error_msg)traceback.print_exc()AGENT_LOAD_ERROR = error_msg# Define a dummy function if import fails, so Gradio app can still loadif not AGENT_AVAILABLE:# This dummy function will be used if the import failsdef answer_gaia_task(question: str, file_path: Optional[str] = None) -> str:return f"ERROR: Agent function could not be loaded. Details: {AGENT_LOAD_ERROR}"# --- Agent Runner Class ---class AgentRunner:def __init__(self):print("AgentRunner initialized.")if not AGENT_AVAILABLE:print(f"WARNING: Agent function failed to load during startup. Error: {AGENT_LOAD_ERROR}")# Optional: Add environment variable checks if needed# if not os.getenv("GROQ_API_KEY") or not os.getenv("TAVILY_API_KEY"):# print("WARNING: Required API keys might not be set in Space secrets.")def __call__(self, question: str) -> str:"""Runs the imported agent function on a single question."""print(f"\n--- AgentRunner received question: {question[:100]}... ---")# Always call the potentially dummy function; it returns error if neededtry:# Call the imported (or dummy) function# Assuming file_path is handled by the agent based on question text for nowfinal_answer = answer_gaia_task(question=question, file_path=None)# Ensure result is always a string for submissionfinal_answer_str = str(final_answer)print(f"--- AgentRunner returning answer: {final_answer_str} ---")return final_answer_strexcept Exception as e:# Catch unexpected errors during the function call itselfprint(f"!!! ERROR calling answer_gaia_task function: {e} !!!")traceback.print_exc() # Log the full error to Space logsreturn f"ERROR: Agent function failed during execution - {e}"# --- Submission Logic ---def run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches questions, runs agent, submits answers."""space_id = os.getenv("SPACE_ID")if not profile: print("User not logged in."); return "Please Login.", Noneusername= f"{profile.username}"; print(f"User logged in: {username}")api_url = DEFAULT_API_URL; questions_url = f"{api_url}/questions"; submit_url = f"{api_url}/submit"1 unmodified line# 1. Instantiate Agent Runnertry:agent = AgentRunner()# Check if agent loaded correctly before proceedingif not AGENT_AVAILABLE:return f"Agent failed to load. Check logs. Error: {AGENT_LOAD_ERROR}", Noneexcept Exception as e: print(f"Error instantiating AgentRunner: {e}"); return f"Init error: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code URL N/A"print(f"Agent code reference: {agent_code}")3 unmodified linestry:response = requests.get(questions_url, timeout=30); response.raise_for_status()questions_data = response.json()if not questions_data: print("Questions list empty."); return "Questions list empty.", Noneprint(f"Fetched {len(questions_data)} questions.")except Exception as e: print(f"Error fetching questions: {e}"); return f"Fetch error: {e}", None# 3. Run Agent on each questionresults_log = []; answers_payload = []print(f"Running agent on {len(questions_data)} questions...")question_count = len(questions_data)for i, item in enumerate(questions_data):task_id = item.get("task_id"); question_text = item.get("question")print(f"\n--- Processing Question {i+1}/{question_count} (ID: {task_id}) ---") # Add progress loggingif not task_id or question_text is None: print(f"Skipping item: {item}"); continuetry:submitted_answer = agent(question_text) # Calls AgentRunner.__call__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:# Catch errors during the agent's execution on a specific taskprint(f"!! Error running agent on task {task_id}: {e} !!"); traceback.print_exc()results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT RUN ERROR: {e}"})answers_payload.append({"task_id": task_id, "submitted_answer": f"AGENT RUN ERROR: {e}"}) # Submit errorif not answers_payload: print("Agent produced no answers."); return "Agent produced no answers.", pd.DataFrame(results_log)# 4. Prepare Submissionsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}print(f"\nSubmitting {len(answers_payload)} answers for user '{username}'...")# 5. Submittry:response = requests.post(submit_url, json=submission_data, timeout=120); response.raise_for_status() # Increased timeoutresult_data = response.json()final_status = (f"Submission Successful!\nUser: {result_data.get('username')}\n"f"Overall Score: {result_data.get('score', 'N/A')}% "1 unmodified linef"Message: {result_data.get('message', 'N/A')}")print("Submission successful."); results_df = pd.DataFrame(results_log); return final_status, results_dfexcept requests.exceptions.HTTPError as e:error_detail = f"Server error {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[:200]}"status_message = f"Submission Failed: {error_detail}"except requests.exceptions.Timeout:status_message = "Submission Failed: The request timed out (120 seconds)."except Exception as e: status_message = f"Submission Failed: Unexpected error - {e}"; traceback.print_exc()print(status_message); results_df = pd.DataFrame(results_log); return status_message, results_df# --- Build Gradio Interface ---with gr.Blocks() as demo:gr.Markdown("# GAIA Agent Evaluation Runner")gr.Markdown("""**Instructions:**1. Ensure your agent logic is in `final_agent.py` and dependencies in `requirements.txt`. Set secrets in Space settings.2. Log in to Hugging Face using the button below.3. Click 'Run Evaluation & Submit All Answers' to run your agent. Check Logs for detailed progress.---**Disclaimers:** Execution can take significant time.""")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])# --- Main execution block ---if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# ... Keep startup checks ...print("Launching Gradio Interface...")demo.launch(debug=True, share=False) # debug=True helps during development
app.py+59-38