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