File size: 7,728 Bytes
8a682b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test script for Optimized Chain of Thought integration
Verifies that the CoT system works correctly with the hybrid architecture
"""

import asyncio
import sys
import os

# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

def test_cot_standalone():
    """Test the CoT system in standalone mode"""
    print("πŸ§ͺ Testing Optimized Chain of Thought (Standalone)")
    print("-" * 50)
    
    try:
        from optimized_chain_of_thought import (
            OptimizedChainOfThought, ReasoningType, ComplexityAnalyzer
        )
        
        # Test complexity analyzer
        analyzer = ComplexityAnalyzer()
        complexity, features = analyzer.analyze("What is machine learning?")
        print(f"βœ… Complexity Analysis: {complexity:.3f}")
        print(f"   Features: {list(features.keys())}")
        
        # Test CoT system
        cot = OptimizedChainOfThought("test_cot")
        print(f"βœ… CoT System initialized")
        
        return True
        
    except Exception as e:
        print(f"❌ CoT Standalone Test Failed: {e}")
        return False

async def test_cot_integration():
    """Test CoT integration with hybrid architecture"""
    print("\nπŸ”— Testing CoT Integration with Hybrid Architecture")
    print("-" * 50)
    
    try:
        from advanced_hybrid_architecture import AdvancedHybridAgent, AgentMode
        
        # Initialize hybrid agent
        agent = AdvancedHybridAgent(
            "test_agent",
            config={
                'cot': {'max_paths': 3, 'cache_size': 50},
                'fsm': {'max_steps': 5}
            }
        )
        print(f"βœ… Hybrid Agent initialized")
        
        # Test CoT mode specifically
        test_query = "Explain the concept of artificial intelligence step by step"
        result = await agent.process_query(test_query)
        
        print(f"βœ… Query processed successfully")
        print(f"   Mode: {result.get('mode')}")
        print(f"   Confidence: {result.get('confidence', 0):.3f}")
        
        if 'reasoning_path' in result:
            path = result['reasoning_path']
            print(f"   CoT Steps: {len(path.steps)}")
            print(f"   Template: {path.template_used}")
            print(f"   Final Answer: {path.final_answer[:100]}...")
        
        return True
        
    except Exception as e:
        print(f"❌ CoT Integration Test Failed: {e}")
        import traceback
        traceback.print_exc()
        return False

async def test_performance_tracking():
    """Test performance tracking capabilities"""
    print("\nπŸ“Š Testing Performance Tracking")
    print("-" * 50)
    
    try:
        from advanced_hybrid_architecture import AdvancedHybridAgent
        
        agent = AdvancedHybridAgent("perf_test_agent")
        
        # Process multiple queries
        queries = [
            "What is 2 + 2?",
            "Explain machine learning",
            "Compare AI and human intelligence"
        ]
        
        for query in queries:
            await agent.process_query(query)
        
        # Get performance report
        report = agent.get_performance_report()
        
        print(f"βœ… Performance tracking working")
        print(f"   Total queries: {report['total_queries']}")
        print(f"   Average confidence: {report['average_confidence']:.3f}")
        print(f"   Mode usage: {report['mode_usage']}")
        
        return True
        
    except Exception as e:
        print(f"❌ Performance Tracking Test Failed: {e}")
        return False

async def test_caching():
    """Test caching functionality"""
    print("\nπŸ’Ύ Testing Caching System")
    print("-" * 50)
    
    try:
        from optimized_chain_of_thought import OptimizedChainOfThought
        
        cot = OptimizedChainOfThought("cache_test")
        
        # First query
        query = "What is the capital of France?"
        result1 = await cot.reason(query)
        
        # Same query again (should use cache)
        result2 = await cot.reason(query)
        
        print(f"βœ… Caching system working")
        print(f"   First run confidence: {result1.total_confidence:.3f}")
        print(f"   Cached run confidence: {result2.total_confidence:.3f}")
        
        # Check cache stats
        stats = cot.reasoning_cache.get_stats()
        print(f"   Cache size: {stats['size']}")
        print(f"   Hit rate: {stats['hit_rate']:.3f}")
        
        return True
        
    except Exception as e:
        print(f"❌ Caching Test Failed: {e}")
        return False

async def test_template_system():
    """Test template selection and usage"""
    print("\nπŸ“‹ Testing Template System")
    print("-" * 50)
    
    try:
        from optimized_chain_of_thought import TemplateLibrary, ComplexityAnalyzer
        
        library = TemplateLibrary()
        analyzer = ComplexityAnalyzer()
        
        # Test different query types
        test_cases = [
            ("Solve the equation: 2x + 3 = 7", "mathematical"),
            ("Compare cats and dogs", "comparative"),
            ("Why does the sky appear blue?", "causal"),
            ("Analyze the impact of social media", "analytical")
        ]
        
        for query, expected_type in test_cases:
            complexity, features = analyzer.analyze(query)
            template = library.select_template(query, features)
            
            print(f"   Query: {query[:30]}...")
            print(f"   Selected: {template.name}")
            print(f"   Expected: {expected_type}")
            print(f"   Match: {'βœ…' if template.name == expected_type else '❌'}")
            print()
        
        return True
        
    except Exception as e:
        print(f"❌ Template System Test Failed: {e}")
        return False

async def main():
    """Run all tests"""
    print("πŸš€ Optimized Chain of Thought Integration Tests")
    print("=" * 60)
    
    tests = [
        ("Standalone CoT", test_cot_standalone),
        ("CoT Integration", test_cot_integration),
        ("Performance Tracking", test_performance_tracking),
        ("Caching System", test_caching),
        ("Template System", test_template_system)
    ]
    
    results = []
    
    for test_name, test_func in tests:
        print(f"\nπŸ§ͺ Running {test_name} Test...")
        try:
            if asyncio.iscoroutinefunction(test_func):
                result = await test_func()
            else:
                result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"❌ {test_name} Test Failed: {e}")
            results.append((test_name, False))
    
    # Summary
    print("\n" + "=" * 60)
    print("πŸ“‹ Test Results Summary")
    print("=" * 60)
    
    passed = 0
    total = len(results)
    
    for test_name, result in results:
        status = "βœ… PASSED" if result else "❌ FAILED"
        print(f"{test_name}: {status}")
        if result:
            passed += 1
    
    print(f"\nOverall: {passed}/{total} tests passed")
    
    if passed == total:
        print("πŸŽ‰ All tests passed! CoT integration is working correctly.")
    else:
        print("⚠️  Some tests failed. Please check the implementation.")
    
    return passed == total

if __name__ == "__main__":
    try:
        success = asyncio.run(main())
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\n⏹️  Tests interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ Test suite failed: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)