test / app.py
ritujadebnath's picture
Update app.py
349cbcc verified
Raw History Blame Contribute Delete
1.38 kB
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# Load the pre-trained model and tokenizer
model_name = "microsoft/DialoGPT-medium"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Initialize conversation history
conversation_history = []
def chat():
print("Welcome to the chatbot! Type 'exit' to end the conversation.")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
break
# Tokenize the user input and add the EOS token
new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
# Append the new user input to the chat history
conversation_history.append(new_user_input_ids)
# Concatenate chat history and generate response
bot_input_ids = torch.cat(conversation_history, dim=-1)
chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
# Convert the response tokens to text
bot_response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"Bot: {bot_response}")
# Append the bot response to the chat history
conversation_history.append(chat_history_ids)
if __name__ == "__main__":
chat()