shsad commited on
Commit
39e0975
·
verified ·
1 Parent(s): 3b0d7a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -249
app.py CHANGED
@@ -4,171 +4,16 @@ import requests
4
  import inspect
5
  import pandas as pd
6
 
7
- # Additional packages
8
- from smolagents import CodeAgent, InferenceClientModel, OpenAIModel
9
 
10
  # (Keep Constants as is)
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
- # Added constants
15
- GAIA_SYSTEM_PROMPT = """You are solving GAIA level 1 questions with extreme precision.
16
 
17
-
18
- CRITICAL RULES:
19
- 1. Return ONLY the final answer - no explanations, no context, no preamble
20
- 2. For numbers: just the number (no units unless explicitly requested)
21
- 3. For strings: just the answer (no articles like "the" or "a")
22
- 4. For lists: format as "item1, item2, item3 (no quotes, no brackets)
23
-
24
- STRATEGY:
25
- - Use web search liberally - search multiple times with different keywords
26
- - Visit actual webpages to get complete information
27
- - Cross-reference multiple sources
28
- - Think step-by-step but output only the final answer
29
- - If you find relevant info but not the complete answer, search again with more specifc terms
30
-
31
- NEVER output:
32
- - "FINAL ANSWER:"
33
- - "The answer is:"
34
- - Explanations or reasoning
35
- - "No information found" (keep searching!)
36
-
37
- Examples of correct outputs:
38
- Question: "How many studio albums?" -> Answer: "7"
39
- Question: "What is the capital?" -> Answer: "Paris"
40
- Question: "List the winners" → Answer: "John, Mary, Bob"
41
- """
42
-
43
- class SmolGaiaAgent:
44
- """
45
- Premium agent optimized for maximum accuracy on GAIA Level 1.
46
- """
47
-
48
- def __init__(self):
49
- print("Initializing Premium SmolGaiaAgent...")
50
-
51
- # Use the most capable model available
52
- # Option 1: Qwen 32B (current - good balance)
53
- self.model = OpenAIModel(
54
- model_id="gpt-4.1",
55
- api_key=os.getenv("OPENAI_API_KEY"),
56
- )
57
-
58
- # MORE STEPS = Better accuracy (but slower)
59
- try:
60
- self.agent = CodeAgent(
61
- tools=[],
62
- add_base_tools=True,
63
- model=self.model,
64
- max_steps=12, # INCREASED from 6 to 12 for thorough reasoning
65
- system_prompt=GAIA_SYSTEM_PROMPT,
66
- )
67
- print("Agent initialized with system_prompt parameter")
68
- self.use_task_prefix = False
69
- except TypeError as e:
70
- print(f"system_prompt not supported, using task prefix: {e}")
71
- self.agent = CodeAgent(
72
- tools=[],
73
- add_base_tools=True,
74
- model=self.model,
75
- max_steps=12,
76
- )
77
- self.use_task_prefix = True
78
-
79
- def __call__(self, question: str) -> str:
80
- """
81
- Runs the CodeAgent on one question with enhanced answer extraction.
82
- """
83
- print(f"[Premium Agent] Question: {question[:80]}...")
84
-
85
- if self.use_task_prefix:
86
- task = f"{GAIA_SYSTEM_PROMPT}\n\nTask: {question}"
87
- else:
88
- task = question
89
-
90
- try:
91
- answer = self.agent.run(task)
92
- answer = str(answer).strip()
93
-
94
- # Enhanced answer cleaning
95
- answer = self.aggressive_clean_answer(answer)
96
-
97
- print(f"[Premium Agent] Final Answer: {answer}")
98
- return answer
99
- except Exception as e:
100
- print(f"[Premium Agent] Error: {e}")
101
- import traceback
102
- traceback.print_exc()
103
- return "Error processing question"
104
-
105
- def aggressive_clean_answer(self, answer: str) -> str:
106
- """
107
- Aggressively clean the answer to extract just the answer.
108
- """
109
- original = answer
110
-
111
- # Remove common prefixes (case insensitive)
112
- prefixes_to_remove = [
113
- "final answer:",
114
- "the final answer is:",
115
- "answer:",
116
- "the answer is:",
117
- "the answer is",
118
- "result:",
119
- "solution:",
120
- "output:",
121
- ]
122
-
123
- answer_lower = answer.lower()
124
- for prefix in prefixes_to_remove:
125
- if answer_lower.startswith(prefix):
126
- answer = answer[len(prefix):].strip()
127
- answer_lower = answer.lower()
128
-
129
- # Remove surrounding quotes
130
- if (answer.startswith('"') and answer.endswith('"')) or \
131
- (answer.startswith("'") and answer.endswith("'")):
132
- answer = answer[1:-1].strip()
133
-
134
- # If answer contains "is:" extract what comes after
135
- if " is:" in answer.lower():
136
- parts = answer.split("is:")
137
- if len(parts) > 1:
138
- answer = parts[-1].strip()
139
-
140
- # If answer contains "are:" extract what comes after
141
- if " are:" in answer.lower():
142
- parts = answer.split("are:")
143
- if len(parts) > 1:
144
- answer = parts[-1].strip()
145
-
146
- # Remove trailing periods (unless it's a decimal number)
147
- if answer.endswith('.') and not answer[-2].isdigit():
148
- answer = answer[:-1].strip()
149
-
150
- # If answer starts with "The " and is followed by a name/noun, remove "The "
151
- if answer.startswith("The ") and len(answer) > 4:
152
- # Check if next word is capitalized (likely a proper noun)
153
- next_word = answer.split()[1] if len(answer.split()) > 1 else ""
154
- if next_word and next_word[0].isupper():
155
- answer = answer[4:].strip()
156
-
157
- # Remove "a " or "an " from the beginning
158
- if answer.lower().startswith("a "):
159
- answer = answer[2:].strip()
160
- elif answer.lower().startswith("an "):
161
- answer = answer[3:].strip()
162
-
163
- print(f"[Cleaning] Original: '{original}' → Cleaned: '{answer}'")
164
- return answer
165
-
166
-
167
-
168
- # Submission logic slightly changed
169
  def run_and_submit_all( profile: gr.OAuthProfile | None):
170
  """
171
- Fetches all questions, runs the Premium Agent, and submits answers.
 
172
  """
173
  # --- Determine HF Space Runtime URL and Repo URL ---
174
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
@@ -184,19 +29,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
184
  questions_url = f"{api_url}/questions"
185
  submit_url = f"{api_url}/submit"
186
 
187
- # 1. Instantiate Agent (modified)
188
- print("\n" + "="*30)
189
- print("INITIALIZING PREMIUM AGENT")
190
- print("="*30)
191
  try:
192
- agent = SmolGaiaAgent()
193
  except Exception as e:
194
  print(f"Error instantiating agent: {e}")
195
- import traceback
196
- traceback.print_exc()
197
  return f"Error initializing agent: {e}", None
198
-
199
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
200
 
201
  # 2. Fetch Questions
202
  print(f"Fetching questions from: {questions_url}")
@@ -219,117 +60,100 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
219
  print(f"An unexpected error occurred fetching questions: {e}")
220
  return f"An unexpected error occurred fetching questions: {e}", None
221
 
222
- # 3. Run Agent with detailed progress tracking
223
  results_log = []
224
  answers_payload = []
225
- total = len(questions_data)
226
-
227
- print("\n" + "="*30)
228
- print(f"PROCESSING {total} QUESTIONS")
229
- print("="*30 + "\n")
230
-
231
- for idx, item in enumerate(questions_data, 1):
232
  task_id = item.get("task_id")
233
  question_text = item.get("question")
234
-
235
  if not task_id or question_text is None:
236
- print(f"⚠ Skipping item with missing task_id or question")
237
  continue
238
-
239
- print(f"\n{'='*30}")
240
- print(f"QUESTION {idx}/{total}")
241
- print(f"Task ID: {task_id}")
242
- print(f"Question: {question_text[:100]}...")
243
- print('='*30)
244
-
245
  try:
246
  submitted_answer = agent(question_text)
247
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
248
- results_log.append({
249
- "Task ID": task_id,
250
- "Question": question_text,
251
- "Submitted Answer": submitted_answer
252
- })
253
- print(f"✓ Answer recorded: {submitted_answer}")
254
  except Exception as e:
255
- print(f"✗ Error processing question: {e}")
256
- import traceback
257
- traceback.print_exc()
258
- results_log.append({
259
- "Task ID": task_id,
260
- "Question": question_text,
261
- "Submitted Answer": f"AGENT ERROR: {e}"
262
- })
263
 
264
  if not answers_payload:
 
265
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
266
 
267
-
 
 
 
268
 
269
 
270
- # 5. Submission
271
- submission_data = {
272
- "username": username.strip(),
273
- "agent_code": agent_code,
274
- "answers": answers_payload
275
- }
276
-
277
- print("\n" + "="*30)
278
- print(f"SUBMITTING {len(answers_payload)} ANSWERS")
279
- print("="*30)
280
-
281
  try:
282
  response = requests.post(submit_url, json=submission_data, timeout=60)
283
  response.raise_for_status()
284
  result_data = response.json()
285
-
286
- score = result_data.get('score', 'N/A')
287
- correct = result_data.get('correct_count', '?')
288
- total_attempted = result_data.get('total_attempted', '?')
289
-
290
  final_status = (
291
  f"Submission Successful!\n"
292
  f"User: {result_data.get('username')}\n"
293
- f"Overall Score: {score}% ({correct}/{total_attempted} correct)\n"
294
- f"Message: {result_data.get('message', 'No message received.')}\n\n"
295
- f"{'EXCELLENT!' if float(score) >= 80 else 'Good job!' if float(score) >= 50 else 'Keep improving!'}"
296
  )
297
- print(f"\n✓ Submission successful! Score: {score}%")
298
  results_df = pd.DataFrame(results_log)
299
  return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  except Exception as e:
301
- print(f"✗ Submission error: {e}")
 
302
  results_df = pd.DataFrame(results_log)
303
- return f"Submission Failed: {e}", results_df
304
 
305
 
306
  # --- Build Gradio Interface using Blocks ---
307
  with gr.Blocks() as demo:
308
- gr.Markdown("# Premium Agent - Optimized for Maximum Accuracy")
309
  gr.Markdown(
310
  """
311
- **Current Configuration:**
312
- - Model: Qwen/Qwen2.5-Coder-32B-Instruct (most capable)
313
- - Max Steps: 12 (thorough reasoning)
314
- - Enhanced answer cleaning
315
- - Detailed progress logging
316
-
317
- **Target Performance:**
318
- - Time: ~20-25 minutes for 20 questions
319
- - Target Score: 60-80% (realistic for Level 1)
320
- - Stretch Goal: 80%+ with optimal configuration
321
-
322
- **To Reach 100%:**
323
- Getting 100% on GAIA Level 1 is extremely difficult. The benchmark shows:
324
- - GPT-4 achieves ~70-80%
325
- - Claude 3.5 achieves ~75-85%
326
- - Human experts achieve ~90-95%
327
  """
328
  )
329
 
330
  gr.LoginButton()
331
- run_button = gr.Button("Run Premium Evaluation & Submit")
332
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=7, interactive=False)
 
 
 
333
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
334
 
335
  run_button.click(
@@ -339,17 +163,25 @@ with gr.Blocks() as demo:
339
 
340
 
341
  if __name__ == "__main__":
342
- print("\n" + "="*30)
343
- print("PREMIUM AGENT STARTING")
344
- print("="*30)
345
-
346
- space_host = os.getenv("SPACE_HOST")
347
- space_id = os.getenv("SPACE_ID")
 
 
 
 
 
 
 
 
 
 
 
348
 
349
- if space_host:
350
- print(f"✓ Runtime URL: https://{space_host}.hf.space")
351
- if space_id:
352
- print(f"✓ Repo URL: https://huggingface.co/spaces/{space_id}/tree/main")
353
 
354
- print("="*30 + "\n")
355
  demo.launch(debug=True, share=False)
 
4
  import inspect
5
  import pandas as pd
6
 
 
 
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
 
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}")
 
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
 
91
+ # 5. Submit
92
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
 
 
 
 
 
 
 
 
93
  try:
94
  response = requests.post(submit_url, json=submission_data, timeout=60)
95
  response.raise_for_status()
96
  result_data = response.json()
 
 
 
 
 
97
  final_status = (
98
  f"Submission Successful!\n"
99
  f"User: {result_data.get('username')}\n"
100
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
101
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
102
+ f"Message: {result_data.get('message', 'No message received.')}"
103
  )
104
+ print("Submission successful.")
105
  results_df = pd.DataFrame(results_log)
106
  return final_status, results_df
107
+ except requests.exceptions.HTTPError as e:
108
+ error_detail = f"Server responded with status {e.response.status_code}."
109
+ try:
110
+ error_json = e.response.json()
111
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
112
+ except requests.exceptions.JSONDecodeError:
113
+ error_detail += f" Response: {e.response.text[:500]}"
114
+ status_message = f"Submission Failed: {error_detail}"
115
+ print(status_message)
116
+ results_df = pd.DataFrame(results_log)
117
+ return status_message, results_df
118
+ except requests.exceptions.Timeout:
119
+ status_message = "Submission Failed: The request timed out."
120
+ print(status_message)
121
+ results_df = pd.DataFrame(results_log)
122
+ return status_message, results_df
123
+ except requests.exceptions.RequestException as e:
124
+ status_message = f"Submission Failed: Network error - {e}"
125
+ print(status_message)
126
+ results_df = pd.DataFrame(results_log)
127
+ return status_message, results_df
128
  except Exception as e:
129
+ status_message = f"An unexpected error occurred during submission: {e}"
130
+ print(status_message)
131
  results_df = pd.DataFrame(results_log)
132
+ return status_message, results_df
133
 
134
 
135
  # --- Build Gradio Interface using Blocks ---
136
  with gr.Blocks() as demo:
137
+ gr.Markdown("# Basic Agent Evaluation Runner")
138
  gr.Markdown(
139
  """
140
+ **Instructions:**
141
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
142
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
143
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
144
+ ---
145
+ **Disclaimers:**
146
+ 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).
147
+ 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.
 
 
 
 
 
 
 
 
148
  """
149
  )
150
 
151
  gr.LoginButton()
152
+
153
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
154
+
155
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
156
+ # Removed max_rows=10 from DataFrame constructor
157
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
158
 
159
  run_button.click(
 
163
 
164
 
165
  if __name__ == "__main__":
166
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
167
+ # Check for SPACE_HOST and SPACE_ID at startup for information
168
+ space_host_startup = os.getenv("SPACE_HOST")
169
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
170
+
171
+ if space_host_startup:
172
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
173
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
174
+ else:
175
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
176
+
177
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
178
+ print(f"✅ SPACE_ID found: {space_id_startup}")
179
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
180
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
181
+ else:
182
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
183
 
184
+ print("-"*(60 + len(" App Starting ")) + "\n")
 
 
 
185
 
186
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
187
  demo.launch(debug=True, share=False)