CoolFace
Apppublic

bitcloud2/Final_Assignment_Template

sourceHugging Faceupdated 1y agoView on Hugging Face
1likes
app.py223 linesDownload Raw Back to root
1import os2import gradio as gr3import requests4import inspect5import pandas as pd6 7from my_agent import SmolAgent  # Import the new agentd8 9# (Keep Constants as is)10# --- Constants ---11DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"12 13 14# --- Basic Agent Definition ---15# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------16class BasicAgent:17    def __init__(self):18        print("BasicAgent initialized.")19 20    def __call__(self, question: str) -> str:21        print(f"Agent received question (first 50 chars): {question[:50]}...")22        fixed_answer = "This is a default answer."23        print(f"Agent returning fixed answer: {fixed_answer}")24        return fixed_answer25 26 27def run_and_submit_all(profile: gr.OAuthProfile | None):28    """29    Fetches all questions, runs the BasicAgent on them, submits all answers,30    and displays the results.31    """32    # --- Determine HF Space Runtime URL and Repo URL ---33    space_id = os.getenv("SPACE_ID")  # Get the SPACE_ID for sending link to the code34 35    if profile:36        username = f"{profile.username}"37        print(f"User logged in: {username}")38    else:39        print("User not logged in.")40        return "Please Login to Hugging Face with the button.", None41 42    api_url = DEFAULT_API_URL43    questions_url = f"{api_url}/questions"44    submit_url = f"{api_url}/submit"45 46    # 1. Instantiate Agent ( modify this part to create your agent)47    try:48        agent = SmolAgent()49    except Exception as e:50        print(f"Error instantiating agent: {e}")51        return f"Error initializing agent: {e}", None52    # 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)53    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"54    print(agent_code)55 56    # 2. Fetch Questions57    print(f"Fetching questions from: {questions_url}")58    try:59        response = requests.get(questions_url, timeout=15)60        response.raise_for_status()61        questions_data = response.json()62        if not questions_data:63            print("Fetched questions list is empty.")64            return "Fetched questions list is empty or invalid format.", None65        print(f"Fetched {len(questions_data)} questions.")66    except requests.exceptions.RequestException as e:67        print(f"Error fetching questions: {e}")68        return f"Error fetching questions: {e}", None69    except requests.exceptions.JSONDecodeError as e:70        print(f"Error decoding JSON response from questions endpoint: {e}")71        print(f"Response text: {response.text[:500]}")72        return f"Error decoding server response for questions: {e}", None73    except Exception as e:74        print(f"An unexpected error occurred fetching questions: {e}")75        return f"An unexpected error occurred fetching questions: {e}", None76 77    # 3. Run your Agent78    results_log = []79    answers_payload = []80    print(f"Running agent on {len(questions_data)} questions...")81    for item in questions_data:82        task_id = item.get("task_id")83        question_text = item.get("question")84        if not task_id or question_text is None:85            print(f"Skipping item with missing task_id or question: {item}")86            continue87        try:88            submitted_answer = agent(question_text)89            answers_payload.append(90                {"task_id": task_id, "submitted_answer": submitted_answer}91            )92            results_log.append(93                {94                    "Task ID": task_id,95                    "Question": question_text,96                    "Submitted Answer": submitted_answer,97                }98            )99        except Exception as e:100            print(f"Error running agent on task {task_id}: {e}")101            results_log.append(102                {103                    "Task ID": task_id,104                    "Question": question_text,105                    "Submitted Answer": f"AGENT ERROR: {e}",106                }107            )108 109    if not answers_payload:110        print("Agent did not produce any answers to submit.")111        return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)112 113    # 4. Prepare Submission114    submission_data = {115        "username": username.strip(),116        "agent_code": agent_code,117        "answers": answers_payload,118    }119    status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."120    print(status_update)121 122    # 5. Submit123    print(f"Submitting {len(answers_payload)} answers to: {submit_url}")124    try:125        response = requests.post(submit_url, json=submission_data, timeout=60)126        response.raise_for_status()127        result_data = response.json()128        final_status = (129            f"Submission Successful!\n"130            f"User: {result_data.get('username')}\n"131            f"Overall Score: {result_data.get('score', 'N/A')}% "132            f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"133            f"Message: {result_data.get('message', 'No message received.')}"134        )135        print("Submission successful.")136        results_df = pd.DataFrame(results_log)137        return final_status, results_df138    except requests.exceptions.HTTPError as e:139        error_detail = f"Server responded with status {e.response.status_code}."140        try:141            error_json = e.response.json()142            error_detail += f" Detail: {error_json.get('detail', e.response.text)}"143        except requests.exceptions.JSONDecodeError:144            error_detail += f" Response: {e.response.text[:500]}"145        status_message = f"Submission Failed: {error_detail}"146        print(status_message)147        results_df = pd.DataFrame(results_log)148        return status_message, results_df149    except requests.exceptions.Timeout:150        status_message = "Submission Failed: The request timed out."151        print(status_message)152        results_df = pd.DataFrame(results_log)153        return status_message, results_df154    except requests.exceptions.RequestException as e:155        status_message = f"Submission Failed: Network error - {e}"156        print(status_message)157        results_df = pd.DataFrame(results_log)158        return status_message, results_df159    except Exception as e:160        status_message = f"An unexpected error occurred during submission: {e}"161        print(status_message)162        results_df = pd.DataFrame(results_log)163        return status_message, results_df164 165 166# --- Build Gradio Interface using Blocks ---167with gr.Blocks() as demo:168    gr.Markdown("# Basic Agent Evaluation Runner")169    gr.Markdown(170        """171        **Instructions:**172 173        1.  Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...174        2.  Log in to your Hugging Face account using the button below. This uses your HF username for submission.175        3.  Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.176 177        ---178        **Disclaimers:**179        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).180        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.181        """182    )183 184    gr.LoginButton()185 186    run_button = gr.Button("Run Evaluation & Submit All Answers")187 188    status_output = gr.Textbox(189        label="Run Status / Submission Result", lines=5, interactive=False190    )191    # Removed max_rows=10 from DataFrame constructor192    results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)193 194    run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])195 196if __name__ == "__main__":197    print("\n" + "-" * 30 + " App Starting " + "-" * 30)198    # Check for SPACE_HOST and SPACE_ID at startup for information199    space_host_startup = os.getenv("SPACE_HOST")200    space_id_startup = os.getenv("SPACE_ID")  # Get SPACE_ID at startup201 202    if space_host_startup:203        print(f"✅ SPACE_HOST found: {space_host_startup}")204        print(f"   Runtime URL should be: https://{space_host_startup}.hf.space")205    else:206        print("ℹ️  SPACE_HOST environment variable not found (running locally?).")207 208    if space_id_startup:  # Print repo URLs if SPACE_ID is found209        print(f"✅ SPACE_ID found: {space_id_startup}")210        print(f"   Repo URL: https://huggingface.co/spaces/{space_id_startup}")211        print(212            f"   Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"213        )214    else:215        print(216            "ℹ️  SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."217        )218 219    print("-" * (60 + len(" App Starting ")) + "\n")220 221    print("Launching Gradio Interface for Basic Agent Evaluation...")222    demo.launch(debug=True, share=False)223