Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -140,190 +140,45 @@ class SuperSmartAgent:
|
|
| 140 |
|
| 141 |
def check_python_suitability(self, state):
|
| 142 |
question = state["question"].lower()
|
| 143 |
-
patterns = ["output", "python", "execute", "run", "
|
| 144 |
state["is_python"] = any(word in question for word in patterns)
|
| 145 |
return state
|
| 146 |
|
| 147 |
def execute_python_code(self, state):
|
| 148 |
file_name = state.get("file_name")
|
| 149 |
|
|
|
|
|
|
|
|
|
|
| 150 |
if file_name and file_name.endswith(".py"):
|
| 151 |
file_path = os.path.join("data", file_name)
|
|
|
|
| 152 |
try:
|
| 153 |
with open(file_path, "r") as f:
|
| 154 |
code = f.read()
|
|
|
|
| 155 |
except Exception as e:
|
| 156 |
-
|
|
|
|
|
|
|
| 157 |
return state
|
| 158 |
else:
|
|
|
|
| 159 |
state["response"] = "No valid Python file attached."
|
| 160 |
return state
|
| 161 |
|
| 162 |
try:
|
| 163 |
result = code_interpreter(code)
|
|
|
|
| 164 |
state["response"] = str(result)
|
| 165 |
except Exception as e:
|
| 166 |
-
|
|
|
|
|
|
|
| 167 |
|
| 168 |
return state
|
| 169 |
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 175 |
-
"""
|
| 176 |
-
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 177 |
-
and displays the results.
|
| 178 |
-
"""
|
| 179 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 180 |
-
#space_id = os.getenv("https://huggingface.co/spaces/selim-ba/Final_Agent_HF_Course/tree/main") # Get the SPACE_ID for sending link to the code
|
| 181 |
-
space_id = os.getenv("SPACE_ID")
|
| 182 |
-
|
| 183 |
-
if profile:
|
| 184 |
-
username= f"{profile.username}"
|
| 185 |
-
print(f"User logged in: {username}")
|
| 186 |
-
else:
|
| 187 |
-
print("User not logged in.")
|
| 188 |
-
return "Please Login to Hugging Face with the button.", None
|
| 189 |
-
|
| 190 |
-
api_url = DEFAULT_API_URL
|
| 191 |
-
questions_url = f"{api_url}/questions"
|
| 192 |
-
submit_url = f"{api_url}/submit"
|
| 193 |
-
|
| 194 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 195 |
-
try:
|
| 196 |
-
agent = SuperSmartAgent() #BasicAgent()
|
| 197 |
-
except Exception as e:
|
| 198 |
-
print(f"Error instantiating agent: {e}")
|
| 199 |
-
return f"Error initializing agent: {e}", None
|
| 200 |
-
# 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)
|
| 201 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 202 |
-
print(agent_code)
|
| 203 |
-
|
| 204 |
-
# 2. Fetch Questions
|
| 205 |
-
print(f"Fetching questions from: {questions_url}")
|
| 206 |
-
try:
|
| 207 |
-
response = requests.get(questions_url, timeout=15)
|
| 208 |
-
response.raise_for_status()
|
| 209 |
-
questions_data = response.json()
|
| 210 |
-
if not questions_data:
|
| 211 |
-
print("Fetched questions list is empty.")
|
| 212 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 213 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 214 |
-
except requests.exceptions.RequestException as e:
|
| 215 |
-
print(f"Error fetching questions: {e}")
|
| 216 |
-
return f"Error fetching questions: {e}", None
|
| 217 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 218 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 219 |
-
print(f"Response text: {response.text[:500]}")
|
| 220 |
-
return f"Error decoding server response for questions: {e}", None
|
| 221 |
-
except Exception as e:
|
| 222 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 223 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 224 |
-
|
| 225 |
-
# 3. Run your Agent
|
| 226 |
-
results_log = []
|
| 227 |
-
answers_payload = []
|
| 228 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 229 |
-
for item in questions_data:
|
| 230 |
-
task_id = item.get("task_id")
|
| 231 |
-
question_text = item.get("question")
|
| 232 |
-
if not task_id or question_text is None:
|
| 233 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 234 |
-
continue
|
| 235 |
-
try:
|
| 236 |
-
submitted_answer = agent(question_text)
|
| 237 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 238 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 239 |
-
except Exception as e:
|
| 240 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 241 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 242 |
-
|
| 243 |
-
if not answers_payload:
|
| 244 |
-
print("Agent did not produce any answers to submit.")
|
| 245 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 246 |
-
|
| 247 |
-
# 4. Prepare Submission
|
| 248 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 249 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 250 |
-
print(status_update)
|
| 251 |
-
|
| 252 |
-
# 5. Submit
|
| 253 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 254 |
-
try:
|
| 255 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 256 |
-
response.raise_for_status()
|
| 257 |
-
result_data = response.json()
|
| 258 |
-
final_status = (
|
| 259 |
-
f"Submission Successful!\n"
|
| 260 |
-
f"User: {result_data.get('username')}\n"
|
| 261 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 262 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 263 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 264 |
-
)
|
| 265 |
-
print("Submission successful.")
|
| 266 |
-
results_df = pd.DataFrame(results_log)
|
| 267 |
-
return final_status, results_df
|
| 268 |
-
except requests.exceptions.HTTPError as e:
|
| 269 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 270 |
-
try:
|
| 271 |
-
error_json = e.response.json()
|
| 272 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 273 |
-
except requests.exceptions.JSONDecodeError:
|
| 274 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 275 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 276 |
-
print(status_message)
|
| 277 |
-
results_df = pd.DataFrame(results_log)
|
| 278 |
-
return status_message, results_df
|
| 279 |
-
except requests.exceptions.Timeout:
|
| 280 |
-
status_message = "Submission Failed: The request timed out."
|
| 281 |
-
print(status_message)
|
| 282 |
-
results_df = pd.DataFrame(results_log)
|
| 283 |
-
return status_message, results_df
|
| 284 |
-
except requests.exceptions.RequestException as e:
|
| 285 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 286 |
-
print(status_message)
|
| 287 |
-
results_df = pd.DataFrame(results_log)
|
| 288 |
-
return status_message, results_df
|
| 289 |
-
except Exception as e:
|
| 290 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 291 |
-
print(status_message)
|
| 292 |
-
results_df = pd.DataFrame(results_log)
|
| 293 |
-
return status_message, results_df
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
# --- Build Gradio Interface using Blocks ---
|
| 297 |
-
with gr.Blocks() as demo:
|
| 298 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 299 |
-
gr.Markdown(
|
| 300 |
-
"""
|
| 301 |
-
**Instructions:**
|
| 302 |
-
|
| 303 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 304 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 305 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 306 |
-
|
| 307 |
-
---
|
| 308 |
-
**Disclaimers:**
|
| 309 |
-
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).
|
| 310 |
-
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.
|
| 311 |
-
"""
|
| 312 |
-
)
|
| 313 |
-
|
| 314 |
-
gr.LoginButton()
|
| 315 |
-
|
| 316 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 317 |
-
|
| 318 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 319 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 320 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 321 |
-
|
| 322 |
-
run_button.click(
|
| 323 |
-
fn=run_and_submit_all,
|
| 324 |
-
outputs=[status_output, results_table]
|
| 325 |
-
)
|
| 326 |
-
|
| 327 |
if __name__ == "__main__":
|
| 328 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 329 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
|
|
|
| 140 |
|
| 141 |
def check_python_suitability(self, state):
|
| 142 |
question = state["question"].lower()
|
| 143 |
+
patterns = ["output", "python", "execute", "run", "script"]
|
| 144 |
state["is_python"] = any(word in question for word in patterns)
|
| 145 |
return state
|
| 146 |
|
| 147 |
def execute_python_code(self, state):
|
| 148 |
file_name = state.get("file_name")
|
| 149 |
|
| 150 |
+
# Debug logging for file_name presence and value
|
| 151 |
+
print(f"[DEBUG] file_name from state: {file_name!r}")
|
| 152 |
+
|
| 153 |
if file_name and file_name.endswith(".py"):
|
| 154 |
file_path = os.path.join("data", file_name)
|
| 155 |
+
print(f"[DEBUG] Attempting to open Python file at: {file_path}")
|
| 156 |
try:
|
| 157 |
with open(file_path, "r") as f:
|
| 158 |
code = f.read()
|
| 159 |
+
print(f"[DEBUG] Successfully read code from {file_path}. Code length: {len(code)} chars")
|
| 160 |
except Exception as e:
|
| 161 |
+
error_msg = f"Error loading Python file: {e}"
|
| 162 |
+
print(f"[ERROR] {error_msg}")
|
| 163 |
+
state["response"] = error_msg
|
| 164 |
return state
|
| 165 |
else:
|
| 166 |
+
print("[WARN] No valid Python file attached or filename missing/incorrect extension.")
|
| 167 |
state["response"] = "No valid Python file attached."
|
| 168 |
return state
|
| 169 |
|
| 170 |
try:
|
| 171 |
result = code_interpreter(code)
|
| 172 |
+
print(f"[DEBUG] Execution result: {result[:100]}...") # Print first 100 chars max
|
| 173 |
state["response"] = str(result)
|
| 174 |
except Exception as e:
|
| 175 |
+
error_msg = f"Error executing Python code: {e}"
|
| 176 |
+
print(f"[ERROR] {error_msg}")
|
| 177 |
+
state["response"] = error_msg
|
| 178 |
|
| 179 |
return state
|
| 180 |
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
if __name__ == "__main__":
|
| 183 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 184 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|