selim-ba commited on
Commit
d2cf8a1
·
verified ·
1 Parent(s): cf28003

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -0
app.py CHANGED
@@ -178,6 +178,158 @@ class SuperSmartAgent:
178
 
179
  return state
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
  if __name__ == "__main__":
183
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
178
 
179
  return state
180
 
181
+ ########################################
182
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
183
+ """
184
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
185
+ and displays the results.
186
+ """
187
+ # --- Determine HF Space Runtime URL and Repo URL ---
188
+ space_id = os.getenv("https://huggingface.co/spaces/selim-ba/Final_Agent_HF_Course/tree/main") # Get the SPACE_ID for sending link to the code
189
+
190
+ if profile:
191
+ username= f"{profile.username}"
192
+ print(f"User logged in: {username}")
193
+ else:
194
+ print("User not logged in.")
195
+ return "Please Login to Hugging Face with the button.", None
196
+
197
+ api_url = DEFAULT_API_URL
198
+ questions_url = f"{api_url}/questions"
199
+ submit_url = f"{api_url}/submit"
200
+
201
+ # 1. Instantiate Agent ( modify this part to create your agent)
202
+ try:
203
+ agent = SuperSmartAgent() #BasicAgent()
204
+ except Exception as e:
205
+ print(f"Error instantiating agent: {e}")
206
+ return f"Error initializing agent: {e}", None
207
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
208
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
209
+ print(agent_code)
210
+
211
+ # 2. Fetch Questions
212
+ print(f"Fetching questions from: {questions_url}")
213
+ try:
214
+ response = requests.get(questions_url, timeout=15)
215
+ response.raise_for_status()
216
+ questions_data = response.json()
217
+ if not questions_data:
218
+ print("Fetched questions list is empty.")
219
+ return "Fetched questions list is empty or invalid format.", None
220
+ print(f"Fetched {len(questions_data)} questions.")
221
+ except requests.exceptions.RequestException as e:
222
+ print(f"Error fetching questions: {e}")
223
+ return f"Error fetching questions: {e}", None
224
+ except requests.exceptions.JSONDecodeError as e:
225
+ print(f"Error decoding JSON response from questions endpoint: {e}")
226
+ print(f"Response text: {response.text[:500]}")
227
+ return f"Error decoding server response for questions: {e}", None
228
+ except Exception as e:
229
+ print(f"An unexpected error occurred fetching questions: {e}")
230
+ return f"An unexpected error occurred fetching questions: {e}", None
231
+
232
+ # 3. Run your Agent
233
+ results_log = []
234
+ answers_payload = []
235
+ print(f"Running agent on {len(questions_data)} questions...")
236
+ for item in questions_data:
237
+ task_id = item.get("task_id")
238
+ question_text = item.get("question")
239
+ if not task_id or question_text is None:
240
+ print(f"Skipping item with missing task_id or question: {item}")
241
+ continue
242
+ try:
243
+ submitted_answer = agent(question_text)
244
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
245
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
246
+ except Exception as e:
247
+ print(f"Error running agent on task {task_id}: {e}")
248
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
249
+
250
+ if not answers_payload:
251
+ print("Agent did not produce any answers to submit.")
252
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
253
+
254
+ # 4. Prepare Submission
255
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
256
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
257
+ print(status_update)
258
+
259
+ # 5. Submit
260
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
261
+ try:
262
+ response = requests.post(submit_url, json=submission_data, timeout=60)
263
+ response.raise_for_status()
264
+ result_data = response.json()
265
+ final_status = (
266
+ f"Submission Successful!\n"
267
+ f"User: {result_data.get('username')}\n"
268
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
269
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
270
+ f"Message: {result_data.get('message', 'No message received.')}"
271
+ )
272
+ print("Submission successful.")
273
+ results_df = pd.DataFrame(results_log)
274
+ return final_status, results_df
275
+ except requests.exceptions.HTTPError as e:
276
+ error_detail = f"Server responded with status {e.response.status_code}."
277
+ try:
278
+ error_json = e.response.json()
279
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
280
+ except requests.exceptions.JSONDecodeError:
281
+ error_detail += f" Response: {e.response.text[:500]}"
282
+ status_message = f"Submission Failed: {error_detail}"
283
+ print(status_message)
284
+ results_df = pd.DataFrame(results_log)
285
+ return status_message, results_df
286
+ except requests.exceptions.Timeout:
287
+ status_message = "Submission Failed: The request timed out."
288
+ print(status_message)
289
+ results_df = pd.DataFrame(results_log)
290
+ return status_message, results_df
291
+ except requests.exceptions.RequestException as e:
292
+ status_message = f"Submission Failed: Network error - {e}"
293
+ print(status_message)
294
+ results_df = pd.DataFrame(results_log)
295
+ return status_message, results_df
296
+ except Exception as e:
297
+ status_message = f"An unexpected error occurred during submission: {e}"
298
+ print(status_message)
299
+ results_df = pd.DataFrame(results_log)
300
+ return status_message, results_df
301
+
302
+ # --- Build Gradio Interface using Blocks ---
303
+ with gr.Blocks() as demo:
304
+ gr.Markdown("# Basic Agent Evaluation Runner")
305
+ gr.Markdown(
306
+ """
307
+ **Instructions:**
308
+
309
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
310
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
311
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
312
+
313
+ ---
314
+ **Disclaimers:**
315
+ Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
316
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
317
+ """
318
+ )
319
+
320
+ gr.LoginButton()
321
+
322
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
323
+
324
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
325
+ # Removed max_rows=10 from DataFrame constructor
326
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
327
+
328
+ run_button.click(
329
+ fn=run_and_submit_all,
330
+ outputs=[status_output, results_table]
331
+ )
332
+
333
 
334
  if __name__ == "__main__":
335
  print("\n" + "-"*30 + " App Starting " + "-"*30)