Mtchmann commited on
Commit
16a1df5
·
verified ·
1 Parent(s): 92da7ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -36
app.py CHANGED
@@ -117,28 +117,50 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
117
  response = requests.get(questions_url, timeout=20)
118
  response.raise_for_status()
119
  questions_data = response.json()
120
- except requests.RequestException as e:
 
 
 
 
 
121
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
122
 
123
  # 4. Run Agent on Questions
124
  results_log = []
125
  answers_payload = []
126
- for item in progress.tqdm(questions_data, desc="Answering Questions"):
 
127
  task_id = item.get("task_id")
128
  question_text = item.get("question")
129
-
130
- submitted_answer = agent(question_text)
131
-
132
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
133
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
134
 
135
- results_df = pd.DataFrame(results_log)
136
  if not answers_payload:
137
- return "Agent did not produce any answers to submit.", results_df
 
138
 
139
  # 5. Prepare and Submit Answers
140
- submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
 
 
141
 
 
 
142
  try:
143
  response = requests.post(submit_url, json=submission_data, timeout=60)
144
  response.raise_for_status()
@@ -150,6 +172,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
150
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
151
  f"Message: {result_data.get('message', 'No message received.')}"
152
  )
 
 
153
  return final_status, results_df
154
  except requests.exceptions.HTTPError as e:
155
  error_detail = f"Server responded with status {e.response.status_code}."
@@ -158,49 +182,75 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
158
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
159
  except requests.exceptions.JSONDecodeError:
160
  error_detail += f" Response: {e.response.text[:500]}"
161
- return f"Submission Failed: {error_detail}", results_df
 
 
 
 
 
 
 
 
162
  except requests.exceptions.RequestException as e:
163
- return f"Submission Failed: Network error - {e}", results_df
 
 
 
 
 
 
 
 
164
 
165
  # --- Build Gradio Interface using Blocks ---
166
- with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
167
- gr.Markdown("# GAIA Agent Evaluation Runner")
168
  gr.Markdown(
169
  """
170
  **Instructions:**
171
- 1. Log in to your Hugging Face account using the button below. This is required to identify you for the submission.
172
- 2. Ensure you have set `HUGGING_FACE_HUB_TOKEN` and `TAVILY_API_KEY` as secrets in your Space settings. The application will use these automatically.
173
- 3. Click 'Run Evaluation & Submit All Answers' to start the process.
 
 
 
 
174
  """
175
  )
176
 
177
- with gr.Row():
178
- gr.LoginButton(value="Sign In with Hugging Face")
179
 
180
- # State component to store the username persistently across interactions.
181
- username_state = gr.State("")
182
-
183
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
184
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
185
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
186
 
187
- # --- Event Handler Wiring ---
188
-
189
- # On page load (or after login), store the username in the state component.
190
- # The `gr.Request` object is passed implicitly to the function.
191
- demo.load(
192
- fn=store_username,
193
- inputs=None,
194
- outputs=[username_state]
195
- )
196
-
197
- # When the run button is clicked, pass the stored username from the state.
198
  run_button.click(
199
  fn=run_and_submit_all,
200
- inputs=[username_state],
201
  outputs=[status_output, results_table]
202
  )
203
 
204
  if __name__ == "__main__":
205
- print("Launching Gradio Interface for GAIA Agent Evaluation...")
206
- demo.launch(share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  response = requests.get(questions_url, timeout=20)
118
  response.raise_for_status()
119
  questions_data = response.json()
120
+ if not questions_data:
121
+ print("Fetched questions list is empty.")
122
+ return "Fetched questions list is empty or invalid format.", None
123
+ print(f"Fetched {len(questions_data)} questions.")
124
+ except requests.exceptions.RequestException as e:
125
+ print(f"Error fetching questions: {e}")
126
  return f"Error fetching questions: {e}", None
127
+ except requests.exceptions.JSONDecodeError as e:
128
+ print(f"Error decoding JSON response from questions endpoint: {e}")
129
+ print(f"Response text: {response.text[:500]}")
130
+ return f"Error decoding server response for questions: {e}", None
131
+ except Exception as e:
132
+ print(f"An unexpected error occurred fetching questions: {e}")
133
+ return f"An unexpected error occurred fetching questions: {e}", None
134
 
135
  # 4. Run Agent on Questions
136
  results_log = []
137
  answers_payload = []
138
+ print(f"Running agent on {len(questions_data)} questions...")
139
+ for item in questions_data:
140
  task_id = item.get("task_id")
141
  question_text = item.get("question")
142
+ if not task_id or question_text is None:
143
+ print(f"Skipping item with missing task_id or question: {item}")
144
+ continue
145
+ try:
146
+ submitted_answer = agent(question_text)
147
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
148
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
149
+ except Exception as e:
150
+ print(f"Error running agent on task {task_id}: {e}")
151
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
152
 
 
153
  if not answers_payload:
154
+ print("Agent did not produce any answers to submit.")
155
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
156
 
157
  # 5. Prepare and Submit Answers
158
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
159
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
160
+ print(status_update)
161
 
162
+ # 5. Submit
163
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
164
  try:
165
  response = requests.post(submit_url, json=submission_data, timeout=60)
166
  response.raise_for_status()
 
172
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
173
  f"Message: {result_data.get('message', 'No message received.')}"
174
  )
175
+ print("Submission successful.")
176
+ results_df = pd.DataFrame(results_log)
177
  return final_status, results_df
178
  except requests.exceptions.HTTPError as e:
179
  error_detail = f"Server responded with status {e.response.status_code}."
 
182
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
183
  except requests.exceptions.JSONDecodeError:
184
  error_detail += f" Response: {e.response.text[:500]}"
185
+ status_message = f"Submission Failed: {error_detail}"
186
+ print(status_message)
187
+ results_df = pd.DataFrame(results_log)
188
+ return status_message, results_df
189
+ except requests.exceptions.Timeout:
190
+ status_message = "Submission Failed: The request timed out."
191
+ print(status_message)
192
+ results_df = pd.DataFrame(results_log)
193
+ return status_message, results_df
194
  except requests.exceptions.RequestException as e:
195
+ status_message = f"Submission Failed: Network error - {e}"
196
+ print(status_message)
197
+ results_df = pd.DataFrame(results_log)
198
+ return status_message, results_df
199
+ except Exception as e:
200
+ status_message = f"An unexpected error occurred during submission: {e}"
201
+ print(status_message)
202
+ results_df = pd.DataFrame(results_log)
203
+ return status_message, results_df
204
 
205
  # --- Build Gradio Interface using Blocks ---
206
+ with gr.Blocks() as demo:
207
+ gr.Markdown("# Basic Agent Evaluation Runner")
208
  gr.Markdown(
209
  """
210
  **Instructions:**
211
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
212
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
213
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
214
+ ---
215
+ **Disclaimers:**
216
+ 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).
217
+ 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.
218
  """
219
  )
220
 
221
+ gr.LoginButton()
 
222
 
 
 
 
223
  run_button = gr.Button("Run Evaluation & Submit All Answers")
224
+
225
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
226
+ # Removed max_rows=10 from DataFrame constructor
227
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
228
 
 
 
 
 
 
 
 
 
 
 
 
229
  run_button.click(
230
  fn=run_and_submit_all,
 
231
  outputs=[status_output, results_table]
232
  )
233
 
234
  if __name__ == "__main__":
235
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
236
+ # Check for SPACE_HOST and SPACE_ID at startup for information
237
+ space_host_startup = os.getenv("SPACE_HOST")
238
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
239
+
240
+ if space_host_startup:
241
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
242
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
243
+ else:
244
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
245
+
246
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
247
+ print(f"✅ SPACE_ID found: {space_id_startup}")
248
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
249
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
250
+ else:
251
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
252
+
253
+ print("-"*(60 + len(" App Starting ")) + "\n")
254
+
255
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
256
+ demo.launch(debug=True, share=False)