File size: 6,848 Bytes
ae1e90a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Grok Logic Layer with Shared Blackboard Integration
Multi-expert collaboration via evidence store
"""

from typing import List, Dict, Any
from lego_moe import LegoMoE
from shared_blackboard import SharedBlackboard, Arbitrator
import re
import json

class GrokWithBlackboard:
    """
    Grok logic layer with shared blackboard for expert collaboration
    Orchestrates multiple experts via evidence store
    """
    
    def __init__(self, lego_moe: LegoMoE):
        self.moe = lego_moe
        self.blackboard = SharedBlackboard()
        self.arbitrator = Arbitrator(self.blackboard)
        print("✓ Grok with Blackboard initialized")
    
    def parse_intent(self, query: str) -> Dict[str, Any]:
        """Parse query intent (same as before)"""
        query_lower = query.lower()
        
        if any(word in query_lower for word in ['calculate', 'compute', 'multiply', 'add', 'divide', 'subtract', 'times']):
            qtype = 'math_arithmetic'
        elif any(word in query_lower for word in ['if', 'then', 'all', 'some', 'implies']):
            qtype = 'logic_deduction'
        else:
            qtype = 'general_qa'
        
        numbers = [float(n) for n in re.findall(r'\d+\.?\d*', query)]
        operators = re.findall(r'[\+\-\*/×÷]', query)
        
        if 'times' in query_lower or 'multiply' in query_lower:
            operators.append('*')
        if 'divided' in query_lower or 'divide' in query_lower:
            operators.append('/')
        
        if len(numbers) >= 2 and len(operators) >= 1:
            qtype = 'math_arithmetic'
        
        return {
            "type": qtype,
            "entities": {"numbers": numbers, "operators": operators}
        }
    
    def execute_math(self, numbers: List[float], operator: str) -> float:
        """Direct math calculation"""
        if operator == '*':
            return numbers[0] * numbers[1]
        elif operator == '/':
            return numbers[0] / numbers[1] if numbers[1] != 0 else None
        elif operator == '+':
            return numbers[0] + numbers[1]
        elif operator == '-':
            return numbers[0] - numbers[1]
        return None
    
    def run_math_expert(self, query: str, numbers: List[float], operator: str):
        """Math expert writes to blackboard"""
        result = self.execute_math(numbers, operator)
        
        self.blackboard.write_evidence(
            expert="math",
            finding=result,
            method="direct_calculation",
            confidence=1.0,
            scope="calculation",
            metadata={"operation": f"{numbers[0]} {operator} {numbers[1]}"}
        )
    
    def run_logic_expert(self, query: str, numbers: List[float], operator: str):
        """Logic expert validates units/consistency"""
        # Simple validation: check if result makes sense
        result_evidence = self.blackboard.read_evidence(expert_filter="math")
        
        if result_evidence:
            result = result_evidence[0].finding
            
            # Sanity check
            if operator == '*' and result < max(numbers):
                finding = "Result seems incorrect (multiplication should increase)"
                confidence = 0.3
            elif operator == '/' and result > numbers[0]:
                finding = "Result seems incorrect (division should decrease)"
                confidence = 0.3
            else:
                finding = "Result passes sanity checks"
                confidence = 0.95
            
            self.blackboard.write_evidence(
                expert="logic",
                finding=finding,
                method="sanity_check",
                confidence=confidence,
                scope="validation"
            )
    
    def reason_with_blackboard(self, query: str, verbose: bool = True) -> Dict[str, Any]:
        """
        Multi-expert reasoning via blackboard
        
        Returns:
            Arbitrated result with confidence
        """
        if verbose:
            print(f"\n{'='*70}")
            print(f"🧠 GROK WITH BLACKBOARD")
            print(f"{'='*70}")
            print(f"Query: {query}\n")
        
        # Start new request
        request_id = f"req_{hash(query) % 10000}"
        self.blackboard.start_request(request_id)
        
        # Parse intent
        intent = self.parse_intent(query)
        if verbose:
            print(f"Intent: {intent['type']}")
        
        # Orchestrate experts based on intent
        if intent['type'] == 'math_arithmetic':
            numbers = intent['entities']['numbers']
            operators = intent['entities']['operators']
            
            if len(numbers) == 2 and len(operators) == 1:
                if verbose:
                    print(f"\nOrchestrating experts:")
                
                # Math expert
                if verbose:
                    print(f"  1. Math expert calculating...")
                self.run_math_expert(query, numbers, operators[0])
                
                # Logic expert validates
                if verbose:
                    print(f"  2. Logic expert validating...")
                self.run_logic_expert(query, numbers, operators[0])
        
        # Lock blackboard
        self.blackboard.lock()
        
        # Arbitrate
        if verbose:
            print(f"\nArbitration:")
        
        confidence = self.arbitrator.aggregate_confidence()
        conflicts = self.arbitrator.detect_conflicts()
        result = self.arbitrator.synthesize_answer()
        
        if verbose:
            print(f"  Confidence: {confidence:.3f}")
            print(f"  Conflicts: {len(conflicts)}")
            print(f"\n{'='*70}")
            print(f"Answer: {result['answer']}")
            print(f"Confidence: {result['confidence']:.3f}")
            print(f"Primary Expert: {result['primary_expert']}")
            if result['supporting_experts']:
                print(f"Supporting: {', '.join(result['supporting_experts'])}")
            print(f"{'='*70}\n")
        
        return result


def main():
    """Test Grok with Blackboard"""
    print("\n🧠 Grok Logic Layer with Shared Blackboard\n")
    
    # Initialize
    print("Loading LEGO-MoE...")
    moe = LegoMoE()
    
    print("\nInitializing Grok with Blackboard...")
    grok = GrokWithBlackboard(moe)
    
    # Test queries
    test_queries = [
        "What is 15 times 23?",
        "What is 100 divided by 4?",
    ]
    
    for query in test_queries:
        result = grok.reason_with_blackboard(query)
        
        print(f"\nBlackboard Evidence:")
        for evidence in grok.blackboard.get_all_evidence():
            print(f"  {evidence['expert']}: {evidence['finding']} (conf: {evidence['confidence']:.2f})")


if __name__ == "__main__":
    main()