Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines4567789101112131314151617181920202122212223242425262728262930313233343135363337383940413842434445464748454647495051495253545155565357585956575860616263646065666768696566707172731 unmodified line7576777475787980818283843 unmodified lines8889908591928793949596979298991001011021031041051061071001081091101021111121131141151161081171181191201121211221231241 unmodified line1261271281201291301311321331341241251351361371381281391401301411421431441451461471481491501511521531541551561571371581591601611411621633 unmodified linesimport pandas as pdfrom dotenv import load_dotenvimport tracebackfrom typing import Optional # Make sure this import is presentfrom 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 functionAGENT_AVAILABLE = FalseAGENT_LOAD_ERROR = ""try: # Ensure this matches the filename and function name exactly from final_agent import answer_gaia_task print("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 = False 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: print(f"ERROR during import or initial setup in final_agent.py: {e}") # Catch errors during the global setup within final_agent.py error_msg = f"ERROR during import or initial setup in final_agent.py: {e}" print(error_msg) traceback.print_exc() AGENT_AVAILABLE = False 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 fails def answer_gaia_task(question: str, file_path: Optional[str] = None) -> str: return "ERROR: Agent function could not be loaded. Check Space logs." return f"ERROR: Agent function could not be loaded. Details: {AGENT_LOAD_ERROR}"
# 2. Define a Runner Class to use the imported function# --- Agent Runner Class ---class AgentRunner: def __init__(self): print("AgentRunner initialized.") if not AGENT_AVAILABLE: print("WARNING: Agent function failed to load during startup.") 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"AgentRunner received question (first 50 chars): {question[:50]}...") if not AGENT_AVAILABLE: return "ERROR: Agent function could not be loaded." print(f"\n--- AgentRunner received question: {question[:100]}... ---") # Always call the potentially dummy function; it returns error if needed try: # Call the imported function # Call the imported (or dummy) function # Assuming file_path is handled by the agent based on question text for now final_answer = answer_gaia_task(question=question, file_path=None) # Ensure result is always a string # Ensure result is always a string for submission final_answer_str = str(final_answer) print(f"Agent function returned answer: {final_answer_str}") print(f"--- AgentRunner returning answer: {final_answer_str} ---") return final_answer_str except Exception as e: print(f"ERROR calling answer_gaia_task: {e}") traceback.print_exc() return f"ERROR: Agent failed during execution - {e}" # Catch unexpected errors during the function call itself print(f"!!! ERROR calling answer_gaia_task function: {e} !!!") traceback.print_exc() # Log the full error to Space logs return f"ERROR: Agent function failed during execution - {e}"
# --- Submission Logic (Mostly unchanged) ---# --- 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 to Hugging Face.", None if not profile: print("User not logged in."); return "Please Login.", None username= 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 Runner try: agent = AgentRunner() except Exception as e: print(f"Error instantiating AgentRunner: {e}"); return f"Error initializing agent runner: {e}", None # Check if agent loaded correctly before proceeding if not AGENT_AVAILABLE: return f"Agent failed to load. Check logs. Error: {AGENT_LOAD_ERROR}", None except Exception as e: print(f"Error instantiating AgentRunner: {e}"); return f"Init error: {e}", None
agent_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 lines try: 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.", None if not questions_data: print("Questions list empty."); return "Questions list empty.", None print(f"Fetched {len(questions_data)} questions.") except Exception as e: print(f"Error fetching questions: {e}"); return f"Error fetching questions: {e}", None except Exception as e: print(f"Error fetching questions: {e}"); return f"Fetch error: {e}", None
# 3. Run Agent on each question results_log = []; answers_payload = [] print(f"Running agent on {len(questions_data)} questions...") for item in questions_data: 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 logging if not task_id or question_text is None: print(f"Skipping item: {item}"); continue try: 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() # Catch errors during the agent's execution on a specific task 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}"}) answers_payload.append({"task_id": task_id, "submitted_answer": f"AGENT RUN ERROR: {e}"}) # Submit error
if not answers_payload: print("Agent produced no answers."); return "Agent produced no answers.", pd.DataFrame(results_log)
# 4. Prepare Submission submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} print(f"Submitting {len(answers_payload)} answers for user '{username}'...") print(f"\nSubmitting {len(answers_payload)} answers for user '{username}'...")
# 5. Submit try: response = requests.post(submit_url, json=submission_data, timeout=60); response.raise_for_status() response = requests.post(submit_url, json=submission_data, timeout=120); response.raise_for_status() # Increased timeout 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 line f"Message: {result_data.get('message', 'N/A')}") 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}." 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}" print(status_message); traceback.print_exc(); results_df = pd.DataFrame(results_log); return status_message, results_df 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 (Unchanged) ---# --- Build Gradio Interface ---with gr.Blocks() as demo: gr.Markdown("# GAIA Agent Evaluation Runner"); gr.Markdown("...") # Keep markdown content 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 (Unchanged) ---# --- Main execution block ---if __name__ == "__main__": print("\n" + "-"*30 + " App Starting " + "-"*30) # ... Keep startup checks ... print("Launching Gradio Interface for GAIA Agent Evaluation...") print("Launching Gradio Interface...") demo.launch(debug=True, share=False) # debug=True helps during developmentapp.py+59-38