import os import requests import pandas as pd import se_agents as se from config import Config from agent import run_agent import asyncio from colorama import Fore, Style, init init() USERNAME = "kaladin4" async def run_and_submit_all(): """ Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results. """ # --- Determine HF Space Runtime URL and Repo URL --- questions_url = f"{Config.get_default_api_url()}/questions" submit_url = f"{Config.get_default_api_url()}/submit" # 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/Kaladin4/AgentCourseU4/tree/main" # 2. Fetch Questions 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 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}", 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. Run your Agent 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 = ( f"{Fore.GREEN}Task Id:{Style.RESET_ALL} {task_id}\n" f"{Fore.BLUE}Task:{Style.RESET_ALL} {item.get('question')}\n" f"{Fore.YELLOW}File:{Style.RESET_ALL} {item.get('file_name')}" ) print(question_text) if not task_id or question_text is None: print(f"Skipping item with missing task_id or question: {item}") continue try: submitted_answer = await run_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 Submission submission_data = { "username": USERNAME, "agent_code": agent_code, "answers": answers_payload, } status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{USERNAME}'..." print(status_update) # 5. Submit print(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_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) results_df = pd.DataFrame(results_log) return status_message, results_df except requests.exceptions.Timeout: status_message = "Submission Failed: The request timed out." print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except 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_df except 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 async def main(): print("\n" + "-" * 30 + " App Starting " + "-" * 30) # Check for SPACE_HOST and SPACE_ID at startup for information print("-" * (60 + len(" App Starting ")) + "\n") print("Starting agent evaluation process...") final_status, results_df = await run_and_submit_all() print("\n" + "=" * 50) print("FINAL STATUS:") print(final_status) print("=" * 50 + "\n") print("Results Summary:") print(results_df) if __name__ == "__main__": asyncio.run(main())