Chris4K's picture
Update app.py
4066fdd verified
raw
history blame
8.05 kB
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)