Frazer2810's picture
Update app.py
fc6592e verified
raw
history blame
3.97 kB
""" Basic Agent Evaluation Runner – invia sempre tutte le risposte """
import os
import requests
import gradio as gr
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"
# --- Agent wrapper -------------------------------------------------------- #
class BasicAgent:
"""LangGraph agent ready for evaluation."""
def __init__(self):
print("BasicAgent initialized (provider=groq).")
self.graph = build_graph(provider="groq")
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
# rimuove la parte "FINAL ANSWER: "
return answer[14:]
# --- Main evaluation logic ------------------------------------------------ #
def run_and_submit_all(profile: gr.OAuthProfile | None):
# 0. Check login
if not profile:
return "Please Login to Hugging Face with the button.", None
username = profile.username
print(f"User logged in: {username}")
# 1. Instantiate agent
try:
agent = BasicAgent()
except Exception as e:
return f"Error initializing agent: {e}", None
# 2. Fetch questions
try:
resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
resp.raise_for_status()
questions_data = resp.json()
if not questions_data:
return "Fetched questions list is empty.", None
except Exception as e:
return f"Error fetching questions: {e}", None
# 3. Run agent and build payload
answers_payload = []
results_log = []
for item in questions_data:
task_id = item.get("task_id")
q_text = item.get("question")
submitted_answer = "errore" # default in caso di failure
try:
submitted_answer = agent(q_text)
except Exception as e:
print(f"Error running agent on task {task_id}: {e}")
# in ogni caso inseriamo la risposta (successo o errore)
answers_payload.append(
{"task_id": task_id, "submitted_answer": submitted_answer}
)
results_log.append(
{
"Task ID": task_id,
"Question": q_text,
"Submitted Answer": submitted_answer,
}
)
# 4. Submit answers
submission = {
"username": username,
"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID', '')}/tree/main",
"answers": answers_payload,
}
try:
resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
resp.raise_for_status()
data = resp.json()
status_msg = (
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_msg = f"Submission Failed: {e}"
return status_msg, pd.DataFrame(results_log)
# --- Gradio UI ------------------------------------------------------------ #
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner (retry & error-safe)")
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)