Update app.py
#581
by mmk12345 - opened
app.py
CHANGED
|
@@ -3,6 +3,7 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
|
@@ -13,22 +14,29 @@ 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 |
-
print(f"Agent returning
|
| 20 |
-
return
|
|
|
|
| 21 |
|
| 22 |
-
def run_and_submit_all(
|
| 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")
|
| 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 +46,14 @@ 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 (
|
| 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 |
-
|
|
|
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
print(agent_code)
|
| 50 |
|
|
@@ -55,16 +64,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 |
-
|
| 59 |
-
|
| 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 |
-
|
| 66 |
-
|
| 67 |
-
|
| 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 +93,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 |
-
|
| 88 |
-
|
| 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)
|
|
@@ -146,11 +155,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).
|
|
@@ -172,10 +179,10 @@ 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")
|
| 179 |
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -183,14 +190,14 @@ if __name__ == "__main__":
|
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
|
| 186 |
-
if space_id_startup:
|
| 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 CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, HfApiModel
|
| 7 |
|
| 8 |
# (Keep Constants as is)
|
| 9 |
# --- Constants ---
|
|
|
|
| 14 |
class BasicAgent:
|
| 15 |
def __init__(self):
|
| 16 |
print("BasicAgent initialized.")
|
| 17 |
+
self.agent = CodeAgent(
|
| 18 |
+
tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
|
| 19 |
+
model=HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct"),
|
| 20 |
+
max_steps=10,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
def __call__(self, question: str) -> str:
|
| 24 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 25 |
+
answer = self.agent.run(question)
|
| 26 |
+
print(f"Agent returning answer: {answer}")
|
| 27 |
+
return answer
|
| 28 |
+
|
| 29 |
|
| 30 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 31 |
"""
|
| 32 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 33 |
and displays the results.
|
| 34 |
"""
|
| 35 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 36 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 37 |
|
| 38 |
if profile:
|
| 39 |
+
username = f"{profile.username}"
|
| 40 |
print(f"User logged in: {username}")
|
| 41 |
else:
|
| 42 |
print("User not logged in.")
|
|
|
|
| 46 |
questions_url = f"{api_url}/questions"
|
| 47 |
submit_url = f"{api_url}/submit"
|
| 48 |
|
| 49 |
+
# 1. Instantiate Agent (modify this part to create your agent)
|
| 50 |
try:
|
| 51 |
agent = BasicAgent()
|
| 52 |
except Exception as e:
|
| 53 |
print(f"Error instantiating agent: {e}")
|
| 54 |
return f"Error initializing agent: {e}", None
|
| 55 |
+
|
| 56 |
+
# 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)
|
| 57 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 58 |
print(agent_code)
|
| 59 |
|
|
|
|
| 64 |
response.raise_for_status()
|
| 65 |
questions_data = response.json()
|
| 66 |
if not questions_data:
|
| 67 |
+
print("Fetched questions list is empty.")
|
| 68 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 69 |
print(f"Fetched {len(questions_data)} questions.")
|
| 70 |
except requests.exceptions.RequestException as e:
|
| 71 |
print(f"Error fetching questions: {e}")
|
| 72 |
return f"Error fetching questions: {e}", None
|
| 73 |
except requests.exceptions.JSONDecodeError as e:
|
| 74 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 75 |
+
print(f"Response text: {response.text[:500]}")
|
| 76 |
+
return f"Error decoding server response for questions: {e}", None
|
| 77 |
except Exception as e:
|
| 78 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 79 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
| 93 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 94 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 95 |
except Exception as e:
|
| 96 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 97 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 98 |
|
| 99 |
if not answers_payload:
|
| 100 |
print("Agent did not produce any answers to submit.")
|
| 101 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 102 |
|
| 103 |
+
# 4. Prepare Submission
|
| 104 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 105 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 106 |
print(status_update)
|
|
|
|
| 155 |
gr.Markdown(
|
| 156 |
"""
|
| 157 |
**Instructions:**
|
|
|
|
| 158 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 159 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 160 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
| 161 |
---
|
| 162 |
**Disclaimers:**
|
| 163 |
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).
|
|
|
|
| 179 |
)
|
| 180 |
|
| 181 |
if __name__ == "__main__":
|
| 182 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 183 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 184 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 185 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 186 |
|
| 187 |
if space_host_startup:
|
| 188 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 190 |
else:
|
| 191 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 192 |
|
| 193 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 194 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 195 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 196 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 197 |
else:
|
| 198 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 199 |
|
| 200 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 201 |
|
| 202 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 203 |
demo.launch(debug=True, share=False)
|