Download test_api_question.py from neuralconfig-admin/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 4.69 kB
-
https://huggingface.co/spaces/neuralconfig-admin/Final_Assignment_Template/resolve/main/test_api_question.py
- Command line
-
hf download hf://spaces/neuralconfig-admin/Final_Assignment_Template/test_api_question.py
-
curl -L -o test_api_question.py https://huggingface.co/spaces/neuralconfig-admin/Final_Assignment_Template/resolve/main/test_api_question.py
4.69 kB
| #!/usr/bin/env python3 | |
| """ | |
| Test script for running the enhanced agent on a single API question. | |
| """ | |
| import os | |
| import json | |
| import logging | |
| import requests | |
| from dotenv import load_dotenv | |
| from enhanced_agent import EnhancedAgent | |
| from tools.attachment_handler import cleanup_temp_file | |
| # Load environment variables | |
| load_dotenv() | |
| # Configure basic logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # ANSI color codes for terminal output | |
| COLORS = { | |
| "RED": "\033[91m", | |
| "GREEN": "\033[92m", | |
| "YELLOW": "\033[93m", | |
| "BLUE": "\033[94m", | |
| "MAGENTA": "\033[95m", | |
| "CYAN": "\033[96m", | |
| "WHITE": "\033[97m", | |
| "BOLD": "\033[1m", | |
| "RESET": "\033[0m" | |
| } | |
| # API URL for questions | |
| QUESTIONS_URL = "https://agents-course-unit4-scoring.hf.space/questions" | |
| def fetch_first_question(): | |
| """Fetch the first question from the evaluation API.""" | |
| try: | |
| logger.info(f"Fetching questions from {QUESTIONS_URL}") | |
| response = requests.get(QUESTIONS_URL) | |
| response.raise_for_status() | |
| questions = response.json() | |
| # Check if the response is a list (as expected) or something else | |
| if not isinstance(questions, list) or len(questions) == 0: | |
| logger.error(f"Unexpected API response format or empty list: {questions}") | |
| return None | |
| # Return the first question | |
| logger.info(f"Successfully fetched the first question (Task ID: {questions[0]['task_id']})") | |
| return questions[0] | |
| except Exception as e: | |
| logger.error(f"Error fetching questions: {str(e)}") | |
| return None | |
| def run_agent_on_question(question): | |
| """Run the enhanced agent on a single question.""" | |
| if not question: | |
| logger.error("No question to process") | |
| return | |
| task_id = question["task_id"] | |
| question_text = question["question"] | |
| # Display question info | |
| print(f"\n{COLORS['BOLD']}{COLORS['MAGENTA']}====================================={COLORS['RESET']}") | |
| print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}QUESTION (Task ID: {task_id}){COLORS['RESET']}") | |
| print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}====================================={COLORS['RESET']}") | |
| print(f"{COLORS['BOLD']}{COLORS['GREEN']}QUESTION TEXT:{COLORS['RESET']}\n{question_text}") | |
| print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}====================================={COLORS['RESET']}") | |
| # Initialize the agent | |
| try: | |
| model = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet") | |
| logger.info(f"Initializing agent with model: {model}") | |
| agent = EnhancedAgent(model=model) | |
| logger.info("Agent initialized successfully") | |
| # Process the question | |
| logger.info("Starting agent execution...") | |
| answer = agent(question_text, task_id=task_id) | |
| # Display the answer | |
| print(f"\n{COLORS['BOLD']}{COLORS['WHITE']}===== FINAL ANSWER ====={COLORS['RESET']}") | |
| print(f"{COLORS['BOLD']}{COLORS['GREEN']}{answer}{COLORS['RESET']}") | |
| print(f"{COLORS['BOLD']}{COLORS['WHITE']}========================={COLORS['RESET']}\n") | |
| return { | |
| "task_id": task_id, | |
| "question": question_text, | |
| "answer": answer | |
| } | |
| except Exception as e: | |
| error_msg = f"Error processing question: {str(e)}" | |
| logger.error(error_msg) | |
| print(f"\n{COLORS['RED']}{error_msg}{COLORS['RESET']}") | |
| return None | |
| def main(): | |
| """Main function to run the test.""" | |
| print(f"{COLORS['BOLD']}{COLORS['BLUE']}Testing Enhanced Agent on a Single API Question{COLORS['RESET']}") | |
| # Fetch the first question | |
| question = fetch_first_question() | |
| if not question: | |
| return 1 | |
| # Run the agent on the question | |
| result = run_agent_on_question(question) | |
| if not result: | |
| return 1 | |
| print(f"{COLORS['BOLD']}{COLORS['BLUE']}Test completed successfully!{COLORS['RESET']}") | |
| return 0 | |
| if __name__ == "__main__": | |
| try: | |
| exit_code = main() | |
| except KeyboardInterrupt: | |
| print(f"\n{COLORS['YELLOW']}Test interrupted by user.{COLORS['RESET']}") | |
| exit_code = 130 | |
| except Exception as e: | |
| print(f"\n{COLORS['RED']}Unexpected error: {str(e)}{COLORS['RESET']}") | |
| logger.exception("Unexpected error") | |
| exit_code = 1 | |
| # Ensure we clean up any temporary files | |
| try: | |
| import glob | |
| temp_files = glob.glob("/tmp/attachment_*") | |
| for file in temp_files: | |
| cleanup_temp_file(file) | |
| except: | |
| pass | |
| exit(exit_code) |