Spaces:
Sleeping
Sleeping
added test
Browse files
app.py
CHANGED
@@ -3,7 +3,7 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import pandas as pd
|
5 |
|
6 |
-
from agent import create_agent
|
7 |
|
8 |
# --- Constants ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
@@ -11,24 +11,24 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
11 |
|
12 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
13 |
"""
|
14 |
-
|
15 |
-
and
|
16 |
"""
|
17 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
18 |
-
space_id = os.getenv("SPACE_ID")
|
19 |
|
20 |
if profile:
|
21 |
-
username =
|
22 |
print(f"User logged in: {username}")
|
23 |
else:
|
24 |
print("User not logged in.")
|
25 |
-
return "Please
|
26 |
|
27 |
api_url = DEFAULT_API_URL
|
28 |
questions_url = f"{api_url}/questions"
|
29 |
submit_url = f"{api_url}/submit"
|
30 |
|
31 |
-
# 1. Instantiate
|
32 |
try:
|
33 |
agent = create_agent()
|
34 |
print("SmolAgent initialized.")
|
@@ -36,11 +36,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
36 |
print(f"Error instantiating agent: {e}")
|
37 |
return f"Error initializing agent: {e}", None
|
38 |
|
39 |
-
#
|
40 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
41 |
print(agent_code)
|
42 |
|
43 |
-
# 2. Fetch
|
44 |
print(f"Fetching questions from: {questions_url}")
|
45 |
try:
|
46 |
response = requests.get(questions_url, timeout=15)
|
@@ -50,18 +50,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
50 |
print("Fetched questions list is empty.")
|
51 |
return "Fetched questions list is empty or invalid format.", None
|
52 |
print(f"Fetched {len(questions_data)} questions.")
|
53 |
-
except
|
54 |
print(f"Error fetching questions: {e}")
|
55 |
return f"Error fetching questions: {e}", None
|
56 |
-
except requests.exceptions.JSONDecodeError as e:
|
57 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
58 |
-
print(f"Response text: {response.text[:500]}")
|
59 |
-
return f"Error decoding server response for questions: {e}", None
|
60 |
-
except Exception as e:
|
61 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
62 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
63 |
|
64 |
-
# 3. Run
|
65 |
results_log = []
|
66 |
answers_payload = []
|
67 |
print(f"Running agent on {len(questions_data)} questions...")
|
@@ -69,117 +62,78 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
69 |
task_id = item.get("task_id")
|
70 |
question_text = item.get("question")
|
71 |
if not task_id or question_text is None:
|
72 |
-
print(f"Skipping item
|
73 |
continue
|
74 |
try:
|
75 |
-
|
76 |
-
answers_payload.append({"task_id": task_id, "submitted_answer":
|
77 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "
|
78 |
except Exception as e:
|
79 |
-
print(f"Error
|
80 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "
|
81 |
|
82 |
if not answers_payload:
|
83 |
-
|
84 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
85 |
-
|
86 |
-
# 4. Prepare Submission
|
87 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
88 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
89 |
-
print(status_update)
|
90 |
|
91 |
-
#
|
92 |
-
|
|
|
93 |
try:
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
f"Submission Successful!\n"
|
99 |
-
f"User: {
|
100 |
-
f"
|
101 |
-
f"
|
102 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
103 |
)
|
104 |
-
|
105 |
-
results_df = pd.DataFrame(results_log)
|
106 |
-
return final_status, results_df
|
107 |
-
except requests.exceptions.HTTPError as e:
|
108 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
109 |
-
try:
|
110 |
-
error_json = e.response.json()
|
111 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
112 |
-
except requests.exceptions.JSONDecodeError:
|
113 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
114 |
-
status_message = f"Submission Failed: {error_detail}"
|
115 |
-
print(status_message)
|
116 |
-
results_df = pd.DataFrame(results_log)
|
117 |
-
return status_message, results_df
|
118 |
-
except requests.exceptions.Timeout:
|
119 |
-
status_message = "Submission Failed: The request timed out."
|
120 |
-
print(status_message)
|
121 |
-
results_df = pd.DataFrame(results_log)
|
122 |
-
return status_message, results_df
|
123 |
-
except requests.exceptions.RequestException as e:
|
124 |
-
status_message = f"Submission Failed: Network error - {e}"
|
125 |
-
print(status_message)
|
126 |
-
results_df = pd.DataFrame(results_log)
|
127 |
-
return status_message, results_df
|
128 |
except Exception as e:
|
129 |
-
|
130 |
-
|
131 |
-
results_df = pd.DataFrame(results_log)
|
132 |
-
return status_message, results_df
|
133 |
|
134 |
|
135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
with gr.Blocks() as demo:
|
137 |
gr.Markdown("# SmolAgent Evaluation Runner")
|
138 |
gr.Markdown(
|
139 |
"""
|
140 |
**Instructions:**
|
141 |
-
1.
|
142 |
-
2.
|
143 |
-
3.
|
144 |
-
|
145 |
-
---
|
146 |
-
**Disclaimers:**
|
147 |
-
After clicking the submit button, it can take some time for the agent to process all questions.
|
148 |
-
This space offers a basic setup; feel free to optimize or extend it (e.g., caching answers, async execution).
|
149 |
"""
|
150 |
)
|
151 |
|
152 |
-
gr.LoginButton()
|
|
|
|
|
153 |
|
154 |
-
|
|
|
|
|
|
|
155 |
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
run_button.click(
|
160 |
-
fn=run_and_submit_all,
|
161 |
-
outputs=[status_output, results_table]
|
162 |
-
)
|
163 |
|
164 |
if __name__ == "__main__":
|
165 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
166 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
167 |
-
space_id_startup = os.getenv("SPACE_ID")
|
168 |
-
|
169 |
-
if space_host_startup:
|
170 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
171 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
172 |
-
else:
|
173 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
174 |
-
|
175 |
-
if space_id_startup:
|
176 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
177 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
178 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
179 |
-
else:
|
180 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
181 |
-
|
182 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
183 |
-
|
184 |
-
print("Launching Gradio Interface for SmolAgent Evaluation...")
|
185 |
demo.launch(debug=True, share=False)
|
|
|
3 |
import requests
|
4 |
import pandas as pd
|
5 |
|
6 |
+
from agent import create_agent, fetch_random_question
|
7 |
|
8 |
# --- Constants ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
11 |
|
12 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
13 |
"""
|
14 |
+
Fetch all questions, run the SmolAgent on them, submit all answers,
|
15 |
+
and display the results.
|
16 |
"""
|
17 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
18 |
+
space_id = os.getenv("SPACE_ID")
|
19 |
|
20 |
if profile:
|
21 |
+
username = profile.username
|
22 |
print(f"User logged in: {username}")
|
23 |
else:
|
24 |
print("User not logged in.")
|
25 |
+
return "Please login to Hugging Face with the button.", None
|
26 |
|
27 |
api_url = DEFAULT_API_URL
|
28 |
questions_url = f"{api_url}/questions"
|
29 |
submit_url = f"{api_url}/submit"
|
30 |
|
31 |
+
# 1. Instantiate SmolAgent
|
32 |
try:
|
33 |
agent = create_agent()
|
34 |
print("SmolAgent initialized.")
|
|
|
36 |
print(f"Error instantiating agent: {e}")
|
37 |
return f"Error initializing agent: {e}", None
|
38 |
|
39 |
+
# Code link for verification
|
40 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
41 |
print(agent_code)
|
42 |
|
43 |
+
# 2. Fetch all questions
|
44 |
print(f"Fetching questions from: {questions_url}")
|
45 |
try:
|
46 |
response = requests.get(questions_url, timeout=15)
|
|
|
50 |
print("Fetched questions list is empty.")
|
51 |
return "Fetched questions list is empty or invalid format.", None
|
52 |
print(f"Fetched {len(questions_data)} questions.")
|
53 |
+
except Exception as e:
|
54 |
print(f"Error fetching questions: {e}")
|
55 |
return f"Error fetching questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
+
# 3. Run agent on each question
|
58 |
results_log = []
|
59 |
answers_payload = []
|
60 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
62 |
task_id = item.get("task_id")
|
63 |
question_text = item.get("question")
|
64 |
if not task_id or question_text is None:
|
65 |
+
print(f"Skipping invalid item: {item}")
|
66 |
continue
|
67 |
try:
|
68 |
+
answer = agent.run(question=question_text)
|
69 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
70 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Answer": answer})
|
71 |
except Exception as e:
|
72 |
+
print(f"Error on task {task_id}: {e}")
|
73 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Answer": f"ERROR: {e}"})
|
74 |
|
75 |
if not answers_payload:
|
76 |
+
return "Agent produced no answers.", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
+
# 4. Submit answers
|
79 |
+
payload = {"username": username, "agent_code": agent_code, "answers": answers_payload}
|
80 |
+
print(f"Submitting {len(answers_payload)} answers...")
|
81 |
try:
|
82 |
+
resp = requests.post(submit_url, json=payload, timeout=60)
|
83 |
+
resp.raise_for_status()
|
84 |
+
data = resp.json()
|
85 |
+
status = (
|
86 |
f"Submission Successful!\n"
|
87 |
+
f"User: {data.get('username')}\n"
|
88 |
+
f"Score: {data.get('score')}% ({data.get('correct_count')}/{data.get('total_attempted')})\n"
|
89 |
+
f"Message: {data.get('message')}"
|
|
|
90 |
)
|
91 |
+
return status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
except Exception as e:
|
93 |
+
print(f"Submission error: {e}")
|
94 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
|
|
|
|
95 |
|
96 |
|
97 |
+
def test_random_question(profile: gr.OAuthProfile | None):
|
98 |
+
"""
|
99 |
+
Fetch a random GAIA question and get the agent's answer for testing.
|
100 |
+
"""
|
101 |
+
if not profile:
|
102 |
+
return "Please login to test.", ""
|
103 |
+
|
104 |
+
try:
|
105 |
+
q = fetch_random_question()
|
106 |
+
agent = create_agent()
|
107 |
+
ans = agent.run(question=q.get('question', ''))
|
108 |
+
return q.get('question', ''), ans
|
109 |
+
except Exception as e:
|
110 |
+
print(f"Test error: {e}")
|
111 |
+
return f"Error: {e}", ""
|
112 |
+
|
113 |
+
|
114 |
+
# --- Build Gradio Interface ---
|
115 |
with gr.Blocks() as demo:
|
116 |
gr.Markdown("# SmolAgent Evaluation Runner")
|
117 |
gr.Markdown(
|
118 |
"""
|
119 |
**Instructions:**
|
120 |
+
1. Clone this space and define your agent logic in agent.py.
|
121 |
+
2. Log in with your Hugging Face account.
|
122 |
+
3. Use 'Run Evaluation & Submit All Answers' or 'Test Random Question'.
|
|
|
|
|
|
|
|
|
|
|
123 |
"""
|
124 |
)
|
125 |
|
126 |
+
login = gr.LoginButton()
|
127 |
+
run_all_btn = gr.Button("Run Evaluation & Submit All Answers")
|
128 |
+
test_btn = gr.Button("Test Random Question")
|
129 |
|
130 |
+
status_box = gr.Textbox(label="Status / Result", lines=5, interactive=False)
|
131 |
+
results_table = gr.DataFrame(label="Full Results Table", wrap=True)
|
132 |
+
question_box = gr.Textbox(label="Random Question", lines=3, interactive=False)
|
133 |
+
answer_box = gr.Textbox(label="Agent Answer", lines=3, interactive=False)
|
134 |
|
135 |
+
run_all_btn.click(fn=run_and_submit_all, inputs=[login], outputs=[status_box, results_table])
|
136 |
+
test_btn.click(fn=test_random_question, inputs=[login], outputs=[question_box, answer_box])
|
|
|
|
|
|
|
|
|
|
|
137 |
|
138 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
demo.launch(debug=True, share=False)
|