import os import gradio as gr import requests import pandas as pd from langchain_core.messages import HumanMessage from agent import build_graph # --- Constants --- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" class BasicAgent: """A langgraph agent.""" def __init__(self): print("BasicAgent initialized.") self.graph = build_graph() def __call__(self, question: str) -> str: print(f"Agent received question (first 50 chars): {question[:50]}...") messages = [HumanMessage(content=question)] result = self.graph.invoke({"messages": messages}) answer = result['messages'][-1].content return answer def run_and_submit_all(profile: gr.OAuthProfile | None): space_id = os.getenv("SPACE_ID") if not profile: return "Please Login to Hugging Face with the button.", None username = profile.username api_url = DEFAULT_API_URL questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit" try: agent = BasicAgent() except Exception as e: return f"Error initializing agent: {e}", None agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" try: resp_q = requests.get(questions_url, timeout=15) resp_q.raise_for_status() questions = resp_q.json() except Exception as e: return f"Error fetching questions: {e}", None results_log = [] answers = [] for item in questions: task_id = item.get("task_id") q = item.get("question") if not task_id or q is None: continue try: ans = agent(q) answers.append({"task_id": task_id, "submitted_answer": ans}) results_log.append({"Task ID": task_id, "Question": q, "Submitted Answer": ans}) except Exception as e: results_log.append({"Task ID": task_id, "Question": q, "Submitted Answer": f"ERROR: {e}"}) if not answers: return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) payload = {"username": username.strip(), "agent_code": agent_code, "answers": answers} try: resp_s = requests.post(submit_url, json=payload, timeout=60) resp_s.raise_for_status() data = resp_s.json() status = ( f"Submission Successful!\n" f"User: {data.get('username')}\n" f"Score: {data.get('score', 'N/A')}% " f"({data.get('correct_count', '?')}/{data.get('total_attempted', '?')})\n" f"{data.get('message', '')}" ) return status, pd.DataFrame(results_log) except Exception as e: return f"Submission Failed: {e}", pd.DataFrame(results_log) with gr.Blocks() as demo: gr.Markdown("# Basic Agent Evaluation Runner") gr.Markdown(""" 1. Clone this space and customize your agent logic. 2. Log in with the button below. 3. Click **Run Evaluation & Submit All Answers**. """) gr.LoginButton() run_btn = gr.Button("Run Evaluation & Submit All Answers") status_out = gr.Textbox(label="Run Status / Submission Result", lines=5) results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) run_btn.click(fn=run_and_submit_all, outputs=[status_out, results_table]) if __name__ == "__main__": demo.launch(debug=True, share=False)