File size: 4,825 Bytes
0739494
0ae88ca
a76a0e4
3dd8a97
6082b65
767cd41
0c0d696
a76a0e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6082b65
a76a0e4
3dd8a97
a76a0e4
 
 
 
 
 
 
 
 
 
 
6082b65
 
a76a0e4
 
6082b65
a76a0e4
 
 
 
6082b65
a76a0e4
6082b65
a76a0e4
 
 
 
6082b65
a76a0e4
 
3dd8a97
a76a0e4
72def17
a76a0e4
 
865ce13
a76a0e4
6082b65
a76a0e4
 
 
 
 
 
 
6082b65
a76a0e4
6e7a990
6082b65
a76a0e4
 
 
 
 
 
6082b65
a76a0e4
 
 
 
 
 
 
 
 
6082b65
a76a0e4
 
6e7a990
a76a0e4
6e7a990
a76a0e4
 
 
 
 
 
 
 
 
3dd8a97
7de379d
6082b65
7de379d
a76a0e4
0b94e1b
a76a0e4
3dd8a97
a76a0e4
 
6082b65
 
a76a0e4
 
 
 
 
0ae88ca
a76a0e4
 
7de379d
0ae88ca
6082b65
a76a0e4
6082b65
0ae88ca
6082b65
0ae88ca
a76a0e4
 
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
import gradio as gr
import google.generativeai as genai
from openai import OpenAI
import os
import numpy as np
from collections import Counter

# --- 1. SYSTEM KONFIGURATION ---
# API Keys sicher laden
GEMINI_KEY = os.getenv("GEMINI_API_KEY")
OPENAI_KEY = os.getenv("OPENAI_API_KEY")

# Clients initialisieren (Fehler abfangen, falls Keys fehlen)
gemini_available = False
openai_client = None

if GEMINI_KEY:
    try:
        genai.configure(api_key=GEMINI_KEY)
        gemini_model = genai.GenerativeModel('gemini-1.5-flash')
        gemini_available = True
    except: pass

if OPENAI_KEY:
    try:
        openai_client = OpenAI(api_key=OPENAI_KEY)
    except: pass

# --- 2. ISAAC KERN (Mathematische Logik) ---
class IsaacBrain:
    def __init__(self, lambda_reg=0.005):
        self.lambda_reg = lambda_reg
        # Initialer Parametervektor (Synapsen)
        self.theta = np.random.randn(5, 1) * 0.05 

    def update_state(self, entropy):
        """
        DAS FEHLTE: Rückkopplung! 
        Hohe Entropie (Chaos) verändert die interne Struktur (Theta).
        """
        # Zufälliges Rauschen basierend auf Entropie injizieren
        noise = np.random.randn(5, 1) * (entropy * 0.02)
        self.theta += noise

    def audit_w_algorithm(self, text):
        """Berechnet Metriken und prüft Stabilität."""
        if not text: return 0.0, 0.0, False
        
        # A. Metriken berechnen
        counts = Counter(text)
        total = len(text)
        probs = [n/total for n in counts.values()]
        h = -sum(p * np.log2(p) for p in probs)
        load = 1.0 / max(h, 0.001) # Schutz vor Div/0
        
        # B. Dynamische Anpassung des Kerns
        self.update_state(h)

        # C. Bedingung dR/dTheta ≈ 0 prüfen
        reg_grad = 2 * self.lambda_reg * self.theta
        # Wenn der Gradient zu groß wird, ist das System instabil
        is_stable = np.allclose(reg_grad, 0, atol=0.05)
        
        return round(h, 4), round(load, 4), is_stable

# Instanz des Kerns
isaac_core = IsaacBrain()

# --- 3. ORCHESTRATOR ---
def master_orchestrator(message, history, platform):
    # Prompting: Die externe KI wird untergeordnet
    system_prompt = (
        f"SYSTEM INSTRUKTION: Du bist NICHT Isaac. Du bist ein Sub-Prozessor (Node: {platform}). "
        f"Isaac ist der übergeordnete Algorithmus. Antworte präzise auf: {message}"
    )
    
    response = ""
    
    # Node Auswahl und Ausführung
    try:
        if platform == "Gemini (Google)":
            if not gemini_available:
                response = "❌ Fehler: Gemini API Key fehlt oder ungültig."
            else:
                resp = gemini_model.generate_content(system_prompt)
                response = resp.text

        elif platform == "GPT-4 (OpenAI)":
            if not openai_client:
                response = "❌ Fehler: OpenAI API Key fehlt."
            else:
                # Syntax für moderne OpenAI v1.0+ Libs
                completion = openai_client.chat.completions.create(
                    model="gpt-4",
                    messages=[{"role": "user", "content": system_prompt}]
                )
                response = completion.choices[0].message.content
        else:
            response = "⚠️ Keine Node ausgewählt."

    except Exception as e:
        response = f"⚠️ Node-Absturz: {str(e)}"

    # Audit durch den Isaac-Kern
    h, l, stable = isaac_core.audit_w_algorithm(response)
    
    if stable:
        status_msg = "🟢 STABIL (dR/dTheta ≈ 0)"
    else:
        status_msg = "⚠️ INSTABIL (Divergenz erkannt)"
        # Optional: Markierung im Text, dass Isaac unzufrieden ist
        response += "\n\n[ISAAC LOG: Antwort hat interne Struktur destabilisiert.]"

    history.append({"role": "user", "content": message})
    history.append({"role": "assistant", "content": response})
    
    return "", history, h, l, status_msg

# --- 4. UI ---
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# 🧬 Isaac: Evolution 4.0 (Multi-Node Nexus)")
    gr.Markdown("Der deterministische Kern (Isaac) nutzt externe LLMs als Sub-Prozessoren.")
    
    with gr.Row():
        platform_select = gr.Radio(
            ["Gemini (Google)", "GPT-4 (OpenAI)"], 
            label="Aktiver Sub-Knoten", 
            value="Gemini (Google)"
        )
    
    chatbot = gr.Chatbot(type="messages", height=400, label="Terminal Output")
    msg = gr.Textbox(placeholder="Befehl an den Nexus...", show_label=False)
    
    with gr.Row():
        h_box = gr.Number(label="Entropie H(θ)")
        l_box = gr.Number(label="Kognitive Last L")
        s_box = gr.Textbox(label="Kern-Integrität")

    msg.submit(master_orchestrator, [msg, chatbot, platform_select], [msg, chatbot, h_box, l_box, s_box])

if __name__ == "__main__":
    demo.launch()