from transformers import GPT2Tokenizer, GPT2Model #pipe = pipeline("text-generation", model="distilbert/distilgpt2") # Load model directly tokenizer = GPT2Tokenizer.from_pretrained('distilgpt2') model = GPT2Model.from_pretrained('distilgpt2') # Set the pad_token to eos_token (since distilgpt2 does not have a pad_token by default) tokenizer.pad_token = tokenizer.eos_token # set custom system message tailored to mental health context system_message = "You are a compassionate and empathetic mental health chatbot. Your goal is to listen carefully, provide comforting support, and offer helpful guidance to users who are feeling down, anxious, or stressed. Always respond with kindness and understanding, making the user feel safe and heard." def generate_response(user_prompt): # combine system_message with user input to form prompt prompt = f"{system_message}\n\nUser: {user_prompt}\nBot: " # Tokenize and generate a response inputs = tokenizer.encode_plus(prompt, return_tensors="pt", padding=True, truncation=True) # Extract input_ids and attention_mask from the tokenizer output input_ids = inputs["input_ids"] attention_mask = inputs["attention_mask"] outputs = model.generate( input_ids=input_ids, attention_mask=attention_mask, do_sample=True, max_length=50, temperature=0.7, top_p=0.9, pad_token_id=tokenizer.eos_token_id ) decoded_output = tokenizer.decode(outputs[0], clean_up_tokenization_spaces=True) print(decoded_output) return decoded_output user_prompt = "I'm feeling really stressed and anxious." response = generate_response(user_prompt) print(response)