Shivangsinha commited on
Commit
12c29d2
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -28
app.py CHANGED
@@ -3,21 +3,59 @@ 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
  """
@@ -55,16 +93,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
@@ -84,14 +122,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)
@@ -145,17 +183,17 @@ 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()
@@ -172,25 +210,25 @@ with gr.Blocks() as demo:
172
  )
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}")
182
  print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
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")
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
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)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from smolagents import (
7
+ CodeAgent,
8
+ HfApiModel,
9
+ DuckDuckGoSearchTool,
10
+ WikipediaSearchTool,
11
+ PythonInterpreterTool,
12
+ tool,
13
+ )
14
 
15
  # (Keep Constants as is)
16
  # --- Constants ---
17
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
 
19
  # --- Basic Agent Definition ---
20
+ # --- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
21
+
22
+ @tool
23
+ def get_current_date_time() -> str:
24
+ """Returns the current date and time in ISO format."""
25
+ from datetime import datetime
26
+ return datetime.now().isoformat()
27
+
28
+
29
  class BasicAgent:
30
  def __init__(self):
31
  print("BasicAgent initialized.")
32
+ model = HfApiModel(
33
+ model_id="Qwen/Qwen2.5-72B-Instruct",
34
+ )
35
+ tools = [
36
+ DuckDuckGoSearchTool(),
37
+ WikipediaSearchTool(),
38
+ PythonInterpreterTool(),
39
+ get_current_date_time,
40
+ ]
41
+ self.agent = CodeAgent(
42
+ tools=tools,
43
+ model=model,
44
+ max_steps=10,
45
+ additional_authorized_imports=["math", "datetime", "re", "json", "collections", "itertools", "statistics"],
46
+ )
47
+
48
  def __call__(self, question: str) -> str:
49
  print(f"Agent received question (first 50 chars): {question[:50]}...")
50
+ try:
51
+ answer = self.agent.run(question)
52
+ final_answer = str(answer)
53
+ except Exception as e:
54
+ print(f"Agent error: {e}")
55
+ final_answer = f"Error: {e}"
56
+ print(f"Agent returning answer: {final_answer}")
57
+ return final_answer
58
+
59
 
60
  def run_and_submit_all( profile: gr.OAuthProfile | None):
61
  """
 
93
  response.raise_for_status()
94
  questions_data = response.json()
95
  if not questions_data:
96
+ print("Fetched questions list is empty.")
97
+ return "Fetched questions list is empty or invalid format.", None
98
  print(f"Fetched {len(questions_data)} questions.")
99
  except requests.exceptions.RequestException as e:
100
  print(f"Error fetching questions: {e}")
101
  return f"Error fetching questions: {e}", None
102
  except requests.exceptions.JSONDecodeError as e:
103
+ print(f"Error decoding JSON response from questions endpoint: {e}")
104
+ print(f"Response text: {response.text[:500]}")
105
+ return f"Error decoding server response for questions: {e}", None
106
  except Exception as e:
107
  print(f"An unexpected error occurred fetching questions: {e}")
108
  return f"An unexpected error occurred fetching questions: {e}", None
 
122
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
123
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
124
  except Exception as e:
125
+ print(f"Error running agent on task {task_id}: {e}")
126
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
127
 
128
  if not answers_payload:
129
  print("Agent did not produce any answers to submit.")
130
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
131
 
132
+ # 4. Prepare Submission
133
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
134
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
135
  print(status_update)
 
183
  gr.Markdown("# Basic Agent Evaluation Runner")
184
  gr.Markdown(
185
  """
186
+ **Instructions:**
187
 
188
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
189
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
190
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
191
 
192
+ ---
193
+ **Disclaimers:**
194
+ 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).
195
+ 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.
196
+ """
197
  )
198
 
199
  gr.LoginButton()
 
210
  )
211
 
212
  if __name__ == "__main__":
213
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
214
  # Check for SPACE_HOST and SPACE_ID at startup for information
215
  space_host_startup = os.getenv("SPACE_HOST")
216
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
217
 
218
  if space_host_startup:
219
  print(f"✅ SPACE_HOST found: {space_host_startup}")
220
  print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
221
  else:
222
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
223
 
224
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
225
  print(f"✅ SPACE_ID found: {space_id_startup}")
226
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
227
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
228
  else:
229
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
230
 
231
+ print("-" * (60 + len(" App Starting ")) + "\n")
232
 
233
  print("Launching Gradio Interface for Basic Agent Evaluation...")
234
+ demo.launch(debug=True, share=False)