Neda1 commited on
Commit
fceb1b8
Β·
verified Β·
1 Parent(s): e47210b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +246 -38
app.py CHANGED
@@ -12,7 +12,6 @@ from agent import build_graph
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
- #DEFAULT_API_URL= "https://neda1-agent-final.hf.space.hf.space"
16
 
17
  # --- Basic Agent Definition ---
18
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
@@ -26,11 +25,11 @@ class BasicAgent:
26
 
27
  def __call__(self, question: str) -> str:
28
  print(f"Agent received question (first 50 chars): {question[:50]}...")
29
- # Wrap the question in a HumanMessage from langchain_core
30
  messages = [HumanMessage(content=question)]
31
- messages = self.graph.invoke({"messages": messages})
32
- answer = messages['messages'][-1].content
33
- return answer[14:]
 
34
 
35
 
36
  def run_and_submit_all( profile: gr.OAuthProfile | None):
@@ -39,7 +38,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
39
  and displays the results.
40
  """
41
  # --- Determine HF Space Runtime URL and Repo URL ---
42
- space_id = os.getenv("SPACE_ID", "https://huggingface.co/spaces/Neda1/agent_final")# Get the SPACE_ID for sending link to the code
43
 
44
  if profile:
45
  username= f"{profile.username}"
@@ -188,7 +187,6 @@ if __name__ == "__main__":
188
  # Check for SPACE_HOST and SPACE_ID at startup for information
189
  space_host_startup = os.getenv("SPACE_HOST")
190
  space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
191
-
192
 
193
  if space_host_startup:
194
  print(f"βœ… SPACE_HOST found: {space_host_startup}")
@@ -206,47 +204,257 @@ if __name__ == "__main__":
206
  print("-"*(60 + len(" App Starting ")) + "\n")
207
 
208
  print("Launching Gradio Interface for Basic Agent Evaluation...")
209
- with gr.Blocks() as demo:
210
- gr.Markdown("# Basic Agent Evaluation Runner")
211
- gr.Markdown(
212
- """
213
- **Instructions:**
214
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
215
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
216
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
217
- ---
218
- **Disclaimers:**
219
- 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).
220
- 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.
221
- """
222
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
- gr.LoginButton()
225
 
226
- run_button = gr.Button("Run Evaluation & Submit All Answers")
227
 
228
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
229
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
230
 
231
- run_button.click(
232
- fn=run_and_submit_all,
233
- outputs=[status_output, results_table]
234
- )
235
 
236
- # βœ… Manual Test Interface (Put inside Blocks!)
237
- gr.Markdown("## Ask your Agent Any Question (Manual Test)")
238
- free_question = gr.Textbox(label="Ask your own question")
239
- free_response = gr.Textbox(label="Agent's Response", interactive=False)
240
 
241
- test_agent = BasicAgent()
242
 
243
- def run_custom_query(q):
244
- return test_agent(q)
245
 
246
- free_question.submit(fn=run_custom_query, inputs=free_question, outputs=free_response)
247
 
248
 
249
 
250
 
251
 
252
- demo.launch(debug=True, share=False)
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
15
 
16
  # --- Basic Agent Definition ---
17
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
25
 
26
  def __call__(self, question: str) -> str:
27
  print(f"Agent received question (first 50 chars): {question[:50]}...")
 
28
  messages = [HumanMessage(content=question)]
29
+ result = self.graph.invoke({"messages": messages})
30
+ answer = result['messages'][-1].content
31
+ return answer # kein [14:] mehr nΓΆtig!
32
+
33
 
34
 
35
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
38
  and displays the results.
39
  """
40
  # --- Determine HF Space Runtime URL and Repo URL ---
41
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
42
 
43
  if profile:
44
  username= f"{profile.username}"
 
187
  # Check for SPACE_HOST and SPACE_ID at startup for information
188
  space_host_startup = os.getenv("SPACE_HOST")
189
  space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
 
190
 
191
  if space_host_startup:
192
  print(f"βœ… SPACE_HOST found: {space_host_startup}")
 
204
  print("-"*(60 + len(" App Starting ")) + "\n")
205
 
206
  print("Launching Gradio Interface for Basic Agent Evaluation...")
207
+ demo.launch(debug=True, share=False)
208
+
209
+ # """ Basic Agent Evaluation Runner"""
210
+ # import os
211
+ # import inspect
212
+ # import gradio as gr
213
+ # import requests
214
+ # import pandas as pd
215
+ # from langchain_core.messages import HumanMessage
216
+ # from agent import build_graph
217
+
218
+
219
+
220
+ # # (Keep Constants as is)
221
+ # # --- Constants ---
222
+ # DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
223
+ # #DEFAULT_API_URL= "https://neda1-agent-final.hf.space.hf.space"
224
+
225
+ # # --- Basic Agent Definition ---
226
+ # # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
227
+
228
+
229
+ # class BasicAgent:
230
+ # """A langgraph agent."""
231
+ # def __init__(self):
232
+ # print("BasicAgent initialized.")
233
+ # self.graph = build_graph()
234
+
235
+ # def __call__(self, question: str) -> str:
236
+ # print(f"Agent received question (first 50 chars): {question[:50]}...")
237
+ # # Wrap the question in a HumanMessage from langchain_core
238
+ # messages = [HumanMessage(content=question)]
239
+ # messages = self.graph.invoke({"messages": messages})
240
+ # answer = messages['messages'][-1].content
241
+ # return answer[14:]
242
+
243
+
244
+ # def run_and_submit_all( profile: gr.OAuthProfile | None):
245
+ # """
246
+ # Fetches all questions, runs the BasicAgent on them, submits all answers,
247
+ # and displays the results.
248
+ # """
249
+ # # --- Determine HF Space Runtime URL and Repo URL ---
250
+ # space_id = os.getenv("SPACE_ID", "https://huggingface.co/spaces/Neda1/agent_final")# Get the SPACE_ID for sending link to the code
251
+
252
+ # if profile:
253
+ # username= f"{profile.username}"
254
+ # print(f"User logged in: {username}")
255
+ # else:
256
+ # print("User not logged in.")
257
+ # return "Please Login to Hugging Face with the button.", None
258
+
259
+ # api_url = DEFAULT_API_URL
260
+ # questions_url = f"{api_url}/questions"
261
+ # submit_url = f"{api_url}/submit"
262
+
263
+ # # 1. Instantiate Agent ( modify this part to create your agent)
264
+ # try:
265
+ # agent = BasicAgent()
266
+ # except Exception as e:
267
+ # print(f"Error instantiating agent: {e}")
268
+ # return f"Error initializing agent: {e}", None
269
+ # # 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)
270
+ # agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
271
+ # print(agent_code)
272
+
273
+ # # 2. Fetch Questions
274
+ # print(f"Fetching questions from: {questions_url}")
275
+ # try:
276
+ # response = requests.get(questions_url, timeout=15)
277
+ # response.raise_for_status()
278
+ # questions_data = response.json()
279
+ # if not questions_data:
280
+ # print("Fetched questions list is empty.")
281
+ # return "Fetched questions list is empty or invalid format.", None
282
+ # print(f"Fetched {len(questions_data)} questions.")
283
+ # except requests.exceptions.RequestException as e:
284
+ # print(f"Error fetching questions: {e}")
285
+ # return f"Error fetching questions: {e}", None
286
+ # except requests.exceptions.JSONDecodeError as e:
287
+ # print(f"Error decoding JSON response from questions endpoint: {e}")
288
+ # print(f"Response text: {response.text[:500]}")
289
+ # return f"Error decoding server response for questions: {e}", None
290
+ # except Exception as e:
291
+ # print(f"An unexpected error occurred fetching questions: {e}")
292
+ # return f"An unexpected error occurred fetching questions: {e}", None
293
+
294
+ # # 3. Run your Agent
295
+ # results_log = []
296
+ # answers_payload = []
297
+ # print(f"Running agent on {len(questions_data)} questions...")
298
+ # for item in questions_data:
299
+ # task_id = item.get("task_id")
300
+ # question_text = item.get("question")
301
+ # if not task_id or question_text is None:
302
+ # print(f"Skipping item with missing task_id or question: {item}")
303
+ # continue
304
+ # try:
305
+ # submitted_answer = agent(question_text)
306
+ # answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
307
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
308
+ # except Exception as e:
309
+ # print(f"Error running agent on task {task_id}: {e}")
310
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
311
+
312
+ # if not answers_payload:
313
+ # print("Agent did not produce any answers to submit.")
314
+ # return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
315
+
316
+ # # 4. Prepare Submission
317
+ # submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
318
+ # status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
319
+ # print(status_update)
320
+
321
+ # # 5. Submit
322
+ # print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
323
+ # try:
324
+ # response = requests.post(submit_url, json=submission_data, timeout=60)
325
+ # response.raise_for_status()
326
+ # result_data = response.json()
327
+ # final_status = (
328
+ # f"Submission Successful!\n"
329
+ # f"User: {result_data.get('username')}\n"
330
+ # f"Overall Score: {result_data.get('score', 'N/A')}% "
331
+ # f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
332
+ # f"Message: {result_data.get('message', 'No message received.')}"
333
+ # )
334
+ # print("Submission successful.")
335
+ # results_df = pd.DataFrame(results_log)
336
+ # return final_status, results_df
337
+ # except requests.exceptions.HTTPError as e:
338
+ # error_detail = f"Server responded with status {e.response.status_code}."
339
+ # try:
340
+ # error_json = e.response.json()
341
+ # error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
342
+ # except requests.exceptions.JSONDecodeError:
343
+ # error_detail += f" Response: {e.response.text[:500]}"
344
+ # status_message = f"Submission Failed: {error_detail}"
345
+ # print(status_message)
346
+ # results_df = pd.DataFrame(results_log)
347
+ # return status_message, results_df
348
+ # except requests.exceptions.Timeout:
349
+ # status_message = "Submission Failed: The request timed out."
350
+ # print(status_message)
351
+ # results_df = pd.DataFrame(results_log)
352
+ # return status_message, results_df
353
+ # except requests.exceptions.RequestException as e:
354
+ # status_message = f"Submission Failed: Network error - {e}"
355
+ # print(status_message)
356
+ # results_df = pd.DataFrame(results_log)
357
+ # return status_message, results_df
358
+ # except Exception as e:
359
+ # status_message = f"An unexpected error occurred during submission: {e}"
360
+ # print(status_message)
361
+ # results_df = pd.DataFrame(results_log)
362
+ # return status_message, results_df
363
+
364
+
365
+ # # --- Build Gradio Interface using Blocks ---
366
+ # with gr.Blocks() as demo:
367
+ # gr.Markdown("# Basic Agent Evaluation Runner")
368
+ # gr.Markdown(
369
+ # """
370
+ # **Instructions:**
371
+ # 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
372
+ # 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
373
+ # 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
374
+ # ---
375
+ # **Disclaimers:**
376
+ # 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).
377
+ # 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.
378
+ # """
379
+ # )
380
+
381
+ # gr.LoginButton()
382
+
383
+ # run_button = gr.Button("Run Evaluation & Submit All Answers")
384
+
385
+ # status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
386
+ # # Removed max_rows=10 from DataFrame constructor
387
+ # results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
388
+
389
+ # run_button.click(
390
+ # fn=run_and_submit_all,
391
+ # outputs=[status_output, results_table]
392
+ # )
393
+
394
+ # if __name__ == "__main__":
395
+ # print("\n" + "-"*30 + " App Starting " + "-"*30)
396
+ # # Check for SPACE_HOST and SPACE_ID at startup for information
397
+ # space_host_startup = os.getenv("SPACE_HOST")
398
+ # space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
399
+
400
+
401
+ # if space_host_startup:
402
+ # print(f"βœ… SPACE_HOST found: {space_host_startup}")
403
+ # print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
404
+ # else:
405
+ # print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
406
+
407
+ # if space_id_startup: # Print repo URLs if SPACE_ID is found
408
+ # print(f"βœ… SPACE_ID found: {space_id_startup}")
409
+ # print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
410
+ # print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
411
+ # else:
412
+ # print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
413
+
414
+ # print("-"*(60 + len(" App Starting ")) + "\n")
415
+
416
+ # print("Launching Gradio Interface for Basic Agent Evaluation...")
417
+ # with gr.Blocks() as demo:
418
+ # gr.Markdown("# Basic Agent Evaluation Runner")
419
+ # gr.Markdown(
420
+ # """
421
+ # **Instructions:**
422
+ # 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
423
+ # 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
424
+ # 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
425
+ # ---
426
+ # **Disclaimers:**
427
+ # 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).
428
+ # 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.
429
+ # """
430
+ # )
431
 
432
+ # gr.LoginButton()
433
 
434
+ # run_button = gr.Button("Run Evaluation & Submit All Answers")
435
 
436
+ # status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
437
+ # results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
438
 
439
+ # run_button.click(
440
+ # fn=run_and_submit_all,
441
+ # outputs=[status_output, results_table]
442
+ # )
443
 
444
+ # # βœ… Manual Test Interface (Put inside Blocks!)
445
+ # gr.Markdown("## Ask your Agent Any Question (Manual Test)")
446
+ # free_question = gr.Textbox(label="Ask your own question")
447
+ # free_response = gr.Textbox(label="Agent's Response", interactive=False)
448
 
449
+ # test_agent = BasicAgent()
450
 
451
+ # def run_custom_query(q):
452
+ # return test_agent(q)
453
 
454
+ # free_question.submit(fn=run_custom_query, inputs=free_question, outputs=free_response)
455
 
456
 
457
 
458
 
459
 
460
+ # demo.launch(debug=True, share=False)