Chris4K's picture
Update app.py
a8bf13e verified
raw
history blame
8.16 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.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):
await websocket.accept()
print("WebSocket connection accepted") # Add explicit logging
ai_manager.clients.add(websocket)
try:
# Send initial welcome message
await websocket.send_text("Connected to AI State Machine")
print("Sent initial welcome message") # Debug logging
while True:
data = await websocket.receive_text()
print(f"Received WebSocket message: {data}") # Explicit receive logging
# Process message through AI manager
ai_manager.receive_message("human", data)
# Ensure broadcast is working
await ai_manager.broadcast(f"Received: {data}")
except Exception as e:
print(f"WebSocket connection 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)