JPM34 commited on
Commit
4bb4d29
·
1 Parent(s): 81e21fd

Switched to smolagent Framework

Browse files
Files changed (1) hide show
  1. app.py +144 -254
app.py CHANGED
@@ -1,33 +1,24 @@
1
- import concurrent.futures
2
- import logging
3
  import os
4
- import sys
5
- import traceback
6
-
7
  import gradio as gr
8
- import pandas as pd
9
  import requests
10
- from dotenv import load_dotenv
11
-
12
- # from agent_gemini import BasicAgent
13
- from agent_mistral import BasicAgent
14
- # from agent_openrouter_llama import BasicAgent
15
-
16
- # Load environment variables from .env file
17
- load_dotenv()
18
-
19
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
20
-
21
- # Configure logging
22
- logging.basicConfig(
23
- level=logging.DEBUG,
24
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
25
- handlers=[logging.StreamHandler(sys.stdout)],
26
- )
27
- logger = logging.getLogger(__name__)
28
 
29
  # (Keep Constants as is)
30
  # --- Constants ---
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
 
33
  def run_and_submit_all(profile: gr.OAuthProfile | None):
@@ -35,249 +26,146 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
35
  Fetches all questions, runs the BasicAgent on them, submits all answers,
36
  and displays the results.
37
  """
38
- try:
39
- # --- Determine HF Space Runtime URL and Repo URL ---
40
- space_id = os.getenv(
41
- "SPACE_ID"
42
- ) # Get the SPACE_ID for sending link to the code
43
-
44
- if profile:
45
- username = f"{profile.username}"
46
- logger.info(f"User logged in: {username}")
47
- else:
48
- logger.warning("User not logged in.")
49
- return "Please Login to Hugging Face with the button.", None
50
-
51
- api_url = os.getenv("DEFAULT_API_URL")
52
- questions_url = f"{api_url}/questions"
53
- submit_url = f"{api_url}/submit"
54
-
55
- # 1. Instantiate Agent ( modify this part to create your agent)
56
- try:
57
- logger.info("Instantiating agent...")
58
- agent = BasicAgent()
59
- logger.info("Agent instantiated successfully")
60
- except Exception as e:
61
- logger.error(f"Error instantiating agent: {e}", exc_info=True)
62
- return (
63
- f"Error initializing agent: {str(e)}\n{traceback.format_exc()}",
64
- None,
65
- )
66
 
67
- # In the case of an app running as a hugging Face space, this link points toward your codebase
68
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
69
- logger.info(f"Agent code: {agent_code}")
70
 
71
- # 2. Fetch Questions
72
- logger.info(f"Fetching questions from: {questions_url}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  try:
74
- response = requests.get(questions_url, timeout=15)
75
- response.raise_for_status()
76
- questions_data = response.json()
77
- if not questions_data:
78
- logger.warning("Fetched questions list is empty.")
79
- return (
80
- "Fetched questions list is empty or invalid format.",
81
- None,
82
- )
83
- logger.info(f"Fetched {len(questions_data)} questions.")
84
- except requests.exceptions.RequestException as e:
85
- logger.error(f"Error fetching questions: {e}", exc_info=True)
86
- return f"Error fetching questions: {str(e)}", None
87
- except requests.exceptions.JSONDecodeError as e:
88
- logger.error(
89
- f"Error decoding JSON response from questions endpoint: {e}",
90
- exc_info=True,
91
  )
92
- logger.error(f"Response text: {response.text[:500]}")
93
- return (
94
- f"Error decoding server response for questions: {str(e)}",
95
- None,
 
 
96
  )
97
  except Exception as e:
98
- logger.error(
99
- f"An unexpected error occurred fetching questions: {e}",
100
- exc_info=True,
 
 
 
 
101
  )
102
- return (
103
- f"An unexpected error occurred fetching questions: {str(e)}",
104
- None,
105
- )
106
-
107
- # 3. Run your Agent
108
- results_log = []
109
- answers_payload = []
110
- logger.info(f"Running agent on {len(questions_data)} questions...")
111
-
112
- # Limit the number of questions to process to avoid timeouts
113
- max_questions = 20 # Process only 20 questions at a time
114
-
115
- tasks_to_process = [
116
- # "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3",
117
- # "1f975693-876d-457b-a649-393859e79bf3",
118
- # "840bfca7-4f7b-481a-8794-c560c340185d",
119
- # "7bd855d8-463d-4ed5-93ca-5fe35145f733",
120
- ]
121
-
122
- # questions_to_process = questions_data[:max_questions]
123
-
124
- if tasks_to_process:
125
- questions_to_process = [
126
- x
127
- for x in questions_data
128
- if x.get("task_id") in tasks_to_process
129
- ]
130
- else:
131
- questions_to_process = questions_data[:max_questions]
132
 
133
- logger.info(
134
- f"Processing {len(questions_to_process)} out of {len(questions_data)} questions"
 
 
135
  )
136
 
137
- for item in questions_to_process:
138
- task_id = item.get("task_id")
139
- question_text = item.get("question")
140
- if not task_id or question_text is None:
141
- logger.warning(
142
- f"Skipping item with missing task_id or question: {item}"
143
- )
144
- continue
145
- try:
146
- logger.info(f"Processing task {task_id}: {question_text}")
147
-
148
- # Use concurrent.futures for thread-safe timeout
149
- with concurrent.futures.ThreadPoolExecutor() as executor:
150
- try:
151
- future = executor.submit(agent, question_text, task_id)
152
- try:
153
- submitted_answer = future.result(
154
- timeout=180
155
- ) # 60 second timeout
156
- logger.info(
157
- f"Answer for task {task_id}: {submitted_answer}"
158
- )
159
-
160
- answers_payload.append(
161
- {
162
- "task_id": task_id,
163
- "submitted_answer": submitted_answer,
164
- }
165
- )
166
- results_log.append(
167
- {
168
- "Task ID": task_id,
169
- "Question": question_text,
170
- "Submitted Answer": submitted_answer,
171
- }
172
- )
173
- except concurrent.futures.TimeoutError:
174
- logger.error(f"Timeout processing task {task_id}")
175
- results_log.append(
176
- {
177
- "Task ID": task_id,
178
- "Question": question_text,
179
- "Submitted Answer": "TIMEOUT ERROR: Question processing timed out after 60 seconds",
180
- }
181
- )
182
- finally:
183
- # Clean up temporary directory after processing
184
- try:
185
- import shutil
186
-
187
- # shutil.rmtree(temp_dir) ## TBD
188
- logger.info(
189
- f"Cleaned up temporary directory for task {task_id}"
190
- )
191
- except Exception as e:
192
- logger.error(
193
- f"Error cleaning up temporary directory for task {task_id}: {e}"
194
- )
195
- except Exception as e:
196
- logger.error(
197
- f"Error running agent on task {task_id}: {e}",
198
- exc_info=True,
199
- )
200
- results_log.append(
201
- {
202
- "Task ID": task_id,
203
- "Question": question_text,
204
- "Submitted Answer": f"AGENT ERROR: {str(e)}",
205
- }
206
- )
207
-
208
- if not answers_payload:
209
- logger.warning("Agent did not produce any answers to submit.")
210
- return (
211
- "Agent did not produce any answers to submit.",
212
- pd.DataFrame(results_log),
213
- )
214
-
215
- # 4. Prepare Submission
216
- submission_data = {
217
- "username": username.strip(),
218
- "agent_code": agent_code,
219
- "answers": answers_payload,
220
- }
221
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
222
- logger.info(status_update)
223
-
224
- # 5. Submit
225
- logger.info(
226
- f"Submitting {len(answers_payload)} answers to: {submit_url}"
227
  )
228
  try:
229
- response = requests.post(
230
- submit_url, json=submission_data, timeout=60
231
- )
232
- response.raise_for_status()
233
- result_data = response.json()
234
- final_status = (
235
- f"Submission Successful!\n"
236
- f"User: {result_data.get('username')}\n"
237
- f"Overall Score: {result_data.get('score', 'N/A')}% "
238
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
239
- f"Message: {result_data.get('message', 'No message received.')}"
240
- )
241
- logger.info("Submission successful.")
242
- results_df = pd.DataFrame(results_log)
243
- return final_status, results_df
244
- except requests.exceptions.HTTPError as e:
245
- error_detail = (
246
- f"Server responded with status {e.response.status_code}."
247
  )
248
- try:
249
- error_json = e.response.json()
250
- error_detail += (
251
- f" Detail: {error_json.get('detail', e.response.text)}"
252
- )
253
- except requests.exceptions.JSONDecodeError:
254
- error_detail += f" Response: {e.response.text[:500]}"
255
- status_message = f"Submission Failed: {error_detail}"
256
- logger.error(status_message, exc_info=True)
257
- results_df = pd.DataFrame(results_log)
258
- return status_message, results_df
259
- except requests.exceptions.Timeout:
260
- status_message = "Submission Failed: The request timed out."
261
- logger.error(status_message, exc_info=True)
262
- results_df = pd.DataFrame(results_log)
263
- return status_message, results_df
264
- except requests.exceptions.RequestException as e:
265
- status_message = f"Submission Failed: Network error - {e}"
266
- logger.error(status_message, exc_info=True)
267
- results_df = pd.DataFrame(results_log)
268
- return status_message, results_df
269
- except Exception as e:
270
- status_message = (
271
- f"An unexpected error occurred during submission: {e}"
272
- )
273
- logger.error(status_message, exc_info=True)
274
- results_df = pd.DataFrame(results_log)
275
- return status_message, results_df
276
  except Exception as e:
277
- logger.error(
278
- f"Unhandled exception in run_and_submit_all: {e}", exc_info=True
279
- )
280
- return f"Critical error: {str(e)}\n{traceback.format_exc()}", None
281
 
282
 
283
  # --- Build Gradio Interface using Blocks ---
@@ -286,9 +174,11 @@ with gr.Blocks() as demo:
286
  gr.Markdown(
287
  """
288
  **Instructions:**
 
289
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
290
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
291
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
292
  ---
293
  **Disclaimers:**
294
  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).
@@ -342,4 +232,4 @@ if __name__ == "__main__":
342
  print("-" * (60 + len(" App Starting ")) + "\n")
343
 
344
  print("Launching Gradio Interface for Basic Agent Evaluation...")
345
- 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
+ # --- Basic Agent Definition ---
13
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
+ # class BasicAgent:
15
+ # def __init__(self):
16
+ # print("BasicAgent initialized.")
17
+ # def __call__(self, question: str) -> str:
18
+ # print(f"Agent received question (first 50 chars): {question[:50]}...")
19
+ # fixed_answer = "This is a default answer."
20
+ # print(f"Agent returning fixed answer: {fixed_answer}")
21
+ # return fixed_answer
22
 
23
 
24
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
26
  Fetches all questions, runs the BasicAgent on them, submits all answers,
27
  and displays the results.
28
  """
29
+ # --- Determine HF Space Runtime URL and Repo URL ---
30
+ space_id = os.getenv(
31
+ "SPACE_ID"
32
+ ) # Get the SPACE_ID for sending link to the code
33
+
34
+ if profile:
35
+ username = f"{profile.username}"
36
+ print(f"User logged in: {username}")
37
+ else:
38
+ print("User not logged in.")
39
+ return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ api_url = DEFAULT_API_URL
42
+ questions_url = f"{api_url}/questions"
43
+ submit_url = f"{api_url}/submit"
44
 
45
+ # 1. Instantiate Agent ( modify this part to create your agent)
46
+ try:
47
+ agent = BasicAgent()
48
+ except Exception as e:
49
+ print(f"Error instantiating agent: {e}")
50
+ return f"Error initializing agent: {e}", None
51
+ # 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)
52
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
53
+ print(agent_code)
54
+
55
+ # 2. Fetch Questions
56
+ print(f"Fetching questions from: {questions_url}")
57
+ try:
58
+ response = requests.get(questions_url, timeout=15)
59
+ response.raise_for_status()
60
+ questions_data = response.json()
61
+ if not questions_data:
62
+ print("Fetched questions list is empty.")
63
+ return "Fetched questions list is empty or invalid format.", None
64
+ print(f"Fetched {len(questions_data)} questions.")
65
+ except requests.exceptions.RequestException as e:
66
+ print(f"Error fetching questions: {e}")
67
+ return f"Error fetching questions: {e}", None
68
+ except requests.exceptions.JSONDecodeError as e:
69
+ print(f"Error decoding JSON response from questions endpoint: {e}")
70
+ print(f"Response text: {response.text[:500]}")
71
+ return f"Error decoding server response for questions: {e}", None
72
+ except Exception as e:
73
+ print(f"An unexpected error occurred fetching questions: {e}")
74
+ return f"An unexpected error occurred fetching questions: {e}", None
75
+
76
+ # 3. Run your Agent
77
+ results_log = []
78
+ answers_payload = []
79
+ print(f"Running agent on {len(questions_data)} questions...")
80
+ for item in questions_data:
81
+ task_id = item.get("task_id")
82
+ question_text = item.get("question")
83
+ if not task_id or question_text is None:
84
+ print(f"Skipping item with missing task_id or question: {item}")
85
+ continue
86
  try:
87
+ submitted_answer = agent(question_text)
88
+ answers_payload.append(
89
+ {"task_id": task_id, "submitted_answer": submitted_answer}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
91
+ results_log.append(
92
+ {
93
+ "Task ID": task_id,
94
+ "Question": question_text,
95
+ "Submitted Answer": submitted_answer,
96
+ }
97
  )
98
  except Exception as e:
99
+ print(f"Error running agent on task {task_id}: {e}")
100
+ results_log.append(
101
+ {
102
+ "Task ID": task_id,
103
+ "Question": question_text,
104
+ "Submitted Answer": f"AGENT ERROR: {e}",
105
+ }
106
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
+ if not answers_payload:
109
+ print("Agent did not produce any answers to submit.")
110
+ return "Agent did not produce any answers to submit.", pd.DataFrame(
111
+ results_log
112
  )
113
 
114
+ # 4. Prepare Submission
115
+ submission_data = {
116
+ "username": username.strip(),
117
+ "agent_code": agent_code,
118
+ "answers": answers_payload,
119
+ }
120
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
121
+ print(status_update)
122
+
123
+ # 5. Submit
124
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
125
+ try:
126
+ response = requests.post(submit_url, json=submission_data, timeout=60)
127
+ response.raise_for_status()
128
+ result_data = response.json()
129
+ final_status = (
130
+ f"Submission Successful!\n"
131
+ f"User: {result_data.get('username')}\n"
132
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
133
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
134
+ f"Message: {result_data.get('message', 'No message received.')}"
135
+ )
136
+ print("Submission successful.")
137
+ results_df = pd.DataFrame(results_log)
138
+ return final_status, results_df
139
+ except requests.exceptions.HTTPError as e:
140
+ error_detail = (
141
+ f"Server responded with status {e.response.status_code}."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  )
143
  try:
144
+ error_json = e.response.json()
145
+ error_detail += (
146
+ f" Detail: {error_json.get('detail', e.response.text)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  )
148
+ except requests.exceptions.JSONDecodeError:
149
+ error_detail += f" Response: {e.response.text[:500]}"
150
+ status_message = f"Submission Failed: {error_detail}"
151
+ print(status_message)
152
+ results_df = pd.DataFrame(results_log)
153
+ return status_message, results_df
154
+ except requests.exceptions.Timeout:
155
+ status_message = "Submission Failed: The request timed out."
156
+ print(status_message)
157
+ results_df = pd.DataFrame(results_log)
158
+ return status_message, results_df
159
+ except requests.exceptions.RequestException as e:
160
+ status_message = f"Submission Failed: Network error - {e}"
161
+ print(status_message)
162
+ results_df = pd.DataFrame(results_log)
163
+ return status_message, results_df
 
 
 
 
 
 
 
 
 
 
 
 
164
  except Exception as e:
165
+ status_message = f"An unexpected error occurred during submission: {e}"
166
+ print(status_message)
167
+ results_df = pd.DataFrame(results_log)
168
+ return status_message, results_df
169
 
170
 
171
  # --- Build Gradio Interface using Blocks ---
 
174
  gr.Markdown(
175
  """
176
  **Instructions:**
177
+
178
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
179
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
180
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
181
+
182
  ---
183
  **Disclaimers:**
184
  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).
 
232
  print("-" * (60 + len(" App Starting ")) + "\n")
233
 
234
  print("Launching Gradio Interface for Basic Agent Evaluation...")
235
+ demo.launch(debug=True, share=True)