import os import gradio as gr import requests import pandas as pd # --- Constants --- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" # --- Import your custom agent graph from agent.py --- from agent import build_graph from langchain_core.messages import HumanMessage # --- Basic Agent Definition (wrapper around your graph) --- class BasicAgent: def __init__(self): print("Initializing BasicAgent with agent.py graph...") self.graph = build_graph() def __call__(self, question: str) -> str: print(f"Agent received question: {question[:50]}...") try: messages = [HumanMessage(content=question)] result = self.graph.invoke({"messages": messages}) answer = result["messages"][-1].content if answer.lower().startswith("final answer"): answer = answer.split(":", 1)[-1].strip() print(f"Agent returning: {answer}") return answer except Exception as e: print(f"Error inside agent: {e}") return f"AGENT ERROR: {e}" def run_and_submit_all(profile: gr.OAuthProfile | None): """ Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results. """ space_id = os.getenv("SPACE_ID") if 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.", None api_url = DEFAULT_API_URL questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit" # 1. Instantiate Agent try: agent = BasicAgent() except Exception as e: print(f"Error instantiating agent: {e}") return f"Error initializing agent: {e}", None agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "N/A" print(f"Agent code repo: {agent_code}") # 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: return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.") except Exception as e: return f"Error 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 = item.get("question") if not task_id or question_text is None: continue 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 }) if not answers_payload: return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) # 4. Prepare Submission submission_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. 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.')}" ) results_df = pd.DataFrame(results_log) return final_status, results_df except Exception as e: return f"Submission Failed: {e}", pd.DataFrame(results_log) # --- Build Gradio Interface using Blocks --- with gr.Blocks() as demo: gr.Markdown("# Basic Agent Evaluation Runner") gr.Markdown( """ **Instructions:** 1. Clone this space and implement your logic in `agent.py`. 2. Log in with your Hugging Face account. 3. Click **Run Evaluation & Submit All Answers**. --- ⚠️ The process may take a while (agent needs to answer all questions). """ ) 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] ) if __name__ == "__main__": print("\n--- App Starting ---") space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") if space_host_startup: print(f"✅ SPACE_HOST: {space_host_startup}") print(f" Runtime URL: https://{space_host_startup}.hf.space") else: print("ℹ️ SPACE_HOST not found (running locally?).") if space_id_startup: print(f"✅ SPACE_ID: {space_id_startup}") print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") else: print("ℹ️ SPACE_ID not found (running locally?).") print("--------------------\n") print("Launching Gradio Interface...") demo.launch(debug=True, share=False)