Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,8 +1,10 @@
|
|
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 ---
|
@@ -13,11 +15,15 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
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 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
21 |
|
22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
23 |
"""
|
@@ -46,7 +52,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
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 |
|
51 |
# 2. Fetch Questions
|
52 |
print(f"Fetching questions from: {questions_url}")
|
@@ -193,4 +199,203 @@ if __name__ == "__main__":
|
|
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 inspect
|
3 |
import gradio as gr
|
4 |
import requests
|
|
|
5 |
import pandas as pd
|
6 |
+
from langchain_core.messages import HumanMessage
|
7 |
+
from agent import build_graph
|
8 |
|
9 |
# (Keep Constants as is)
|
10 |
# --- Constants ---
|
|
|
15 |
class BasicAgent:
|
16 |
def __init__(self):
|
17 |
print("BasicAgent initialized.")
|
18 |
+
self.graph = build_graph()
|
19 |
def __call__(self, question: str) -> str:
|
20 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
21 |
+
# Wrap the question in a HumanMessage from langchain_core
|
22 |
+
messages = [HumanMessage(content=question)]
|
23 |
+
messages = self.graph.invoke({"messages": messages})
|
24 |
+
answer = messages['messages'][-1].content
|
25 |
+
return answer[14:]
|
26 |
+
|
27 |
|
28 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
29 |
"""
|
|
|
52 |
return f"Error initializing agent: {e}", None
|
53 |
# 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)
|
54 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
55 |
+
print(f"agent_code: {agent_code}")
|
56 |
|
57 |
# 2. Fetch Questions
|
58 |
print(f"Fetching questions from: {questions_url}")
|
|
|
199 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
200 |
|
201 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
202 |
+
demo.launch(debug=True, share=False)
|
203 |
+
|
204 |
+
|
205 |
+
|
206 |
+
# import os
|
207 |
+
# import gradio as gr
|
208 |
+
# import requests
|
209 |
+
# import inspect
|
210 |
+
# import pandas as pd
|
211 |
+
|
212 |
+
# # (Keep Constants as is)
|
213 |
+
# # --- Constants ---
|
214 |
+
# DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
215 |
+
|
216 |
+
# # --- Basic Agent Definition ---
|
217 |
+
# # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
218 |
+
# class BasicAgent:
|
219 |
+
# def __init__(self):
|
220 |
+
# print("BasicAgent initialized.")
|
221 |
+
# def __call__(self, question: str) -> str:
|
222 |
+
# print(f"Agent received question (first 50 chars): {question[:50]}...")
|
223 |
+
# fixed_answer = "This is a default answer."
|
224 |
+
# print(f"Agent returning fixed answer: {fixed_answer}")
|
225 |
+
# return fixed_answer
|
226 |
+
|
227 |
+
# def run_and_submit_all( profile: gr.OAuthProfile | None):
|
228 |
+
# """
|
229 |
+
# Fetches all questions, runs the BasicAgent on them, submits all answers,
|
230 |
+
# and displays the results.
|
231 |
+
# """
|
232 |
+
# # --- Determine HF Space Runtime URL and Repo URL ---
|
233 |
+
# space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
234 |
+
|
235 |
+
# if profile:
|
236 |
+
# username= f"{profile.username}"
|
237 |
+
# print(f"User logged in: {username}")
|
238 |
+
# else:
|
239 |
+
# print("User not logged in.")
|
240 |
+
# return "Please Login to Hugging Face with the button.", None
|
241 |
+
|
242 |
+
# api_url = DEFAULT_API_URL
|
243 |
+
# questions_url = f"{api_url}/questions"
|
244 |
+
# submit_url = f"{api_url}/submit"
|
245 |
+
|
246 |
+
# # 1. Instantiate Agent ( modify this part to create your agent)
|
247 |
+
# try:
|
248 |
+
# agent = BasicAgent()
|
249 |
+
# except Exception as e:
|
250 |
+
# print(f"Error instantiating agent: {e}")
|
251 |
+
# return f"Error initializing agent: {e}", None
|
252 |
+
# # 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)
|
253 |
+
# agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
254 |
+
# print(agent_code)
|
255 |
+
|
256 |
+
# # 2. Fetch Questions
|
257 |
+
# print(f"Fetching questions from: {questions_url}")
|
258 |
+
# try:
|
259 |
+
# response = requests.get(questions_url, timeout=15)
|
260 |
+
# response.raise_for_status()
|
261 |
+
# questions_data = response.json()
|
262 |
+
# if not questions_data:
|
263 |
+
# print("Fetched questions list is empty.")
|
264 |
+
# return "Fetched questions list is empty or invalid format.", None
|
265 |
+
# print(f"Fetched {len(questions_data)} questions.")
|
266 |
+
# except requests.exceptions.RequestException as e:
|
267 |
+
# print(f"Error fetching questions: {e}")
|
268 |
+
# return f"Error fetching questions: {e}", None
|
269 |
+
# except requests.exceptions.JSONDecodeError as e:
|
270 |
+
# print(f"Error decoding JSON response from questions endpoint: {e}")
|
271 |
+
# print(f"Response text: {response.text[:500]}")
|
272 |
+
# return f"Error decoding server response for questions: {e}", None
|
273 |
+
# except Exception as e:
|
274 |
+
# print(f"An unexpected error occurred fetching questions: {e}")
|
275 |
+
# return f"An unexpected error occurred fetching questions: {e}", None
|
276 |
+
|
277 |
+
# # 3. Run your Agent
|
278 |
+
# results_log = []
|
279 |
+
# answers_payload = []
|
280 |
+
# print(f"Running agent on {len(questions_data)} questions...")
|
281 |
+
# for item in questions_data:
|
282 |
+
# task_id = item.get("task_id")
|
283 |
+
# question_text = item.get("question")
|
284 |
+
# if not task_id or question_text is None:
|
285 |
+
# print(f"Skipping item with missing task_id or question: {item}")
|
286 |
+
# continue
|
287 |
+
# try:
|
288 |
+
# submitted_answer = agent(question_text)
|
289 |
+
# answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
290 |
+
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
291 |
+
# except Exception as e:
|
292 |
+
# print(f"Error running agent on task {task_id}: {e}")
|
293 |
+
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
294 |
+
|
295 |
+
# if not answers_payload:
|
296 |
+
# print("Agent did not produce any answers to submit.")
|
297 |
+
# return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
298 |
+
|
299 |
+
# # 4. Prepare Submission
|
300 |
+
# submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
301 |
+
# status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
302 |
+
# print(status_update)
|
303 |
+
|
304 |
+
# # 5. Submit
|
305 |
+
# print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
306 |
+
# try:
|
307 |
+
# response = requests.post(submit_url, json=submission_data, timeout=60)
|
308 |
+
# response.raise_for_status()
|
309 |
+
# result_data = response.json()
|
310 |
+
# final_status = (
|
311 |
+
# f"Submission Successful!\n"
|
312 |
+
# f"User: {result_data.get('username')}\n"
|
313 |
+
# f"Overall Score: {result_data.get('score', 'N/A')}% "
|
314 |
+
# f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
315 |
+
# f"Message: {result_data.get('message', 'No message received.')}"
|
316 |
+
# )
|
317 |
+
# print("Submission successful.")
|
318 |
+
# results_df = pd.DataFrame(results_log)
|
319 |
+
# return final_status, results_df
|
320 |
+
# except requests.exceptions.HTTPError as e:
|
321 |
+
# error_detail = f"Server responded with status {e.response.status_code}."
|
322 |
+
# try:
|
323 |
+
# error_json = e.response.json()
|
324 |
+
# error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
325 |
+
# except requests.exceptions.JSONDecodeError:
|
326 |
+
# error_detail += f" Response: {e.response.text[:500]}"
|
327 |
+
# status_message = f"Submission Failed: {error_detail}"
|
328 |
+
# print(status_message)
|
329 |
+
# results_df = pd.DataFrame(results_log)
|
330 |
+
# return status_message, results_df
|
331 |
+
# except requests.exceptions.Timeout:
|
332 |
+
# status_message = "Submission Failed: The request timed out."
|
333 |
+
# print(status_message)
|
334 |
+
# results_df = pd.DataFrame(results_log)
|
335 |
+
# return status_message, results_df
|
336 |
+
# except requests.exceptions.RequestException as e:
|
337 |
+
# status_message = f"Submission Failed: Network error - {e}"
|
338 |
+
# print(status_message)
|
339 |
+
# results_df = pd.DataFrame(results_log)
|
340 |
+
# return status_message, results_df
|
341 |
+
# except Exception as e:
|
342 |
+
# status_message = f"An unexpected error occurred during submission: {e}"
|
343 |
+
# print(status_message)
|
344 |
+
# results_df = pd.DataFrame(results_log)
|
345 |
+
# return status_message, results_df
|
346 |
+
|
347 |
+
|
348 |
+
# # --- Build Gradio Interface using Blocks ---
|
349 |
+
# with gr.Blocks() as demo:
|
350 |
+
# gr.Markdown("# Basic Agent Evaluation Runner")
|
351 |
+
# gr.Markdown(
|
352 |
+
# """
|
353 |
+
# **Instructions:**
|
354 |
+
|
355 |
+
# 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
356 |
+
# 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
357 |
+
# 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
358 |
+
|
359 |
+
# ---
|
360 |
+
# **Disclaimers:**
|
361 |
+
# 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).
|
362 |
+
# 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.
|
363 |
+
# """
|
364 |
+
# )
|
365 |
+
|
366 |
+
# gr.LoginButton()
|
367 |
+
|
368 |
+
# run_button = gr.Button("Run Evaluation & Submit All Answers")
|
369 |
+
|
370 |
+
# status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
371 |
+
# # Removed max_rows=10 from DataFrame constructor
|
372 |
+
# results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
373 |
+
|
374 |
+
# run_button.click(
|
375 |
+
# fn=run_and_submit_all,
|
376 |
+
# outputs=[status_output, results_table]
|
377 |
+
# )
|
378 |
+
|
379 |
+
# if __name__ == "__main__":
|
380 |
+
# print("\n" + "-"*30 + " App Starting " + "-"*30)
|
381 |
+
# # Check for SPACE_HOST and SPACE_ID at startup for information
|
382 |
+
# space_host_startup = os.getenv("SPACE_HOST")
|
383 |
+
# space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
384 |
+
|
385 |
+
# if space_host_startup:
|
386 |
+
# print(f"✅ SPACE_HOST found: {space_host_startup}")
|
387 |
+
# print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
388 |
+
# else:
|
389 |
+
# print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
390 |
+
|
391 |
+
# if space_id_startup: # Print repo URLs if SPACE_ID is found
|
392 |
+
# print(f"✅ SPACE_ID found: {space_id_startup}")
|
393 |
+
# print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
394 |
+
# print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
395 |
+
# else:
|
396 |
+
# print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
397 |
+
|
398 |
+
# print("-"*(60 + len(" App Starting ")) + "\n")
|
399 |
+
|
400 |
+
# print("Launching Gradio Interface for Basic Agent Evaluation...")
|
401 |
+
# demo.launch(debug=True, share=False)
|