File size: 5,258 Bytes
022a8c8
 
 
 
 
87f1c74
f11c554
022a8c8
 
76dae34
 
022a8c8
 
e1bf1f2
 
5c0fd51
e1bf1f2
5c0fd51
022a8c8
 
a9243a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c424219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1cae92
885c512
a9243a6
 
 
 
 
4279e53
a9243a6
4066fdd
 
 
 
 
 
a9243a6
 
 
1ac7e59
 
a9243a6
1ac7e59
a9243a6
4066fdd
1ac7e59
 
 
 
a9243a6
 
1ac7e59
 
4066fdd
 
 
1ac7e59
4066fdd
a9243a6
1ac7e59
 
a9243a6
1ac7e59
 
 
 
a9243a6
1ac7e59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4066fdd
1ac7e59
 
 
 
a9243a6
1ac7e59
 
 
a9243a6
 
 
4278cab
1ac7e59
9f36b00
4278cab
a8bf13e
1ac7e59
e946edc
4066fdd
 
1ac7e59
 
 
 
 
 
 
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

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 random
import time
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import uvicorn

class AIStateManager:
    def __init__(self):
        self.state = "awake"
        self.research_tasks = ["Explore AI Ethics", "Find latest AI models", "Investigate quantum computing"]
        self.current_task = None
        self.heartbeat_count = 0
        self.clients = set()

    async def set_state(self, new_state):
        """Thread-safe state change with logging."""
        print(f"[STATE CHANGE] {self.state}{new_state}")
        self.state = new_state
        await self.broadcast(f"State changed to {new_state}")

    async def broadcast(self, message):
        """Broadcast message to all connected clients."""
        for client in list(self.clients):
            try:
                await client.send_text(message)
            except Exception as e:
                print(f"Broadcast error: {e}")
                self.clients.remove(client)

    async def research_cycle(self):
        """Manages research state tasks."""
        while True:
            await asyncio.sleep(5)  # Longer interval for visibility
            
            # State-based logic
            if self.state == "awake":
                self.heartbeat_count += 1
                if self.heartbeat_count >= 3:
                    await self.set_state("research")
            
            elif self.state == "research":
                if self.research_tasks:
                    task = self.research_tasks.pop(0)
                    await self.broadcast(f"Researching: {task}")
                    
                    # Simulate task work
                    await asyncio.sleep(3)
                    
                    # Random chance of generating follow-up
                    if random.random() < 0.3:
                        await self.broadcast(f"Question about {task}")
                else:
                    await self.set_state("sleeping")
            
            elif self.state == "sleeping":
                await self.broadcast("System in sleep mode")
                await asyncio.sleep(10)  # Longer sleep
                
                # Reset after sleep
                self.research_tasks = ["Explore AI Ethics", "Find latest AI models", "Investigate quantum computing"]
                await self.set_state("awake")
                self.heartbeat_count = 0

# FastAPI Setup
app = FastAPI()
ai_manager = AIStateManager()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    ai_manager.clients.add(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await ai_manager.broadcast(f"Received: {data}")
    except Exception as e:
        print(f"WebSocket error: {e}")
    finally:
        ai_manager.clients.remove(websocket)

@app.on_event("startup")
async def startup_event():
    """Start research cycle on app startup."""
    asyncio.create_task(ai_manager.research_cycle())
     

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

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