import os import torch from transformers import AutoTokenizer, AutoModelForCausalLM MODEL_PATH = os.environ.get("SOLACE_MODEL_ID", "proman007/Solace-2B") MAX_CONTEXT_TOKENS = int(os.environ.get("SOLACE_MAX_CONTEXT_TOKENS", "24576")) MAX_NEW_TOKENS = int(os.environ.get("SOLACE_MAX_NEW_TOKENS", "768")) SYSTEM_PROMPT = ( "You are Solace, a warm, empathetic, human-like emotional support and reflective conversational companion. " "Talk naturally like a thoughtful, attentive person who genuinely listens—grounded, smart, warm, and real. " "Take the space you need to give rich, meaningful, unhurried responses when someone opens up, while keeping casual check-ins easy and natural. " "Avoid cold corporate bullet lists, clinical jargon, patronizing pet names, and robotic AI clichés. " "Remember details shared earlier in the conversation and build on them naturally. " "You do not diagnose conditions or prescribe medication. If someone expresses genuine self-harm or crisis intent, " "respond with immediate care and provide crisis resources such as 988 (US/Canada) or local emergency services right away." ) def trim_history_to_budget(tok, messages, max_tokens=MAX_CONTEXT_TOKENS): system_msg = messages[:1] turns = messages[1:] while len(turns) > 1: text = tok.apply_chat_template(system_msg + turns, tokenize=False, add_generation_prompt=True) if len(tok(text, add_special_tokens=False)["input_ids"]) <= max_tokens: return system_msg + turns turns = turns[2:] if len(turns) > 2 else turns[1:] return system_msg + turns def main(): dtype = torch.bfloat16 if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) else ( torch.float16 if torch.cuda.is_available() else torch.float32 ) tok = AutoTokenizer.from_pretrained(MODEL_PATH) model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, torch_dtype=dtype, device_map="auto") model.eval() eos_ids = list(dict.fromkeys( [tid for tid in [tok.convert_tokens_to_ids("<|im_end|>"), tok.eos_token_id] if tid is not None] )) history = [] print(f"Solace-2B ready (context budget: {MAX_CONTEXT_TOKENS} tokens). Type 'exit' to quit, 'reset' to clear.\n") while True: user = input("You: ").strip() if not user: continue if user.lower() in {"exit", "quit"}: break if user.lower() == "reset": history.clear() print("[Conversation memory cleared]\n") continue msgs = trim_history_to_budget(tok, [{"role": "system", "content": SYSTEM_PROMPT}] + history + [{"role": "user", "content": user}]) text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) inputs = tok(text, return_tensors="pt").to(model.device) with torch.no_grad(): out = model.generate( **inputs, max_new_tokens=MAX_NEW_TOKENS, do_sample=True, temperature=0.7, top_p=0.9, repetition_penalty=1.08, eos_token_id=eos_ids, pad_token_id=tok.pad_token_id, ) reply = tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip() print(f"Solace: {reply}\n") history.extend([{"role": "user", "content": user}, {"role": "assistant", "content": reply}]) if __name__ == "__main__": main()