JorgeVanco commited on
Commit
679c3aa
·
1 Parent(s): a9860b4

Async changes

Browse files
Files changed (1) hide show
  1. app.py +72 -37
app.py CHANGED
@@ -4,34 +4,42 @@ import requests
4
  import inspect
5
  import pandas as pd
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
 
 
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
  self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
17
- print("BasicAgent initialized.")
18
-
19
- def __call__(self, question: str) -> str:
20
- print(f"Agent received question (first 50 chars): {question[:50]}...")
21
- answer = self.agent.run(question)
22
- print(f"Agent returning fixed answer: {answer}")
23
- return answer
24
-
25
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
26
  """
27
  Fetches all questions, runs the BasicAgent on them, submits all answers,
28
  and displays the results.
29
  """
30
  # --- Determine HF Space Runtime URL and Repo URL ---
31
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
32
 
33
  if profile:
34
- username= f"{profile.username}"
35
  print(f"User logged in: {username}")
36
  else:
37
  print("User not logged in.")
@@ -58,16 +66,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
58
  response.raise_for_status()
59
  questions_data = response.json()
60
  if not questions_data:
61
- print("Fetched questions list is empty.")
62
- return "Fetched questions list is empty or invalid format.", None
63
  print(f"Fetched {len(questions_data)} questions.")
64
  except requests.exceptions.RequestException as e:
65
  print(f"Error fetching questions: {e}")
66
  return f"Error fetching questions: {e}", None
67
  except requests.exceptions.JSONDecodeError as e:
68
- print(f"Error decoding JSON response from questions endpoint: {e}")
69
- print(f"Response text: {response.text[:500]}")
70
- return f"Error decoding server response for questions: {e}", None
71
  except Exception as e:
72
  print(f"An unexpected error occurred fetching questions: {e}")
73
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -76,26 +84,50 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
76
  results_log = []
77
  answers_payload = []
78
  print(f"Running agent on {len(questions_data)} questions...")
79
- for item in questions_data:
 
80
  task_id = item.get("task_id")
81
  question_text = item.get("question")
82
  if not task_id or question_text is None:
83
  print(f"Skipping item with missing task_id or question: {item}")
84
- continue
 
 
 
 
85
  try:
86
- submitted_answer = agent(question_text)
87
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
89
  except Exception as e:
90
- print(f"Error running agent on task {task_id}: {e}")
91
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  if not answers_payload:
94
  print("Agent did not produce any answers to submit.")
95
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
96
 
97
- # 4. Prepare Submission
98
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
99
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
100
  print(status_update)
101
 
@@ -165,20 +197,19 @@ with gr.Blocks() as demo:
165
 
166
  run_button = gr.Button("Run Evaluation & Submit All Answers")
167
 
168
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
 
169
  # Removed max_rows=10 from DataFrame constructor
170
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
171
 
172
- run_button.click(
173
- fn=run_and_submit_all,
174
- outputs=[status_output, results_table]
175
- )
176
 
177
  if __name__ == "__main__":
178
- print("\n" + "-"*30 + " App Starting " + "-"*30)
179
  # Check for SPACE_HOST and SPACE_ID at startup for information
180
  space_host_startup = os.getenv("SPACE_HOST")
181
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
182
 
183
  if space_host_startup:
184
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -186,14 +217,18 @@ if __name__ == "__main__":
186
  else:
187
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
188
 
189
- if space_id_startup: # Print repo URLs if SPACE_ID is found
190
  print(f"✅ SPACE_ID found: {space_id_startup}")
191
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
192
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
193
  else:
194
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
195
 
196
- print("-"*(60 + len(" App Starting ")) + "\n")
197
 
198
  print("Launching Gradio Interface for Basic Agent Evaluation...")
199
- demo.launch(debug=True, share=False)
 
4
  import inspect
5
  import pandas as pd
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
7
+ import asyncio
8
+ from concurrent.futures import ThreadPoolExecutor
9
 
10
  # (Keep Constants as is)
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
+
15
  # --- Basic Agent Definition ---
16
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
17
+
18
+
19
  class BasicAgent:
20
  def __init__(self):
21
  self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
22
+ self.executor = ThreadPoolExecutor()
23
+
24
+ async def __call__(self, question: str) -> str:
25
+ loop = asyncio.get_event_loop()
26
+ return await loop.run_in_executor(self.executor, self.agent.run, question)
27
+
28
+
29
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
30
+ return asyncio.run(_run_and_submit_all_async(profile))
31
+
32
+
33
+ async def _run_and_submit_all_async(profile: gr.OAuthProfile | None):
34
  """
35
  Fetches all questions, runs the BasicAgent on them, submits all answers,
36
  and displays the results.
37
  """
38
  # --- Determine HF Space Runtime URL and Repo URL ---
39
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
40
 
41
  if profile:
42
+ username = f"{profile.username}"
43
  print(f"User logged in: {username}")
44
  else:
45
  print("User not logged in.")
 
66
  response.raise_for_status()
67
  questions_data = response.json()
68
  if not questions_data:
69
+ print("Fetched questions list is empty.")
70
+ return "Fetched questions list is empty or invalid format.", None
71
  print(f"Fetched {len(questions_data)} questions.")
72
  except requests.exceptions.RequestException as e:
73
  print(f"Error fetching questions: {e}")
74
  return f"Error fetching questions: {e}", None
75
  except requests.exceptions.JSONDecodeError as e:
76
+ print(f"Error decoding JSON response from questions endpoint: {e}")
77
+ print(f"Response text: {response.text[:500]}")
78
+ return f"Error decoding server response for questions: {e}", None
79
  except Exception as e:
80
  print(f"An unexpected error occurred fetching questions: {e}")
81
  return f"An unexpected error occurred fetching questions: {e}", None
 
84
  results_log = []
85
  answers_payload = []
86
  print(f"Running agent on {len(questions_data)} questions...")
87
+
88
+ async def run_agent_task(item):
89
  task_id = item.get("task_id")
90
  question_text = item.get("question")
91
  if not task_id or question_text is None:
92
  print(f"Skipping item with missing task_id or question: {item}")
93
+ return {
94
+ "Task ID": task_id,
95
+ "Question": question_text,
96
+ "Submitted Answer": "INVALID INPUT",
97
+ }, None
98
  try:
99
+ submitted_answer = await agent(question_text)
100
+ return {
101
+ "Task ID": task_id,
102
+ "Question": question_text,
103
+ "Submitted Answer": submitted_answer,
104
+ }, {"task_id": task_id, "submitted_answer": submitted_answer}
105
  except Exception as e:
106
+ print(f"Error running agent on task {task_id}: {e}")
107
+ return {
108
+ "Task ID": task_id,
109
+ "Question": question_text,
110
+ "Submitted Answer": f"AGENT ERROR: {e}",
111
+ }, None
112
+
113
+ tasks = [run_agent_task(item) for item in questions_data]
114
+ results = await asyncio.gather(*tasks)
115
+
116
+ for result_log, answer in results:
117
+ results_log.append(result_log)
118
+ if answer:
119
+ answers_payload.append(answer)
120
 
121
  if not answers_payload:
122
  print("Agent did not produce any answers to submit.")
123
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
124
 
125
+ # 4. Prepare Submission
126
+ submission_data = {
127
+ "username": username.strip(),
128
+ "agent_code": agent_code,
129
+ "answers": answers_payload,
130
+ }
131
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
132
  print(status_update)
133
 
 
197
 
198
  run_button = gr.Button("Run Evaluation & Submit All Answers")
199
 
200
+ status_output = gr.Textbox(
201
+ label="Run Status / Submission Result", lines=5, interactive=False
202
+ )
203
  # Removed max_rows=10 from DataFrame constructor
204
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
205
 
206
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
207
 
208
  if __name__ == "__main__":
209
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
210
  # Check for SPACE_HOST and SPACE_ID at startup for information
211
  space_host_startup = os.getenv("SPACE_HOST")
212
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
213
 
214
  if space_host_startup:
215
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
217
  else:
218
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
219
 
220
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
221
  print(f"✅ SPACE_ID found: {space_id_startup}")
222
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
223
+ print(
224
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
225
+ )
226
  else:
227
+ print(
228
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
229
+ )
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)