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