File size: 8,050 Bytes
022a8c8
 
 
 
 
87f1c74
f11c554
022a8c8
 
76dae34
 
022a8c8
 
e1bf1f2
 
5c0fd51
e1bf1f2
5c0fd51
022a8c8
 
a9243a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c424219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1cae92
885c512
a9243a6
 
 
 
 
4279e53
a9243a6
 
 
 
 
 
 
 
 
 
 
 
4066fdd
 
 
 
 
 
 
 
 
a9243a6
 
 
4066fdd
a9243a6
4066fdd
 
a9243a6
4066fdd
 
a9243a6
 
4066fdd
a9243a6
4066fdd
a9243a6
4066fdd
 
a9243a6
 
 
4066fdd
a9243a6
4066fdd
a9243a6
4066fdd
a9243a6
4066fdd
a9243a6
 
4066fdd
a9243a6
4066fdd
a9243a6
 
 
4066fdd
 
 
 
 
 
 
a9243a6
 
 
 
 
4066fdd
a9243a6
4066fdd
9f36b00
a9243a6
 
 
4066fdd
 
a9243a6
4066fdd
a9243a6
 
4066fdd
a9243a6
 
 
 
4066fdd
a9243a6
 
 
 
4066fdd
a9243a6
e946edc
4066fdd
a9243a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4278cab
4066fdd
 
 
9f36b00
4278cab
a8bf13e
ab8e714
4066fdd
e946edc
4066fdd
 
 
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
226
227
228
229
230
231
232

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.onopen = function() {
    console.log("WebSocket connected!");
    ws.send("Hello AI!"); // Send initial message
};

ws.onmessage = (event) => {
    console.log("Message from server: ", event.data);
    let chatbox = document.getElementById("chatbox");
    chatbox.innerHTML += `<p>${event.data}</p>`;
    chatbox.scrollTop = chatbox.scrollHeight;
};

ws.onerror = function(error) {
    console.error("WebSocket Error: ", error);
};

function sendMessage() {
    let input = document.getElementById("inputbox");
    let message = input.value.trim();
    if (message) {
        ws.send(message);
        input.value = "";
    }
}   
 
        
    </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()

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

class AIStateManager:
    def __init__(self):
        self.state = "awake"
        self.msg_queue = asyncio.Queue()  # Use asyncio.Queue for async operations
        self.heartbeat_count = 0
        self.lock = asyncio.Lock()  # Use asyncio.Lock for async locking
        self.clients = set()  # Set to store WebSocket clients

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

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

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

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

    async def broadcast(self, message):
        """Sends message to all connected WebSocket clients."""
        print(f"Broadcasting: {message}")
        for client in list(self.clients):  # Create a copy to avoid runtime modification
            try:
                await client.send_text(message)
            except Exception as e:
                print(f"Error broadcasting to client: {e}")
                self.clients.remove(client)

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

    async def consciousness(self):
        """Controls research/sleep cycle."""
        while True:
            print("Consciousness cycle")
            await self.broadcast("Consciousness cycle...")
            await asyncio.sleep(2)  # Consciousness checks every 2 sec
            async with self.lock:
                if self.state == "awake":
                    if self.heartbeat_count >= 5:
                        await 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
                        await self.set_state("sleeping")
                        asyncio.create_task(self.run_sleeping())

                elif self.state == "sleeping":
                    if self.heartbeat_count >= 20:
                        await 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):
    await websocket.accept()
    print("Initial message sent to WebSocket") 

    ai_manager.clients.add(websocket)  # Add client to set
    try:
        while True:
            data = await websocket.receive_text()
            print(f"BACKEND RECEIVED: {data}")
            await ai_manager.receive_message("human", data)
    except Exception as e:
        print(f"WebSocket error: {e}")
    finally:
        ai_manager.clients.remove(websocket)  # Remove client when connection closes

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

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