Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,110 +1,114 @@
|
|
| 1 |
-
"""
|
| 2 |
-
|
| 3 |
-
import os
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
#
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Basic Agent Evaluation Runner – invia sempre tutte le risposte """
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from langchain_core.messages import HumanMessage
|
| 8 |
+
from agent import build_graph
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# --- Constants ------------------------------------------------------------ #
|
| 12 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# --- Agent wrapper -------------------------------------------------------- #
|
| 16 |
+
class BasicAgent:
|
| 17 |
+
"""LangGraph agent ready for evaluation."""
|
| 18 |
+
def __init__(self):
|
| 19 |
+
print("BasicAgent initialized (provider=groq).")
|
| 20 |
+
self.graph = build_graph(provider="groq")
|
| 21 |
+
|
| 22 |
+
def __call__(self, question: str) -> str:
|
| 23 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 24 |
+
msgs = [HumanMessage(content=question)]
|
| 25 |
+
result = self.graph.invoke({"messages": msgs})
|
| 26 |
+
answer = result["messages"][-1].content
|
| 27 |
+
# rimuove la parte "FINAL ANSWER: "
|
| 28 |
+
return answer[14:]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# --- Main evaluation logic ------------------------------------------------ #
|
| 32 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 33 |
+
# 0. Check login
|
| 34 |
+
if not profile:
|
| 35 |
+
return "Please Login to Hugging Face with the button.", None
|
| 36 |
+
username = profile.username
|
| 37 |
+
print(f"User logged in: {username}")
|
| 38 |
+
|
| 39 |
+
# 1. Instantiate agent
|
| 40 |
+
try:
|
| 41 |
+
agent = BasicAgent()
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"Error initializing agent: {e}", None
|
| 44 |
+
|
| 45 |
+
# 2. Fetch questions
|
| 46 |
+
try:
|
| 47 |
+
resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
|
| 48 |
+
resp.raise_for_status()
|
| 49 |
+
questions_data = resp.json()
|
| 50 |
+
if not questions_data:
|
| 51 |
+
return "Fetched questions list is empty.", None
|
| 52 |
+
except Exception as e:
|
| 53 |
+
return f"Error fetching questions: {e}", None
|
| 54 |
+
|
| 55 |
+
# 3. Run agent and build payload
|
| 56 |
+
answers_payload = []
|
| 57 |
+
results_log = []
|
| 58 |
+
|
| 59 |
+
for item in questions_data:
|
| 60 |
+
task_id = item.get("task_id")
|
| 61 |
+
q_text = item.get("question")
|
| 62 |
+
|
| 63 |
+
submitted_answer = "errore" # default in caso di failure
|
| 64 |
+
try:
|
| 65 |
+
submitted_answer = agent(q_text)
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 68 |
+
|
| 69 |
+
# in ogni caso inseriamo la risposta (successo o errore)
|
| 70 |
+
answers_payload.append(
|
| 71 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
| 72 |
+
)
|
| 73 |
+
results_log.append(
|
| 74 |
+
{
|
| 75 |
+
"Task ID": task_id,
|
| 76 |
+
"Question": q_text,
|
| 77 |
+
"Submitted Answer": submitted_answer,
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# 4. Submit answers
|
| 82 |
+
submission = {
|
| 83 |
+
"username": username,
|
| 84 |
+
"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID', '')}/tree/main",
|
| 85 |
+
"answers": answers_payload,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
|
| 90 |
+
resp.raise_for_status()
|
| 91 |
+
data = resp.json()
|
| 92 |
+
status_msg = (
|
| 93 |
+
f"Submission Successful!\nUser: {data.get('username')}\n"
|
| 94 |
+
f"Overall Score: {data.get('score', 'N/A')}% "
|
| 95 |
+
f"({data.get('correct_count', '?')}/{data.get('total_attempted', '?')} correct)\n"
|
| 96 |
+
f"Message: {data.get('message', 'No message received.')}"
|
| 97 |
+
)
|
| 98 |
+
except Exception as e:
|
| 99 |
+
status_msg = f"Submission Failed: {e}"
|
| 100 |
+
|
| 101 |
+
return status_msg, pd.DataFrame(results_log)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# --- Gradio UI ------------------------------------------------------------ #
|
| 105 |
+
with gr.Blocks() as demo:
|
| 106 |
+
gr.Markdown("# Basic Agent Evaluation Runner (retry & error-safe)")
|
| 107 |
+
gr.LoginButton()
|
| 108 |
+
run_btn = gr.Button("Run Evaluation & Submit All Answers")
|
| 109 |
+
status_box = gr.Textbox(lines=5, label="Run Status / Submission Result")
|
| 110 |
+
results_tbl = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 111 |
+
run_btn.click(fn=run_and_submit_all, outputs=[status_box, results_tbl])
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
demo.launch(debug=True, share=False)
|