GoodLuckChuck commited on
Commit
a9d6c9f
·
verified ·
1 Parent(s): 9047cda

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +247 -1
app.py CHANGED
@@ -364,4 +364,250 @@ class ChuckAgent:
364
  except Exception as e:
365
  error_msg = f"Error running ChuckAgent: {str(e)}"
366
  logger.error(error_msg, exc_info=True)
367
- return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  except Exception as e:
365
  error_msg = f"Error running ChuckAgent: {str(e)}"
366
  logger.error(error_msg, exc_info=True)
367
+ return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
368
+
369
+ async def shutdown(self):
370
+ logger.info("ChuckAgent shutting down...")
371
+ await close_shared_http_session()
372
+ logger.info("ChuckAgent shutdown complete.")
373
+
374
+ # --- Core Evaluation Logic ---
375
+ def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
376
+ space_id = os.getenv("SPACE_ID")
377
+ agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
378
+ return space_id, agent_code_url
379
+
380
+ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
381
+ questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
382
+ logger.info(f"Fetching questions from: {questions_url}")
383
+ try:
384
+ response = requests.get(questions_url, timeout=30)
385
+ response.raise_for_status()
386
+ questions_data = response.json()
387
+ if not questions_data or not isinstance(questions_data, list):
388
+ logger.warning(f"Fetched questions empty or invalid: {questions_data}")
389
+ raise ValueError("Fetched questions list is empty or not a list.")
390
+ logger.info(f"Fetched {len(questions_data)} questions.")
391
+ return questions_data
392
+ except requests.exceptions.RequestException as e:
393
+ logger.error(f"Error fetching questions: {e}", exc_info=True)
394
+ raise ConnectionError(f"Error fetching questions: {e}") from e
395
+ except (requests.exceptions.JSONDecodeError, ValueError) as e:
396
+ logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
397
+ raise ValueError(f"Error decoding server response for questions: {e}") from e
398
+
399
+ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
400
+ answers_payload = []
401
+ results_log = []
402
+ logger.info(f"Running agent on {len(questions_data)} questions...")
403
+
404
+ for i, item in enumerate(questions_data):
405
+ task_id = item.get("task_id")
406
+ question_text = item.get("question")
407
+ if not task_id or question_text is None:
408
+ logger.warning(f"Skipping item {i+1} with missing data: {item}")
409
+ continue
410
+ logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
411
+ model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
412
+ try:
413
+ model_ans, reasoning = agent(question_text)
414
+ except Exception as e:
415
+ logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
416
+ model_ans = f"AGENT_CALL_ERROR: {e}"
417
+ reasoning = str(e)
418
+
419
+ payload_item = {"task_id": task_id, "submitted_answer": model_ans}
420
+ if reasoning:
421
+ payload_item["reasoning_trace"] = reasoning
422
+ answers_payload.append(payload_item)
423
+
424
+ results_log.append({
425
+ "Task ID": task_id,
426
+ "Question": question_text,
427
+ "Submitted Answer": model_ans,
428
+ "Reasoning Trace": reasoning
429
+ })
430
+ return answers_payload, results_log
431
+
432
+ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
433
+ if not answers_payload:
434
+ logger.warning("Agent did not produce any answers to submit.")
435
+ return "Agent did not produce any answers to submit."
436
+
437
+ submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
438
+ submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
439
+ logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
440
+ try:
441
+ response = requests.post(submit_url, json=submission_data, timeout=60)
442
+ response.raise_for_status()
443
+ result_data = response.json()
444
+ return (
445
+ f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
446
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
447
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
448
+ f"Message: {result_data.get('message', 'No message received.')}"
449
+ )
450
+ except requests.exceptions.HTTPError as e:
451
+ error_detail = f"Server responded with {e.response.status_code}."
452
+ try:
453
+ error_json = e.response.json()
454
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
455
+ except requests.exceptions.JSONDecodeError:
456
+ error_detail += f" Raw Response: {e.response.text[:500]}"
457
+ logger.error(f"Submission Failed: {error_detail}")
458
+ return f"Submission Failed: {error_detail}"
459
+ except requests.exceptions.Timeout:
460
+ logger.error("Submission Failed: The request timed out.")
461
+ return "Submission Failed: The request timed out."
462
+ except requests.exceptions.RequestException as e:
463
+ logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
464
+ return f"Submission Failed: Network error - {e}"
465
+ except Exception as e:
466
+ logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
467
+ return f"An unexpected error occurred during submission: {e}"
468
+
469
+ # --- Gradio Interface Main Function ---
470
+ GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
471
+
472
+ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
473
+ global GLOBAL_CHUCK_AGENT
474
+ logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
475
+ if args:
476
+ logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
477
+
478
+ if not isinstance(profile, gr.OAuthProfile) and profile is not None:
479
+ logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
480
+ found_profile_in_args = False
481
+ for arg_val in args:
482
+ if isinstance(arg_val, gr.OAuthProfile):
483
+ profile = arg_val
484
+ found_profile_in_args = True
485
+ logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
486
+ break
487
+ if not found_profile_in_args and profile is None:
488
+ logger.error("Could not identify a valid gr.OAuthProfile object.")
489
+ return "Login error: Could not identify user profile.", pd.DataFrame()
490
+
491
+ logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
492
+
493
+ if not profile:
494
+ logger.warning("User not logged in for evaluation.")
495
+ return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
496
+
497
+ username = profile.username
498
+ logger.info(f"User logged in: {username}")
499
+
500
+ _, agent_code_url = get_space_id_agent_code_url()
501
+ logger.info(f"Agent code URL: {agent_code_url}")
502
+ results_log_data: List[Dict[str, Any]] = []
503
+
504
+ try:
505
+ if GLOBAL_CHUCK_AGENT is None:
506
+ GLOBAL_CHUCK_AGENT = ChuckAgent() # This is where QuestionAnsweringAgent is instantiated
507
+ agent_instance = GLOBAL_CHUCK_AGENT
508
+ except EnvironmentError as e: # This will catch missing API keys from ChuckAgent init
509
+ logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
510
+ return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
511
+ except Exception as e: # Catches other errors from ChuckAgent init, like the TypeError we're fixing
512
+ logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
513
+ return f"Error initializing agent: {e}", pd.DataFrame()
514
+
515
+ try:
516
+ questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
517
+ answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
518
+ submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
519
+ except (ConnectionError, ValueError) as e:
520
+ submission_status = str(e)
521
+ except Exception as e:
522
+ logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
523
+ submission_status = f"An unexpected error occurred: {e}"
524
+
525
+ results_df = pd.DataFrame(results_log_data if results_log_data else [])
526
+ return submission_status, results_df
527
+
528
+ # --- Build Gradio Interface ---
529
+ with gr.Blocks() as demo:
530
+ gr.Markdown("# Basic Agent Evaluation Runner")
531
+ gr.Markdown(
532
+ """
533
+ **Instructions:**
534
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
535
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
536
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
537
+ """
538
+ )
539
+ gr.Markdown(
540
+ """
541
+ **Disclaimers:** 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). 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 separate action or even to answer the questions in async.
542
+ """
543
+ )
544
+ gr.Markdown(
545
+ f"""
546
+ ---
547
+ **Technical Notes:**
548
+ * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
549
+ * Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
550
+ * `requirements.txt` should specify a compatible `gradio` version (e.g., `gradio==4.29.0` or `gradio==4.44.1`).
551
+ * The current `smolagents` version might have an internal issue with `CodeAgent` initialization. A workaround is active.
552
+ """
553
+ )
554
+
555
+ login_button = gr.LoginButton()
556
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
557
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
558
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
559
+
560
+ run_button.click(
561
+ fn=run_and_submit_all_evaluation,
562
+ inputs=[login_button],
563
+ outputs=[status_output, results_table]
564
+ )
565
+
566
+ # --- Application Startup & Shutdown Handling ---
567
+ if __name__ == "__main__":
568
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
569
+ space_host_startup = os.getenv("SPACE_HOST")
570
+ space_id_startup, agent_url_startup = get_space_id_agent_code_url()
571
+
572
+ if space_host_startup:
573
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
574
+ print(f" Runtime URL might be: https://{space_host_startup}")
575
+ else:
576
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
577
+
578
+ if space_id_startup:
579
+ print(f"✅ SPACE_ID found: {space_id_startup}")
580
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
581
+ print(f" Agent Code URL reported to server: {agent_url_startup}")
582
+ else:
583
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
584
+
585
+ print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
586
+ print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
587
+ print("-"*(60 + len(" App Starting ")) + "\n")
588
+ print("Launching Gradio Interface for Chuck Agent Evaluation...")
589
+
590
+ try:
591
+ demo.launch(debug=True, share=False)
592
+ finally:
593
+ loop_to_use = None
594
+ if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
595
+ loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
596
+ elif SHARED_HTTP_SESSION:
597
+ loop_to_use = SHARED_HTTP_SESSION.loop
598
+
599
+ if loop_to_use and loop_to_use.is_running():
600
+ logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
601
+ try:
602
+ current_loop = asyncio.get_event_loop_policy().get_event_loop() # More robust way to get current loop
603
+ if current_loop is not loop_to_use and not loop_to_use.is_closed():
604
+ asyncio.set_event_loop(loop_to_use)
605
+
606
+ if GLOBAL_CHUCK_AGENT:
607
+ loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
608
+ elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
609
+ loop_to_use.run_until_complete(close_shared_http_session())
610
+ except Exception as e:
611
+ logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
612
+ else:
613
+ logger.info("No active HTTP session or running loop to close in finally block.")