chezhian commited on
Commit
30e2a8d
·
verified ·
1 Parent(s): e430c43
Files changed (1) hide show
  1. app.py +132 -23
app.py CHANGED
@@ -1,54 +1,94 @@
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
- from agent import answer_question
6
 
 
 
7
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
 
9
- def run_and_submit_all(profile: gr.OAuthProfile | None):
10
- if not profile:
11
- return "Please Login to Hugging Face with the button.", None
12
 
13
- username = profile.username
14
- space_id = os.getenv("SPACE_ID", "YOUR_SPACE_ID")
15
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  api_url = DEFAULT_API_URL
18
  questions_url = f"{api_url}/questions"
19
  submit_url = f"{api_url}/submit"
20
 
21
- # Fetch questions
 
 
 
 
 
 
 
 
 
 
 
22
  try:
23
  response = requests.get(questions_url, timeout=15)
24
  response.raise_for_status()
25
  questions_data = response.json()
26
  if not questions_data:
27
- return "Fetched questions list is empty or invalid format.", None
28
- except Exception as e:
 
 
 
29
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
30
 
31
- # Run agent on questions
32
  results_log = []
33
  answers_payload = []
 
34
  for item in questions_data:
35
  task_id = item.get("task_id")
36
  question_text = item.get("question")
37
- if not task_id or not question_text:
 
38
  continue
39
  try:
40
- submitted_answer = answer_question(question_text)
41
- # Remove "FINAL ANSWER: " if not required by API (check course instructions)
42
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
43
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
44
  except Exception as e:
45
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
46
 
47
  if not answers_payload:
 
48
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
49
 
50
- # Submit answers
51
- submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
 
52
  try:
53
  response = requests.post(submit_url, json=submission_data, timeout=60)
54
  response.raise_for_status()
@@ -60,17 +100,86 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
60
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
61
  f"Message: {result_data.get('message', 'No message received.')}"
62
  )
63
- return final_status, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  except Exception as e:
65
- return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
 
66
 
 
67
  with gr.Blocks() as demo:
68
- gr.Markdown("# smolagents GAIA Benchmark Submission")
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  gr.LoginButton()
 
70
  run_button = gr.Button("Run Evaluation & Submit All Answers")
71
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5)
 
 
72
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
73
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
 
74
 
75
  if __name__ == "__main__":
76
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")
26
+ return "Please Login to Hugging Face with the button.", None
27
 
28
  api_url = DEFAULT_API_URL
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
  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)