File size: 14,314 Bytes
ba68fc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python3
"""
Question processing and agent coordination for GAIA solver.
Handles question classification, file management, and agent execution.
"""

import re
import time
from typing import Dict, Any, List, Optional

from ..config.settings import Config
from ..models.manager import ModelManager
from ..utils.exceptions import GAIAError, ClassificationError


class QuestionProcessor:
    """Processes questions and coordinates agent execution."""
    
    def __init__(self, model_manager: ModelManager, config: Config):
        self.model_manager = model_manager
        self.config = config
        self.question_loader = None
        self.classifier = None
        
        # Initialize components lazily
        self._init_components()
        
        # Prompt templates (simplified version)
        self.prompt_templates = self._get_prompt_templates()
    
    def _init_components(self) -> None:
        """Initialize question loader and classifier."""
        try:
            # Import and initialize question loader
            from ..utils.question_loader import GAIAQuestionLoader
            self.question_loader = GAIAQuestionLoader()
            
            # Import and initialize classifier
            from ..utils.classifier import QuestionClassifier
            self.classifier = QuestionClassifier(self.model_manager)
            
        except ImportError:
            # Fallback to legacy imports if new modules not ready
            print("โš ๏ธ Using legacy question processing components")
            self._init_legacy_components()
    
    def _init_legacy_components(self) -> None:
        """Initialize legacy components as fallback."""
        try:
            import sys
            import os
            
            # Add parent directory to path for legacy imports
            parent_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
            if parent_dir not in sys.path:
                sys.path.insert(0, parent_dir)
            
            from gaia_web_loader import GAIAQuestionLoaderWeb
            from question_classifier import QuestionClassifier as LegacyClassifier
            
            self.question_loader = GAIAQuestionLoaderWeb()
            self.classifier = LegacyClassifier()
            
        except ImportError as e:
            print(f"โš ๏ธ Could not initialize question processing components: {e}")
            # Create minimal fallback
            self.question_loader = None
            self.classifier = None
    
    def _get_prompt_templates(self) -> Dict[str, str]:
        """Get simplified prompt templates."""
        return {
            "multimedia": """You are solving a GAIA benchmark multimedia question.

TASK: {question_text}

APPROACH:
1. Use appropriate multimedia analysis tools
2. For YouTube videos, ALWAYS use analyze_youtube_video tool
3. Extract exact information requested
4. Provide precise final answer

Focus on accuracy and use tool outputs directly.""",

            "research": """You are solving a GAIA benchmark research question.

TASK: {question_text}

APPROACH:
1. Use research_with_comprehensive_fallback for robust search
2. Try multiple research methods if needed
3. Use tool outputs directly - do not fabricate information
4. Provide factual, verified answer

Trust validated research data over internal knowledge.""",

            "logic_math": """You are solving a GAIA benchmark logic/math question.

TASK: {question_text}

APPROACH:
1. Break down the problem step-by-step
2. Use advanced_calculator for calculations
3. Show your work clearly
4. Verify your final answer

Focus on mathematical precision.""",

            "file_processing": """You are solving a GAIA benchmark file processing question.

TASK: {question_text}

APPROACH:
1. Use appropriate file analysis tools
2. Extract the specific data requested
3. Process and calculate as needed
4. Use tool results directly

Trust file processing tool outputs.""",

            "chess": """You are solving a GAIA benchmark chess question.

TASK: {question_text}

APPROACH:
1. Use analyze_chess_multi_tool for comprehensive analysis
2. Take the EXACT move returned by the tool
3. Do not modify or interpret the result
4. Use tool result directly as final answer

Trust the chess analysis tool completely.""",

            "general": """You are solving a GAIA benchmark question.

TASK: {question_text}

APPROACH:
1. Analyze the question carefully
2. Choose appropriate tools
3. Work systematically
4. Provide clear, direct answer

Focus on answering exactly what is asked."""
        }
    
    def process_question(self, question_data: Dict[str, Any]) -> str:
        """Process a question and return the raw response."""
        question_text = question_data.get("question", "")
        task_id = question_data.get("task_id", "unknown")
        
        # Handle file downloads if needed
        enhanced_question = self._handle_file_processing(question_data)
        
        # Classify the question
        classification = self._classify_question(enhanced_question, question_data)
        
        # Get appropriate prompt
        prompt = self._get_enhanced_prompt(enhanced_question, classification)
        
        # Execute with agent
        response = self._execute_with_agent(prompt)
        
        return response
    
    def _handle_file_processing(self, question_data: Dict[str, Any]) -> str:
        """Handle file downloads and enhance question text."""
        question_text = question_data.get("question", "")
        has_file = bool(question_data.get("file_name", ""))
        
        if has_file and self.question_loader:
            file_name = question_data.get('file_name')
            task_id = question_data.get('task_id', 'unknown')
            
            print(f"๐Ÿ“Ž Note: This question has an associated file: {file_name}")
            
            try:
                # Download the file
                print(f"โฌ‡๏ธ Downloading file: {file_name}")
                downloaded_path = self.question_loader.download_file(task_id)
                
                if downloaded_path:
                    print(f"โœ… File downloaded to: {downloaded_path}")
                    question_text += f"\n\n[Note: This question references a file: {downloaded_path}]"
                else:
                    print(f"โš ๏ธ Failed to download file: {file_name}")
                    question_text += f"\n\n[Note: This question references a file: {file_name} - download failed]"
            except Exception as e:
                print(f"โš ๏ธ Error downloading file: {e}")
                question_text += f"\n\n[Note: This question references a file: {file_name} - download error]"
        
        return question_text
    
    def _classify_question(self, question_text: str, question_data: Dict[str, Any]) -> Dict[str, Any]:
        """Classify the question to determine agent type."""
        try:
            if self.classifier:
                file_name = question_data.get('file_name', '')
                classification = self.classifier.classify_question(question_text, file_name)
            else:
                # Fallback classification
                classification = self._fallback_classification(question_text)
            
            # Special handling for known patterns
            classification = self._enhance_classification(question_text, classification)
            
            return classification
            
        except Exception as e:
            print(f"โš ๏ธ Classification error: {e}")
            # Return general classification as fallback
            return {
                'primary_agent': 'general',
                'complexity': 3,
                'tools_needed': [],
                'confidence': 0.5
            }
    
    def _fallback_classification(self, question_text: str) -> Dict[str, Any]:
        """Simple fallback classification logic."""
        question_lower = question_text.lower()
        
        # YouTube detection
        youtube_pattern = r'(https?://)?(www\.)?(youtube\.com|youtu\.?be)'
        if re.search(youtube_pattern, question_text):
            return {
                'primary_agent': 'multimedia',
                'complexity': 3,
                'tools_needed': ['analyze_youtube_video'],
                'confidence': 0.9
            }
        
        # Chess detection
        chess_keywords = ['chess', 'position', 'move', 'algebraic notation']
        if any(keyword in question_lower for keyword in chess_keywords):
            return {
                'primary_agent': 'chess',
                'complexity': 4,
                'tools_needed': ['analyze_chess_multi_tool'],
                'confidence': 0.9
            }
        
        # File processing detection
        file_extensions = ['.xlsx', '.xls', '.py', '.txt', '.pdf']
        if any(ext in question_lower for ext in file_extensions):
            return {
                'primary_agent': 'file_processing',
                'complexity': 3,
                'tools_needed': ['analyze_excel_file', 'analyze_python_code'],
                'confidence': 0.8
            }
        
        # Math detection
        math_keywords = ['calculate', 'solve', 'equation', 'formula', 'math']
        if any(keyword in question_lower for keyword in math_keywords):
            return {
                'primary_agent': 'logic_math',
                'complexity': 3,
                'tools_needed': ['advanced_calculator'],
                'confidence': 0.7
            }
        
        # Research fallback
        return {
            'primary_agent': 'research',
            'complexity': 3,
            'tools_needed': ['research_with_comprehensive_fallback'],
            'confidence': 0.6
        }
    
    def _enhance_classification(self, question_text: str, classification: Dict[str, Any]) -> Dict[str, Any]:
        """Enhance classification with special handling."""
        question_lower = question_text.lower()
        
        # Force YouTube classification
        youtube_url_pattern = r'(https?://)?(www\.)?(youtube\.com|youtu\.?be)/(?:watch\?v=|embed/|v/|shorts/|playlist\?list=|channel/|user/|[^/\s]+/?)?([^\s&?/]+)'
        if re.search(youtube_url_pattern, question_text):
            classification['primary_agent'] = 'multimedia'
            if 'analyze_youtube_video' not in classification.get('tools_needed', []):
                classification['tools_needed'] = ['analyze_youtube_video'] + classification.get('tools_needed', [])
            print("๐ŸŽฅ YouTube URL detected - forcing multimedia classification")
        
        # Force chess classification
        chess_keywords = ['chess', 'position', 'move', 'algebraic notation', 'black to move', 'white to move']
        if any(keyword in question_lower for keyword in chess_keywords):
            classification['primary_agent'] = 'chess'
            print("โ™Ÿ๏ธ Chess question detected - using specialized chess analysis")
        
        return classification
    
    def _get_enhanced_prompt(self, question_text: str, classification: Dict[str, Any]) -> str:
        """Get enhanced prompt based on classification."""
        question_type = classification.get('primary_agent', 'general')
        
        print(f"๐ŸŽฏ Question type: {question_type}")
        print(f"๐Ÿ“Š Complexity: {classification.get('complexity', 'unknown')}/5")
        print(f"๐Ÿ”ง Tools needed: {classification.get('tools_needed', [])}")
        
        # Get appropriate template
        if question_type in self.prompt_templates:
            template = self.prompt_templates[question_type]
        else:
            template = self.prompt_templates["general"]
        
        enhanced_prompt = template.format(question_text=question_text)
        print(f"๐Ÿ“‹ Using {question_type} prompt template")
        
        return enhanced_prompt
    
    def _execute_with_agent(self, prompt: str) -> str:
        """Execute prompt with smolagents agent."""
        try:
            # Get current model
            model = self.model_manager.get_current_model()
            
            # Create fresh agent for memory management
            from smolagents import CodeAgent
            
            # Import tools
            tools = self._get_tools()
            
            print("๐Ÿง  Creating fresh agent to avoid memory accumulation...")
            agent = CodeAgent(
                model=model,
                tools=tools,
                max_steps=self.config.model.MAX_STEPS,
                verbosity_level=self.config.model.VERBOSITY_LEVEL
            )
            
            # Execute the prompt
            response = agent.run(prompt)
            raw_answer = str(response)
            print(f"โœ… Generated raw answer: {raw_answer[:100]}...")
            
            return raw_answer
            
        except Exception as e:
            # Try fallback model if available
            if self.model_manager._switch_to_fallback():
                print("๐Ÿ”„ Retrying with fallback model...")
                return self._execute_with_agent(prompt)
            else:
                raise GAIAError(f"Agent execution failed: {e}")
    
    def _get_tools(self) -> List:
        """Get available tools for the agent."""
        try:
            # Import tools from the old system for now
            import sys
            import os
            
            parent_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
            if parent_dir not in sys.path:
                sys.path.insert(0, parent_dir)
            
            from gaia_tools import GAIA_TOOLS
            return GAIA_TOOLS
            
        except ImportError:
            print("โš ๏ธ Could not import GAIA_TOOLS, using empty tool list")
            return []
    
    def get_random_question(self) -> Optional[Dict[str, Any]]:
        """Get a random question."""
        if self.question_loader:
            return self.question_loader.get_random_question()
        return None
    
    def get_questions(self, max_questions: int = 5) -> List[Dict[str, Any]]:
        """Get multiple questions."""
        if self.question_loader and hasattr(self.question_loader, 'questions'):
            return self.question_loader.questions[:max_questions]
        return []