Irfshaikh's picture
Update app.py
404278e verified
import os
import requests
import pandas as pd
import gradio as gr
from langchain_core.messages import HumanMessage
from agent import build_graph
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
class BasicAgent:
def __init__(self):
self.graph = build_graph()
def __call__(self, question: str) -> str:
result = self.graph.invoke({"messages": [HumanMessage(content=question)]})
return result['messages'][-1].content
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
agent_code = f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main"
session = requests.Session()
try:
agent = BasicAgent()
except Exception as e:
return f"Error initializing agent: {e}", None
try:
response = session.get(f"{DEFAULT_API_URL}/questions", timeout=15)
response.raise_for_status()
questions = response.json()
if not questions:
return "No questions received from server.", None
except Exception as e:
return f"Error fetching questions: {e}", None
results_log = []
answers_payload = []
for item in questions:
task_id = item.get("task_id")
q = item.get("question")
if not (task_id and q):
continue
try:
answer = agent(q)
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
except Exception as e:
answer = f"AGENT ERROR: {e}"
results_log.append({"Task ID": task_id, "Question": q, "Submitted Answer": answer})
if not answers_payload:
return "Agent did not produce valid answers.", pd.DataFrame(results_log)
try:
res = session.post(
f"{DEFAULT_API_URL}/submit",
json={
"username": username.strip(),
"agent_code": agent_code,
"answers": answers_payload
},
timeout=60
)
res.raise_for_status()
r = res.json()
status = (
f"Submission Successful!\nUser: {r.get('username')}\n"
f"Score: {r.get('score', 'N/A')}% "
f"({r.get('correct_count', '?')}/{r.get('total_attempted', '?')})\n"
f"Message: {r.get('message', 'No message received.')}"
)
return status, pd.DataFrame(results_log)
except requests.exceptions.RequestException as e:
return f"Submission Failed: {e}", pd.DataFrame(results_log)