File size: 7,953 Bytes
90d7802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#!/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())