#!/usr/bin/env python3 """ Test script for the enhanced agent with various question types. """ import os import sys import json import logging import argparse from datetime import datetime from dotenv import load_dotenv from enhanced_agent import EnhancedAgent from tools.attachment_handler import download_file_by_task_id, cleanup_temp_file # Load environment variables load_dotenv() # Configure colorful logging class ColoredFormatter(logging.Formatter): """Custom formatter with ANSI colors for log levels""" COLORS = { 'DEBUG': '\033[94m', # Blue 'INFO': '\033[92m', # Green 'WARNING': '\033[93m', # Yellow 'ERROR': '\033[91m', # Red 'CRITICAL': '\033[91m\033[1m', # Bold Red } RESET = '\033[0m' def format(self, record): log_message = super().format(record) if record.levelname in self.COLORS: return f"{self.COLORS[record.levelname]}{log_message}{self.RESET}" return log_message # Set up logging log_filename = f"enhanced_agent_test_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log" logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler(log_filename) # Log to file (without colors) ] ) # Add colored console handler console_handler = logging.StreamHandler() console_handler.setFormatter(ColoredFormatter('%(asctime)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(console_handler) logger = logging.getLogger(__name__) # Test questions with expected minimal answers TEST_QUESTIONS = [ { "name": "Basic information", "question": "What is the capital of France?", "expected": "Paris" }, { "name": "Numerical answer", "question": "What is 25 * 4 + 10?", "expected": "110" }, { "name": "Who question", "question": "Who was the first woman to win a Nobel Prize?", "expected": "Marie Curie" }, { "name": "List answer", "question": "List the colors of the French flag.", "expected": "blue, white, red" }, { "name": "Reverse text", "question": ".txet siht esrever esaelP", "expected": "Please reverse this text." }, { "name": "Excel question (hypothetical)", "question": "What is the total revenue from food sales in the attached Excel file?", "expected": "$1234.56", "annotation": "Mock question - actual Excel files will vary" }, { "name": "Chess move", "question": "In chess notation, what's the standard first move for white in the Sicilian Defense?", "expected": "e4" }, { "name": "IOC code", "question": "What is the IOC country code for the United States?", "expected": "USA" }, { "name": "Comma-separated list", "question": "List the first three planets in our solar system, in order from the Sun.", "expected": "Mercury, Venus, Earth" }, { "name": "Yes/no question", "question": "Is water a compound?", "expected": "Yes" } ] def run_test(agent, question_data): """Run a test and return results.""" question = question_data["question"] expected = question_data["expected"] name = question_data["name"] logger.info("=" * 80) logger.info(f"TEST: {name}") logger.info("-" * 80) logger.info(f"QUESTION: {question}") logger.info(f"EXPECTED: {expected}") try: answer = agent(question) logger.info(f"ACTUAL: {answer}") if answer.lower() == expected.lower(): logger.info("RESULT: ✅ PASS") return True else: logger.info("RESULT: ❌ FAIL") return False except Exception as e: logger.error(f"ERROR: {str(e)}") logger.info("RESULT: ❌ FAIL (error)") return False def main(): """Main function to run the tests.""" parser = argparse.ArgumentParser(description="Test the enhanced agent with various question types.") parser.add_argument("--model", help="OpenRouter model to use", default=os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")) parser.add_argument("--questions", help="Path to JSON file with custom questions") parser.add_argument("--task-id", help="Task ID to test with file attachment") args = parser.parse_args() # Load custom questions if provided questions = TEST_QUESTIONS if args.questions: try: with open(args.questions, 'r') as f: custom_questions = json.load(f) if isinstance(custom_questions, list): questions = custom_questions logger.info(f"Loaded {len(questions)} custom questions from {args.questions}") else: logger.error(f"Invalid questions file format: {args.questions}") except Exception as e: logger.error(f"Error loading questions file: {str(e)}") # Initialize the agent try: logger.info(f"Initializing agent with model: {args.model}") agent = EnhancedAgent(model=args.model) logger.info("Agent initialized successfully") except Exception as e: logger.error(f"Failed to initialize agent: {str(e)}") return 1 # Test file attachment handling if a task ID is provided if args.task_id: logger.info("=" * 80) logger.info(f"TESTING FILE ATTACHMENT: Task ID {args.task_id}") logger.info("-" * 80) try: attachment_result = download_file_by_task_id(args.task_id) if attachment_result["success"]: file_path = attachment_result["file_path"] file_name = attachment_result["file_name"] content_type = attachment_result["content_type"] logger.info(f"Successfully downloaded attachment: {file_name} ({content_type})") logger.info(f"File path: {file_path}") # Try to read the file content try: if content_type.startswith("text/") or content_type.startswith("application/json"): with open(file_path, 'r') as f: content_preview = f.read(1000) logger.info(f"File content preview:\n{content_preview}...") else: logger.info(f"Binary file detected, size: {os.path.getsize(file_path)} bytes") except Exception as e: logger.error(f"Error reading file content: {str(e)}") # Clean up cleanup_temp_file(file_path) logger.info("File cleaned up") else: logger.error(f"Failed to download attachment: {attachment_result.get('error', 'Unknown error')}") except Exception as e: logger.error(f"Error testing file attachment: {str(e)}") # Run the tests results = [] logger.info("=" * 80) logger.info(f"RUNNING {len(questions)} TESTS") logger.info("=" * 80) for i, question_data in enumerate(questions, 1): logger.info(f"Test {i}/{len(questions)}") result = run_test(agent, question_data) results.append(result) # Summarize results passed = sum(results) failed = len(results) - passed logger.info("=" * 80) logger.info("TEST SUMMARY") logger.info("-" * 80) logger.info(f"Total tests: {len(results)}") logger.info(f"Passed: {passed}") logger.info(f"Failed: {failed}") logger.info(f"Success rate: {passed/len(results)*100:.2f}%") logger.info("=" * 80) return 0 if failed == 0 else 1 if __name__ == "__main__": sys.exit(main())