Alfred828 commited on
Commit
8b27cad
·
verified ·
1 Parent(s): 7672dcd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -36
app.py CHANGED
@@ -1,34 +1,45 @@
 
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.")
@@ -55,16 +66,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,26 +84,67 @@ 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")
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  try:
83
- submitted_answer = agent(question_text)
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)
98
 
@@ -146,11 +198,9 @@ with gr.Blocks() as demo:
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).
@@ -162,20 +212,19 @@ with gr.Blocks() as demo:
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(
170
- fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
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}")
@@ -183,14 +232,18 @@ 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")
 
 
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)
 
1
+ import asyncio
2
  import os
3
+
4
  import gradio as gr
 
 
5
  import pandas as pd
6
+ import requests
7
+
8
+ from agents.common_agent import AgenticRAG
9
+ from config import settings
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
+
16
  # --- Basic Agent Definition ---
17
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
  class BasicAgent:
19
  def __init__(self):
20
  print("BasicAgent initialized.")
21
+ self.agent = AgenticRAG()
22
+
23
+ async def __call__(self, question: str) -> str:
24
+ # print(f"Agent received question (first 50 chars): {question[:50]}...")
25
+ print(f"Agent received question: {question}")
26
+
27
+ answer = await self.agent.ainvoke(question)
28
 
29
+ print(f"Agent returning answer: {answer}")
30
+ return answer
31
+
32
+
33
+ async def run_and_submit_all(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
+ print(len(questions_data))
88
+ tasks = [[]]
89
+ task_index = 0
90
  for item in questions_data:
91
  task_id = item.get("task_id")
92
  question_text = item.get("question")
93
  if not task_id or question_text is None:
94
  print(f"Skipping item with missing task_id or question: {item}")
95
  continue
96
+
97
+ tasks[task_index].append(agent(question_text))
98
+ if len(tasks[task_index]) >= 10:
99
+ task_index += 1
100
+ tasks.append([])
101
+
102
+ task_results = []
103
+ for task in tasks:
104
+ task_result = await asyncio.gather(*task)
105
+
106
+ task_results.extend(task_result)
107
+
108
+ for index, item in enumerate(questions_data):
109
+ task_id = item.get("task_id")
110
+ question_text = item.get("question")
111
+
112
+ if not task_id or question_text is None:
113
+ print(f"Skipping item with missing task_id or question: {item}")
114
+ continue
115
+
116
  try:
117
+ submitted_answer = task_results[index]
118
+ answers_payload.append(
119
+ {"task_id": task_id, "submitted_answer": submitted_answer}
120
+ )
121
+ results_log.append(
122
+ {
123
+ "Task ID": task_id,
124
+ "Question": question_text,
125
+ "Submitted Answer": submitted_answer,
126
+ }
127
+ )
128
  except Exception as e:
129
+ print(f"Error running agent on task {task_id}: {e}")
130
+ results_log.append(
131
+ {
132
+ "Task ID": task_id,
133
+ "Question": question_text,
134
+ "Submitted Answer": f"AGENT ERROR: {e}",
135
+ }
136
+ )
137
 
138
  if not answers_payload:
139
  print("Agent did not produce any answers to submit.")
140
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
141
 
142
+ # 4. Prepare Submission
143
+ submission_data = {
144
+ "username": username.strip(),
145
+ "agent_code": agent_code,
146
+ "answers": answers_payload,
147
+ }
148
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
149
  print(status_update)
150
 
 
198
  gr.Markdown(
199
  """
200
  **Instructions:**
 
201
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
202
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
203
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
204
  ---
205
  **Disclaimers:**
206
  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).
 
212
 
213
  run_button = gr.Button("Run Evaluation & Submit All Answers")
214
 
215
+ status_output = gr.Textbox(
216
+ label="Run Status / Submission Result", lines=5, interactive=False
217
+ )
218
  # Removed max_rows=10 from DataFrame constructor
219
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
220
 
221
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
222
 
223
  if __name__ == "__main__":
224
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
225
  # Check for SPACE_HOST and SPACE_ID at startup for information
226
  space_host_startup = os.getenv("SPACE_HOST")
227
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
228
 
229
  if space_host_startup:
230
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
232
  else:
233
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
234
 
235
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
236
  print(f"✅ SPACE_ID found: {space_id_startup}")
237
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
238
+ print(
239
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
240
+ )
241
  else:
242
+ print(
243
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
244
+ )
245
 
246
+ print("-" * (60 + len(" App Starting ")) + "\n")
247
 
248
  print("Launching Gradio Interface for Basic Agent Evaluation...")
249
+ demo.launch(debug=True, share=False)