lmrkmrcs commited on
Commit
a36abbe
ยท
verified ยท
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -40
app.py CHANGED
@@ -1,34 +1,165 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
6
 
7
- # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  class BasicAgent:
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
21
 
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
  Fetches all questions, runs the BasicAgent on them, submits all answers,
25
  and displays the results.
26
  """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -38,13 +169,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
  agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # 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)
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
@@ -55,16 +186,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
61
  except requests.exceptions.RequestException as e:
62
  print(f"Error fetching questions: {e}")
63
  return f"Error fetching questions: {e}", None
64
  except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
  print(f"An unexpected error occurred fetching questions: {e}")
70
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -73,6 +204,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
73
  results_log = []
74
  answers_payload = []
75
  print(f"Running agent on {len(questions_data)} questions...")
 
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
@@ -84,14 +216,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
  print(status_update)
@@ -140,30 +272,38 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
140
  return status_message, results_df
141
 
142
 
143
- # --- Build Gradio Interface using Blocks ---
 
 
 
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
- **Instructions:**
149
-
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
 
 
 
 
154
  ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
 
 
158
  """
159
  )
160
 
161
  gr.LoginButton()
162
 
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
@@ -173,9 +313,8 @@ with gr.Blocks() as demo:
173
 
174
  if __name__ == "__main__":
175
  print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
  print(f"โœ… SPACE_HOST found: {space_host_startup}")
@@ -183,7 +322,7 @@ if __name__ == "__main__":
183
  else:
184
  print("โ„น๏ธ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
  print(f"โœ… SPACE_ID found: {space_id_startup}")
188
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
@@ -192,5 +331,5 @@ if __name__ == "__main__":
192
 
193
  print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
  demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, tool
6
 
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
+ # ============================================
11
+ # CUSTOM TOOLS FOR THE AGENT
12
+ # ============================================
13
+
14
+ @tool
15
+ def calculator(expression: str) -> str:
16
+ """
17
+ Performs mathematical calculations.
18
+
19
+ Args:
20
+ expression: A math expression like "2 + 2" or "10 * 5 / 2"
21
+
22
+ Returns:
23
+ The result of the calculation
24
+ """
25
+ try:
26
+ allowed_chars = set('0123456789+-*/(). ')
27
+ if all(c in allowed_chars for c in expression):
28
+ result = eval(expression)
29
+ return f"{result}"
30
+ else:
31
+ return "Invalid expression. Use only numbers and basic operators."
32
+ except Exception as e:
33
+ return f"Error: {str(e)}"
34
+
35
+
36
+ @tool
37
+ def get_current_time() -> str:
38
+ """
39
+ Gets the current date and time in UTC.
40
+
41
+ Returns:
42
+ The current date and time
43
+ """
44
+ from datetime import datetime
45
+ now = datetime.utcnow()
46
+ return f"Current date and time (UTC): {now.strftime('%Y-%m-%d %H:%M:%S')}"
47
+
48
+
49
+ @tool
50
+ def reverse_text(text: str) -> str:
51
+ """
52
+ Reverses the given text string.
53
+
54
+ Args:
55
+ text: The text to reverse
56
+
57
+ Returns:
58
+ The reversed text
59
+ """
60
+ return text[::-1]
61
+
62
+
63
+ @tool
64
+ def count_words(text: str) -> str:
65
+ """
66
+ Counts the number of words in a text.
67
+
68
+ Args:
69
+ text: The text to count words in
70
+
71
+ Returns:
72
+ The word count
73
+ """
74
+ words = text.split()
75
+ return f"{len(words)}"
76
+
77
+
78
+ @tool
79
+ def string_length(text: str) -> str:
80
+ """
81
+ Returns the length of a string (number of characters).
82
+
83
+ Args:
84
+ text: The text to measure
85
+
86
+ Returns:
87
+ The number of characters
88
+ """
89
+ return f"{len(text)}"
90
+
91
+
92
+ # ============================================
93
+ # BASIC AGENT CLASS - USING SMOLAGENTS
94
+ # ============================================
95
+
96
  class BasicAgent:
97
  def __init__(self):
98
+ print("Initializing BasicAgent with smolagents...")
99
+
100
+ # Initialize the model
101
+ self.model = InferenceClientModel(
102
+ model_id="Qwen/Qwen2.5-7B-Instruct",
103
+ token=os.environ.get("HF_TOKEN"),
104
+ )
105
+
106
+ # Create the agent with tools
107
+ self.agent = CodeAgent(
108
+ model=self.model,
109
+ tools=[
110
+ DuckDuckGoSearchTool(), # Web search
111
+ calculator, # Math calculations
112
+ get_current_time, # Current time
113
+ reverse_text, # Reverse strings
114
+ count_words, # Count words
115
+ string_length, # String length
116
+ ],
117
+ max_steps=6,
118
+ verbosity_level=1,
119
+ )
120
+
121
+ print("BasicAgent initialized successfully!")
122
+
123
  def __call__(self, question: str) -> str:
124
+ print(f"Agent received question: {question[:100]}...")
125
+
126
+ try:
127
+ # Create a prompt that helps the agent understand its task
128
+ enhanced_question = f"""Please answer the following question accurately and concisely.
129
+ If you need to search for information, use the web search tool.
130
+ If you need to do math, use the calculator tool.
131
+ Give only the final answer without explanation unless asked.
132
 
133
+ Question: {question}"""
134
+
135
+ # Run the agent
136
+ answer = self.agent.run(enhanced_question)
137
+
138
+ # Convert to string and clean up
139
+ answer = str(answer).strip()
140
+
141
+ print(f"Agent answer: {answer[:100]}...")
142
+ return answer
143
+
144
+ except Exception as e:
145
+ print(f"Agent error: {e}")
146
+ # Try a simpler approach if the agent fails
147
+ return f"I could not determine the answer. Error: {str(e)}"
148
+
149
+
150
+ # ============================================
151
+ # RUN AND SUBMIT FUNCTION
152
+ # ============================================
153
+
154
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
155
  """
156
  Fetches all questions, runs the BasicAgent on them, submits all answers,
157
  and displays the results.
158
  """
159
+ space_id = os.getenv("SPACE_ID")
 
160
 
161
  if profile:
162
+ username = f"{profile.username}"
163
  print(f"User logged in: {username}")
164
  else:
165
  print("User not logged in.")
 
169
  questions_url = f"{api_url}/questions"
170
  submit_url = f"{api_url}/submit"
171
 
172
+ # 1. Instantiate Agent
173
  try:
174
  agent = BasicAgent()
175
  except Exception as e:
176
  print(f"Error instantiating agent: {e}")
177
  return f"Error initializing agent: {e}", None
178
+
179
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
180
  print(agent_code)
181
 
 
186
  response.raise_for_status()
187
  questions_data = response.json()
188
  if not questions_data:
189
+ print("Fetched questions list is empty.")
190
+ return "Fetched questions list is empty or invalid format.", None
191
  print(f"Fetched {len(questions_data)} questions.")
192
  except requests.exceptions.RequestException as e:
193
  print(f"Error fetching questions: {e}")
194
  return f"Error fetching questions: {e}", None
195
  except requests.exceptions.JSONDecodeError as e:
196
+ print(f"Error decoding JSON response from questions endpoint: {e}")
197
+ print(f"Response text: {response.text[:500]}")
198
+ return f"Error decoding server response for questions: {e}", None
199
  except Exception as e:
200
  print(f"An unexpected error occurred fetching questions: {e}")
201
  return f"An unexpected error occurred fetching questions: {e}", None
 
204
  results_log = []
205
  answers_payload = []
206
  print(f"Running agent on {len(questions_data)} questions...")
207
+
208
  for item in questions_data:
209
  task_id = item.get("task_id")
210
  question_text = item.get("question")
 
216
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
217
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
218
  except Exception as e:
219
+ print(f"Error running agent on task {task_id}: {e}")
220
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
221
 
222
  if not answers_payload:
223
  print("Agent did not produce any answers to submit.")
224
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
225
 
226
+ # 4. Prepare Submission
227
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
228
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
229
  print(status_update)
 
272
  return status_message, results_df
273
 
274
 
275
+ # ============================================
276
+ # GRADIO INTERFACE
277
+ # ============================================
278
+
279
  with gr.Blocks() as demo:
280
+ gr.Markdown("# ๐ŸŽฏ GAIA Agent Evaluation Runner")
281
  gr.Markdown(
282
  """
283
+ **Unit 4 Final Project - HuggingFace AI Agents Course**
284
+
285
+ This agent uses **smolagents** with the following tools:
286
+ - ๐Ÿ” **Web Search** - Search the internet for information
287
+ - ๐Ÿงฎ **Calculator** - Perform mathematical calculations
288
+ - ๐Ÿ• **Current Time** - Get the current date and time
289
+ - ๐Ÿ”„ **Reverse Text** - Reverse strings
290
+ - ๐Ÿ“ **Word Count** - Count words in text
291
+ - ๐Ÿ“ **String Length** - Measure string length
292
+
293
  ---
294
+ **Instructions:**
295
+ 1. Log in to your Hugging Face account using the button below
296
+ 2. Click 'Run Evaluation & Submit All Answers'
297
+ 3. Wait for the agent to process all questions (this may take a few minutes)
298
+ 4. View your score on the leaderboard!
299
  """
300
  )
301
 
302
  gr.LoginButton()
303
 
304
+ run_button = gr.Button("๐Ÿš€ Run Evaluation & Submit All Answers")
305
 
306
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
307
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
308
 
309
  run_button.click(
 
313
 
314
  if __name__ == "__main__":
315
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
316
  space_host_startup = os.getenv("SPACE_HOST")
317
+ space_id_startup = os.getenv("SPACE_ID")
318
 
319
  if space_host_startup:
320
  print(f"โœ… SPACE_HOST found: {space_host_startup}")
 
322
  else:
323
  print("โ„น๏ธ SPACE_HOST environment variable not found (running locally?).")
324
 
325
+ if space_id_startup:
326
  print(f"โœ… SPACE_ID found: {space_id_startup}")
327
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
328
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
331
 
332
  print("-"*(60 + len(" App Starting ")) + "\n")
333
 
334
+ print("Launching Gradio Interface for GAIA Agent Evaluation...")
335
  demo.launch(debug=True, share=False)