File size: 7,260 Bytes
1fc2038
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Hybrid GAIA Solver - Best of Both Architectures
Combines the production-proven main.py with modular architecture benefits.
"""

import os
import sys
from pathlib import Path

# Add current directory to path
current_dir = Path(__file__).parent
if str(current_dir) not in sys.path:
    sys.path.insert(0, str(current_dir))

# Architecture selection based on availability and preferences
ARCHITECTURE_PREFERENCE = os.getenv("GAIA_ARCHITECTURE", "auto")  # auto, legacy, refactored

def get_solver_class():
    """
    Intelligent solver selection with fallback chain:
    1. Try refactored architecture (if available and requested)
    2. Fall back to legacy monolithic (production-proven)
    """
    
    if ARCHITECTURE_PREFERENCE == "legacy":
        print("πŸ”§ Using legacy monolithic architecture (forced)")
        from main import GAIASolver
        return GAIASolver, "legacy"
    
    if ARCHITECTURE_PREFERENCE == "refactored":
        try:
            print("πŸ”§ Using refactored modular architecture (forced)")
            from gaia import GAIASolver, Config
            return GAIASolver, "refactored"
        except ImportError as e:
            print(f"❌ Refactored architecture not available: {e}")
            print("πŸ”„ Falling back to legacy architecture")
            from main import GAIASolver
            return GAIASolver, "legacy"
    
    # Auto mode - intelligent selection
    try:
        # Try refactored first (preferred for new development)
        from gaia import GAIASolver, Config
        print("βœ… Using refactored modular architecture (auto-selected)")
        return GAIASolver, "refactored"
    except ImportError:
        # Fall back to legacy (production-proven)
        from main import GAIASolver
        print("βœ… Using legacy monolithic architecture (auto-selected)")
        return GAIASolver, "legacy"

class HybridGAIASolver:
    """
    Hybrid solver that provides a unified interface regardless of underlying architecture.
    """
    
    def __init__(self, **kwargs):
        self.solver_class, self.architecture = get_solver_class()
        
        if self.architecture == "refactored":
            # Initialize refactored version with configuration
            try:
                from gaia import Config
                config = kwargs.get('config', Config())
                self.solver = self.solver_class(config)
            except Exception as e:
                print(f"⚠️ Refactored initialization failed: {e}")
                print("πŸ”„ Falling back to legacy architecture")
                from main import GAIASolver
                self.solver = GAIASolver(**kwargs)
                self.architecture = "legacy"
        else:
            # Initialize legacy version
            self.solver = self.solver_class(**kwargs)
    
    def solve_question(self, question_data):
        """
        Unified solve_question interface that works with both architectures.
        """
        if self.architecture == "refactored":
            # Refactored architecture expects different format
            try:
                result = self.solver.solve_question(question_data)
                # Convert refactored result to legacy format for compatibility
                if hasattr(result, 'answer'):
                    return {
                        'answer': result.answer,
                        'explanation': getattr(result, 'reasoning', ''),
                        'confidence': getattr(result, 'confidence', 1.0),
                        'method_used': getattr(result, 'method_used', 'unknown'),
                        'execution_time': getattr(result, 'execution_time', 0.0)
                    }
                else:
                    return result
            except Exception as e:
                print(f"⚠️ Refactored solver failed: {e}")
                print("πŸ”„ This question may need legacy solver")
                return f"Error with refactored solver: {str(e)}"
        else:
            # Legacy architecture
            return self.solver.solve_question(question_data)
    
    def get_system_info(self):
        """Get information about the current architecture and capabilities."""
        info = {
            'architecture': self.architecture,
            'solver_class': self.solver_class.__name__,
            'capabilities': {}
        }
        
        if self.architecture == "refactored":
            try:
                status = self.solver.get_system_status()
                info['capabilities'] = status
            except:
                info['capabilities'] = {'status': 'refactored architecture active'}
        else:
            info['capabilities'] = {
                'status': 'legacy monolithic architecture active',
                'features': 'production-proven, comprehensive'
            }
        
        return info
    
    def solve_random_question(self):
        """Solve a random question (legacy interface compatibility)."""
        if hasattr(self.solver, 'solve_random_question'):
            return self.solver.solve_random_question()
        else:
            return "Random question solving not available in current architecture"
    
    def solve_all_questions(self, max_questions=5):
        """Solve multiple questions (legacy interface compatibility)."""
        if hasattr(self.solver, 'solve_all_questions'):
            return self.solver.solve_all_questions(max_questions)
        else:
            return "Batch question solving not available in current architecture"

def main():
    """Main function for testing the hybrid solver."""
    print("πŸš€ GAIA Solver - Hybrid Architecture")
    print("=" * 50)
    
    try:
        # Initialize hybrid solver
        solver = HybridGAIASolver()
        
        # Show system information
        info = solver.get_system_info()
        print(f"πŸ“Š Architecture: {info['architecture']}")
        print(f"πŸ”§ Solver Class: {info['solver_class']}")
        print(f"πŸ’‘ Capabilities: {info['capabilities']}")
        
        # Test with a sample question
        print("\nπŸ§ͺ Testing with sample question...")
        sample_question = {
            "task_id": "hybrid_test_001",
            "question": "What is 2 + 2?",
            "level": 1
        }
        
        result = solver.solve_question(sample_question)
        
        print(f"\nπŸ“‹ Results:")
        if isinstance(result, dict):
            print(f"  Answer: {result.get('answer', 'No answer')}")
            print(f"  Explanation: {result.get('explanation', 'No explanation')}")
            if 'confidence' in result:
                print(f"  Confidence: {result['confidence']:.2f}")
            if 'method_used' in result:
                print(f"  Method: {result['method_used']}")
            if 'execution_time' in result:
                print(f"  Time: {result['execution_time']:.2f}s")
        else:
            print(f"  Result: {result}")
        
        print(f"\nβœ… Hybrid solver test completed successfully!")
        print(f"πŸ—οΈ  Using {info['architecture']} architecture")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()