Spaces:
No application file
No application file
| # Import necessary libraries | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import torch | |
| # Load pre-trained model and tokenizer | |
| model_name = 'microsoft/DialoGPT-medium' | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| model = AutoModelForCausalLM.from_pretrained(model_name) | |
| def generate_response(user_input, chat_history_ids=None): | |
| # Encode the new user input, add the eos_token and return a tensor in Pytorch | |
| new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt') | |
| # Append the new user input tokens to the chat history, | |
| # pass the tokens to the model, and get the response | |
| bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if chat_history_ids is not None else new_user_input_ids | |
| chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id) | |
| # Decode the generated response from the model | |
| response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) | |
| return response, chat_history_ids | |
| # Example usage: | |
| # response, chat_history_ids = generate_response("Hello, how are you?") | |
| # print(response) | |