import os import torch import gradio as gr 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." ) 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() def trim_history_to_budget(messages, max_tokens=MAX_CONTEXT_TOKENS): """Keep system prompt + as many recent turns as fit within max_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 respond(message, history): msgs = [{"role": "system", "content": SYSTEM_PROMPT}] for item in history: if isinstance(item, dict): msgs.append({"role": item["role"], "content": item["content"]}) else: u, a = item if u: msgs.append({"role": "user", "content": u}) if a: msgs.append({"role": "assistant", "content": a}) msgs.append({"role": "user", "content": message}) msgs = trim_history_to_budget(msgs) text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) inputs = tok(text, return_tensors="pt").to(model.device) eos_ids = [tid for tid in [tok.convert_tokens_to_ids("<|im_end|>"), tok.eos_token_id] if tid is not None] 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=list(dict.fromkeys(eos_ids)), pad_token_id=tok.pad_token_id, ) reply = tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip() return reply demo = gr.ChatInterface( fn=respond, title="Solace-2B — Human-Centered Reflective Conversational Companion", description=( "Warm, long-context conversational support trained on Qwen3.5-2B with 100% commercial-licensed datasets. " "Not a replacement for licensed clinical care; if in crisis call/text 988 in the US/Canada or local emergency services." ), ) if __name__ == "__main__": demo.launch()