File size: 7,830 Bytes
022a8c8
 
 
 
 
87f1c74
f11c554
022a8c8
 
76dae34
 
022a8c8
 
e1bf1f2
 
5c0fd51
e1bf1f2
5c0fd51
022a8c8
 
a9243a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
600da4a
a9243a6
 
 
 
 
 
 
 
885c512
a9243a6
 
 
 
 
457a598
 
885c512
 
 
 
 
c1cae92
885c512
 
 
 
 
 
 
 
c1cae92
 
885c512
a9243a6
 
 
 
 
4279e53
a9243a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f36b00
a9243a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e946edc
a9243a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4278cab
a9243a6
9f36b00
4278cab
e946edc
 
 
 
 
a9243a6
9f36b00
a9243a6
 
 
 
457a598
a9243a6
 
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

from langfuse import Langfuse
from langfuse.decorators import observe, langfuse_context

from config.config import settings
from services.llama_generator import LlamaGenerator
import os

# Initialize Langfuse
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-04d2302a-aa5c-4870-9703-58ab64c3bcae"
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-d34ea200-feec-428e-a621-784fce93a5af"
os.environ["LANGFUSE_HOST"] = "https://chris4k-langfuse-template-space.hf.space"  # 🇪🇺 EU region

try:
    langfuse = Langfuse()
except Exception as e:
    print("Langfuse Offline")
    


########

html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI State Machine</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; }
        #chatbox { width: 80%; height: 300px; border: 1px solid #ccc; overflow-y: auto; margin: 20px auto; padding: 10px; }
        #inputbox { width: 70%; padding: 5px; }
        button { padding: 5px 10px; }
    </style>
</head>
<body>
    <h2>AI State Machine</h2>
    <div id="chatbox"></div>
    <input type="text" id="inputbox" placeholder="Type your message...">
    <button onclick="sendMessage()">Send</button>

    <script>
        let ws = new WebSocket("wss://chris4k-a-i-statemachine.hf.space/ws");

        ws.onmessage = (event) => {
            let chatbox = document.getElementById("chatbox");
            chatbox.innerHTML += `<p>${event.data}</p>`;
            chatbox.scrollTop = chatbox.scrollHeight;
        };

        function sendMessage() {
        console.log("sending .... ")
            let input = document.getElementById("inputbox");
            let message = input.value.trim();
            if (message) {
                ws.send(message);
                input.value = "";
            }
        }



      ws.onopen = function() {
        console.log("WebSocket connected!");
        ws.send("Hello AI!"); // Send message to backend once the connection is open.
      };
    
      ws.onmessage = function(event) {
        console.log("Message from server: ", event.data); // Logs the AI/system message.
      };
    
      ws.onerror = function(error) {
        console.error("WebSocket Error: ", error);
      };    
 
        
    </script>
</body>
</html>
"""
######

import asyncio
import queue
import threading
import random
import time
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import uvicorn

# FastAPI App
app = FastAPI()

class AIStateManager:
    def __init__(self):
        self.state = "awake"
        self.msg_queue = queue.Queue()
        self.heartbeat_count = 0
        self.lock = threading.Lock()
        self.clients = set()

        # Research Task List
        self.research_tasks = ["Explore AI Ethics", "Find latest AI models", "Investigate quantum computing"]
        self.current_task = None

    def set_state(self, new_state):
        with self.lock:
            print(f"[STATE CHANGE] {self.state}{new_state}")
            self.state = new_state
            self.add_message("system", f"State changed to {new_state}")

    def receive_message(self, sender, message):
        """Adds messages to queue and resets heartbeat if human sends input."""
        with self.lock:
            self.msg_queue.put((sender, message))
            if sender == "human":
                self.heartbeat_count = 0
                if self.state != "awake":
                    self.set_state("awake")

    def add_message(self, sender, message):
        """AI or System can add messages to queue."""
        with self.lock:
            self.msg_queue.put((sender, message))

    def process_messages(self):
        """Processes messages in queue."""
        while not self.msg_queue.empty():
            sender, message = self.msg_queue.get()
            print(f"[{sender.upper()}] {message}")
            asyncio.create_task(self.broadcast(f"[{sender.upper()}] {message}"))

    async def broadcast(self, message):
        """Sends message to all connected WebSocket clients."""
        for ws in self.clients:
            await ws.send_text(message)

    async def heartbeat(self):
        """Basic heartbeat loop."""
        while True:
            await asyncio.sleep(1)  # One 'beat'
            with self.lock:
                self.heartbeat_count += 1
                self.process_messages()

    async def consciousness(self):
        """Controls research/sleep cycle."""
        while True:
            await asyncio.sleep(2)  # Consciousness checks every 2 sec
            with self.lock:
                if self.state == "awake":
                    if self.heartbeat_count >= 5:
                        self.set_state("research")
                        asyncio.create_task(self.run_research())

                elif self.state == "research":
                    if not self.research_tasks:  # If no tasks left, move to sleep
                        self.set_state("sleeping")
                        asyncio.create_task(self.run_sleeping())

                elif self.state == "sleeping":
                    if self.heartbeat_count >= 20:
                        self.set_state("research")  # Restart research after sleep
                        asyncio.create_task(self.run_research())
                print(self.state)

    async def run_research(self):
        """Runs research tasks in order."""
        while self.state == "research" and self.research_tasks:
            await asyncio.sleep(3)
            self.current_task = self.research_tasks.pop(0)
            self.add_message("ai", f"Researching: {self.current_task}")
            if random.random() < 0.3:  # AI might ask a follow-up question
                self.add_message("ai", f"Question: What do you think about {self.current_task}?")
            self.process_messages()

    async def run_sleeping(self):
        """Runs self-training until state changes."""
        while self.state == "sleeping":
            await asyncio.sleep(5)
            self.add_message("system", "Self-training in progress...")
            self.process_messages()

    def modify_research_tasks(self):
        """Background process to edit research tasks dynamically (subconscious)."""
        while True:
            time.sleep(10)  # Runs every 10 seconds
            with self.lock:
                if self.state == "research" and random.random() < 0.5:
                    new_task = f"Investigate {random.choice(['AI Bias', 'Neural Networks', 'Data Privacy'])}"
                    self.research_tasks.append(new_task)
                    self.add_message("system", f"New research task added: {new_task}")

# Initialize AI Manager
ai_manager = AIStateManager()

# Start Heartbeat and Consciousness in separate threads
threading.Thread(target=lambda: asyncio.run(ai_manager.heartbeat()), daemon=True).start()
threading.Thread(target=lambda: asyncio.run(ai_manager.consciousness()), daemon=True).start()
threading.Thread(target=ai_manager.modify_research_tasks, daemon=True).start()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    """WebSocket connection handler."""
    await websocket.accept()
    ai_manager.clients.add(websocket)
    try:
        while True:
            data = await websocket.receive_text()  # Receive messages from the user.
            print(f"Received: {data}")  # Debug: Print the received data.
            ai_manager.receive_message("human", data)  # Send it to the AI manager.
    except Exception as e:
        print(f"Connection closed with error: {e}")
        ai_manager.clients.remove(websocket)

@app.get("/")
async def get():
    """Serve frontend HTML."""
    return HTMLResponse(html)

if __name__ == "__main__":
    uvicorn.run(app, host="localhost", port=8000)