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 = """ AI State Machine

AI State Machine

""" ###### 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)