broadfield commited on
Commit
e959996
·
verified ·
1 Parent(s): fd4bcdc

Adding file test: 028bdf26-de04-4b72-b3b4-89ba1d2f6a6f

Browse files
Files changed (1) hide show
  1. chatbot_logic.py +26 -0
chatbot_logic.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Import necessary libraries
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import torch
5
+
6
+ # Load pre-trained model and tokenizer
7
+ model_name = 'microsoft/DialoGPT-medium'
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForCausalLM.from_pretrained(model_name)
10
+
11
+ def generate_response(user_input, chat_history_ids=None):
12
+ # Encode the new user input, add the eos_token and return a tensor in Pytorch
13
+ new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt')
14
+
15
+ # Append the new user input tokens to the chat history,
16
+ # pass the tokens to the model, and get the response
17
+ 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
18
+ chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
19
+
20
+ # Decode the generated response from the model
21
+ response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
22
+ return response, chat_history_ids
23
+
24
+ # Example usage:
25
+ # response, chat_history_ids = generate_response("Hello, how are you?")
26
+ # print(response)