File size: 4,833 Bytes
5326cba | 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 | """
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
|