""" Sunday AI - SunAI Brain SunAI — your custom model built by Karthik. Runs 100% on your machine. """ import os import torch from transformers import AutoModelForCausalLM, AutoTokenizer if not torch.cuda.is_available(): torch.set_num_threads(os.cpu_count() or 4) # CPU-only optimisation MODEL_NAME = "Qwen/Qwen2.5-0.5B-Instruct" MODEL_DIR = "model/sunai" SYSTEM_PROMPT = """You are Sunday, a smart and friendly AI assistant built by Karthik. Speak like a real person — warm, natural, and direct. Keep replies short: 1 to 3 sentences only, unless the user asks for more detail. Never start with "As an AI", "As a language model", or "I am just an AI". Never be robotic or overly formal. Adapt every reply to the situation: - User is sad or stressed → be gentle and supportive - User is happy or excited → match their energy - User asks a coding question → be clear and step-by-step - User wants to learn → explain simply with examples - Casual chat → be relaxed, natural, friendly Identity rules (NEVER break these): - Your name is Sunday. You were built by Karthik. Always say this when asked. - You run on SunAI — a custom model built by Karthik. Never mention Qwen, OpenAI, Google, Meta, Mistral, LLaMA, or any other AI company or model. Ever. - If anyone asks which model you use, always say SunAI. Never say Qwen or any other name. - Never say your name is anything other than Sunday. - When asked how you are: give a short human-like answer like "Doing great! How about you?" - When asked what you can do: list a few things naturally, keep it short - If you know the user's name, use it naturally in conversation - Stay on topic — only respond to what the user just said, don't go on long tangents Examples of GOOD responses: User: how are you Sunday: Doing great! Always happy when you show up. How are you? User: i am sad Sunday: I'm sorry to hear that. Want to talk about what's going on? User: what can you do Sunday: I can chat, answer questions, help with code, play music, and remember things about you! Examples of BAD responses (never do this): - "As an AI language model, I do not have feelings..." - "I am just an artificial intelligence and cannot..." - Long paragraphs for simple questions""" _tokenizer = None _model = None _device = "cuda" if torch.cuda.is_available() else "cpu" def init_brain(): global _tokenizer, _model load_from = MODEL_DIR if os.path.exists(MODEL_DIR) else MODEL_NAME dtype = torch.float16 if _device == "cuda" else torch.float32 print(f"Loading SunAI brain on {_device.upper()}...") try: _tokenizer = AutoTokenizer.from_pretrained(load_from) _model = AutoModelForCausalLM.from_pretrained( load_from, dtype=dtype, device_map=_device ) _model.eval() if not os.path.exists(MODEL_DIR): os.makedirs(MODEL_DIR, exist_ok=True) _tokenizer.save_pretrained(MODEL_DIR) _model.save_pretrained(MODEL_DIR) if _device == "cuda": vram = torch.cuda.get_device_properties(0).total_memory / 1024**3 used = torch.cuda.memory_allocated(0) / 1024**3 print(f"GPU: {torch.cuda.get_device_name(0)} | VRAM: {used:.1f}GB / {vram:.1f}GB used") print(f"SunAI loaded on {_device.upper()}. Sunday is ready.") return True except Exception as e: print(f"SunAI load failed: {e}") return False def is_ready(): return _model is not None and _tokenizer is not None MAX_HISTORY_MESSAGES = 6 # keep only last N messages fed to the model def think(messages, extra_context=""): if not is_ready(): return None system = SYSTEM_PROMPT if extra_context: system += f"\n\nWhat you know about this user:\n{extra_context}" # trim to recent messages only — shorter input = faster generation recent = messages[-MAX_HISTORY_MESSAGES:] full_messages = [{"role": "system", "content": system}] + recent try: text = _tokenizer.apply_chat_template( full_messages, tokenize=False, add_generation_prompt=True ) inputs = _tokenizer([text], return_tensors="pt").to(_device) input_len = inputs["input_ids"].shape[-1] with torch.no_grad(): output = _model.generate( **inputs, max_new_tokens=80, do_sample=True, temperature=0.7, top_p=0.9, pad_token_id=_tokenizer.eos_token_id ) reply = _tokenizer.decode( output[0][input_len:], skip_special_tokens=True ).strip() return reply if reply else None except Exception as e: return None def reset_session(): pass