theakshayrane commited on
Commit
b7d9e16
·
verified ·
1 Parent(s): 97157c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -112
app.py CHANGED
@@ -1,25 +1,16 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
  from agent import BasicAgent
7
 
8
- # (Keep Constants as is)
9
- # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
-
13
- def run_and_submit_all( profile: gr.OAuthProfile | None):
14
- """
15
- Fetches all questions, runs the BasicAgent on them, submits all answers,
16
- and displays the results.
17
- """
18
- # --- Determine HF Space Runtime URL and Repo URL ---
19
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
20
 
21
  if profile:
22
- username= f"{profile.username}"
23
  print(f"User logged in: {username}")
24
  else:
25
  print("User not logged in.")
@@ -29,66 +20,43 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
29
  questions_url = f"{api_url}/questions"
30
  submit_url = f"{api_url}/submit"
31
 
32
- # 1. Instantiate Agent ( modify this part to create your agent)
33
  try:
34
  agent = BasicAgent()
35
  except Exception as e:
36
- print(f"Error instantiating agent: {e}")
37
  return f"Error initializing agent: {e}", None
38
- # 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)
39
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
40
- print(agent_code)
41
 
42
- # 2. Fetch Questions
43
  print(f"Fetching questions from: {questions_url}")
44
  try:
45
  response = requests.get(questions_url, timeout=15)
46
  response.raise_for_status()
47
  questions_data = response.json()
48
- if not questions_data:
49
- print("Fetched questions list is empty.")
50
- return "Fetched questions list is empty or invalid format.", None
51
- print(f"Fetched {len(questions_data)} questions.")
52
- except requests.exceptions.RequestException as e:
53
- print(f"Error fetching questions: {e}")
54
- return f"Error fetching questions: {e}", None
55
- except requests.exceptions.JSONDecodeError as e:
56
- print(f"Error decoding JSON response from questions endpoint: {e}")
57
- print(f"Response text: {response.text[:500]}")
58
- return f"Error decoding server response for questions: {e}", None
59
  except Exception as e:
60
- print(f"An unexpected error occurred fetching questions: {e}")
61
- return f"An unexpected error occurred fetching questions: {e}", None
62
 
63
- # 3. Run your Agent
64
  results_log = []
65
  answers_payload = []
66
  print(f"Running agent on {len(questions_data)} questions...")
 
67
  for item in questions_data:
68
  task_id = item.get("task_id")
69
  question_text = item.get("question")
70
  if not task_id or question_text is None:
71
- print(f"Skipping item with missing task_id or question: {item}")
72
  continue
73
  try:
74
  submitted_answer = agent(question_text)
75
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
76
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
77
  except Exception as e:
78
- print(f"Error running agent on task {task_id}: {e}")
79
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
80
 
81
  if not answers_payload:
82
- print("Agent did not produce any answers to submit.")
83
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
84
 
85
- # 4. Prepare Submission
86
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
87
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
88
- print(status_update)
89
-
90
- # 5. Submit
91
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
92
  try:
93
  response = requests.post(submit_url, json=submission_data, timeout=60)
94
  response.raise_for_status()
@@ -100,86 +68,18 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
100
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
101
  f"Message: {result_data.get('message', 'No message received.')}"
102
  )
103
- print("Submission successful.")
104
- results_df = pd.DataFrame(results_log)
105
- return final_status, results_df
106
- except requests.exceptions.HTTPError as e:
107
- error_detail = f"Server responded with status {e.response.status_code}."
108
- try:
109
- error_json = e.response.json()
110
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
111
- except requests.exceptions.JSONDecodeError:
112
- error_detail += f" Response: {e.response.text[:500]}"
113
- status_message = f"Submission Failed: {error_detail}"
114
- print(status_message)
115
- results_df = pd.DataFrame(results_log)
116
- return status_message, results_df
117
- except requests.exceptions.Timeout:
118
- status_message = "Submission Failed: The request timed out."
119
- print(status_message)
120
- results_df = pd.DataFrame(results_log)
121
- return status_message, results_df
122
- except requests.exceptions.RequestException as e:
123
- status_message = f"Submission Failed: Network error - {e}"
124
- print(status_message)
125
- results_df = pd.DataFrame(results_log)
126
- return status_message, results_df
127
  except Exception as e:
128
- status_message = f"An unexpected error occurred during submission: {e}"
129
- print(status_message)
130
- results_df = pd.DataFrame(results_log)
131
- return status_message, results_df
132
 
133
-
134
- # --- Build Gradio Interface using Blocks ---
135
  with gr.Blocks() as demo:
136
- gr.Markdown("# Basic Agent Evaluation Runner")
137
- gr.Markdown(
138
- """
139
- **Instructions:**
140
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
141
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
142
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
143
- ---
144
- **Disclaimers:**
145
- 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).
146
- 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.
147
- """
148
- )
149
-
150
  gr.LoginButton()
151
-
152
  run_button = gr.Button("Run Evaluation & Submit All Answers")
153
-
154
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
155
- # Removed max_rows=10 from DataFrame constructor
156
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
157
 
158
- run_button.click(
159
- fn=run_and_submit_all,
160
- outputs=[status_output, results_table]
161
- )
162
 
163
  if __name__ == "__main__":
164
- print("\n" + "-"*30 + " App Starting " + "-"*30)
165
- # Check for SPACE_HOST and SPACE_ID at startup for information
166
- space_host_startup = os.getenv("SPACE_HOST")
167
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
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: # Print repo URLs if SPACE_ID is found
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 Basic Agent Evaluation...")
185
  demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
  from agent import BasicAgent
6
 
 
 
7
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
 
9
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
10
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
 
 
11
 
12
  if profile:
13
+ username = f"{profile.username}"
14
  print(f"User logged in: {username}")
15
  else:
16
  print("User not logged in.")
 
20
  questions_url = f"{api_url}/questions"
21
  submit_url = f"{api_url}/submit"
22
 
 
23
  try:
24
  agent = BasicAgent()
25
  except Exception as e:
 
26
  return f"Error initializing agent: {e}", None
27
+
28
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
29
 
 
30
  print(f"Fetching questions from: {questions_url}")
31
  try:
32
  response = requests.get(questions_url, timeout=15)
33
  response.raise_for_status()
34
  questions_data = response.json()
 
 
 
 
 
 
 
 
 
 
 
35
  except Exception as e:
36
+ return f"Error fetching questions: {e}", None
 
37
 
 
38
  results_log = []
39
  answers_payload = []
40
  print(f"Running agent on {len(questions_data)} questions...")
41
+
42
  for item in questions_data:
43
  task_id = item.get("task_id")
44
  question_text = item.get("question")
45
  if not task_id or question_text is None:
 
46
  continue
47
  try:
48
  submitted_answer = agent(question_text)
49
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
50
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
51
  except Exception as e:
 
52
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
53
 
54
  if not answers_payload:
 
55
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
56
 
 
57
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
58
+
59
+ print(f"Submitting {len(answers_payload)} answers...")
 
 
 
60
  try:
61
  response = requests.post(submit_url, json=submission_data, timeout=60)
62
  response.raise_for_status()
 
68
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
69
  f"Message: {result_data.get('message', 'No message received.')}"
70
  )
71
+ return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  except Exception as e:
73
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
74
 
 
 
75
  with gr.Blocks() as demo:
76
+ gr.Markdown("# GAIA Benchmark Agent Runner")
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  gr.LoginButton()
 
78
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
79
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
80
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
81
 
82
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
83
 
84
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  demo.launch(debug=True, share=False)