| """Basic Agent Evaluation Runner – GPT-4.1 edition (HF Spaces)""" |
| import os |
| import requests |
| import gradio as gr |
| import pandas as pd |
| from langchain_core.messages import HumanMessage |
| from agent import build_graph |
|
|
| |
| DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" |
|
|
| |
| class BasicAgent: |
| """LangGraph agent ready for evaluation.""" |
| def __init__(self): |
| print("BasicAgent initialized (using GPT-4.1).") |
| |
| self.graph = build_graph(provider="openai") |
|
|
| def __call__(self, question: str) -> str: |
| print(f"Agent received question (first 50 chars): {question[:50]}...") |
| msgs = [HumanMessage(content=question)] |
| result = self.graph.invoke({"messages": msgs}) |
| answer = result["messages"][-1].content |
| return answer[14:] |
|
|
|
|
| |
| def run_and_submit_all(profile: gr.OAuthProfile | None): |
| |
| if not profile: |
| return "Please Login to Hugging Face with the button.", None |
| username = profile.username |
| print(f"User logged in: {username}") |
|
|
| |
| try: |
| agent = BasicAgent() |
| except Exception as e: |
| return f"Error initializing agent: {e}", None |
|
|
| |
| space_id = os.getenv("SPACE_ID", "unknown-space") |
| agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" |
|
|
| |
| try: |
| resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15) |
| resp.raise_for_status() |
| questions_data = resp.json() |
| except Exception as e: |
| return f"Error fetching questions: {e}", None |
|
|
| |
| results_log = [] |
| answers_payload = [] |
| for item in questions_data: |
| task_id = item.get("task_id") |
| q_text = item.get("question") |
| try: |
| ans = agent(q_text) |
| answers_payload.append({"task_id": task_id, "submitted_answer": ans}) |
| results_log.append({"Task ID": task_id, "Question": q_text, "Submitted Answer": ans}) |
| except Exception as e: |
| results_log.append({"Task ID": task_id, "Question": q_text, "Submitted Answer": f"AGENT ERROR: {e}"}) |
|
|
| |
| submission = {"username": username, "agent_code": agent_code, "answers": answers_payload} |
| try: |
| resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60) |
| resp.raise_for_status() |
| data = resp.json() |
| status = ( |
| f"Submission Successful!\nUser: {data.get('username')}\n" |
| f"Overall Score: {data.get('score', 'N/A')}% " |
| f"({data.get('correct_count', '?')}/{data.get('total_attempted', '?')} correct)\n" |
| f"Message: {data.get('message', 'No message received.')}" |
| ) |
| except Exception as e: |
| status = f"Submission Failed: {e}" |
|
|
| return status, pd.DataFrame(results_log) |
|
|
| |
| with gr.Blocks() as demo: |
| gr.Markdown("# Basic Agent Evaluation Runner (GPT-4.1)") |
| gr.LoginButton() |
| run_btn = gr.Button("Run Evaluation & Submit All Answers") |
| status_box = gr.Textbox(lines=5, label="Run Status / Submission Result") |
| results_tbl = gr.DataFrame(label="Questions and Agent Answers", wrap=True) |
| run_btn.click(fn=run_and_submit_all, outputs=[status_box, results_tbl]) |
|
|
| if __name__ == "__main__": |
| demo.launch(debug=True, share=False) |
|
|