kdevoe commited on
Commit
6760e8e
·
verified ·
1 Parent(s): 3c0f819

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
3
+ from langchain.memory import ConversationBufferMemory
4
+ from langchain.prompts import PromptTemplate
5
+
6
+ # Load the tokenizer and model for t5-base
7
+ tokenizer = T5Tokenizer.from_pretrained("t5-base")
8
+ model = T5ForConditionalGeneration.from_pretrained("t5-base")
9
+
10
+ # Set up conversational memory using LangChain's ConversationBufferMemory
11
+ memory = ConversationBufferMemory()
12
+
13
+ # Define the chatbot function with memory
14
+ def chat_with_t5(input_text):
15
+ # Retrieve conversation history and append the current user input
16
+ conversation_history = memory.load_memory_variables({})['history']
17
+
18
+ # Combine the history with the current user input
19
+ # For regular T5, we need to prompt the model differently since it's not instruction-tuned like FLAN-T5
20
+ # Using a simple summarization prompt format as an example, you can modify as needed
21
+ full_input = f"User: {input_text}\nAssistant:"
22
+
23
+ if conversation_history:
24
+ full_input = f"Previous conversation: {conversation_history}\n{full_input}"
25
+
26
+ # Tokenize the input for the model
27
+ input_ids = tokenizer.encode(full_input, return_tensors="pt")
28
+
29
+ # Generate the response from the model
30
+ outputs = model.generate(input_ids, max_length=200, num_return_sequences=1)
31
+
32
+ # Decode the model output
33
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
34
+
35
+ # Update the memory with the user input and model response
36
+ memory.save_context({"input": input_text}, {"output": response})
37
+
38
+ return response
39
+
40
+ # Set up the Gradio interface
41
+ interface = gr.Interface(
42
+ fn=chat_with_t5,
43
+ inputs=gr.Textbox(label="Chat with T5-Base"),
44
+ outputs=gr.Textbox(label="T5-Base's Response"),
45
+ title="T5-Base Chatbot with Memory",
46
+ description="This is a simple chatbot powered by the T5-base model with conversational memory, using LangChain.",
47
+ )
48
+
49
+ # Launch the Gradio app
50
+ interface.launch()