psychology_bot / app.py
Israr-dawar's picture
Update app.py
b3bcecc
import streamlit as st
from streamlit_chat import message
from langchain.llms import CTransformers
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains import ConversationChain
from langchain.schema.output_parser import StrOutputParser
from langchain.memory import ConversationBufferMemory
from langchain import PromptTemplate, LLMChain
#create llm
llm = CTransformers(model="Israr-dawar/psychology_chatbot_quantized_model",model_type="llama",
config={'max_new_tokens':128,'temperature':0.01})
def should_finish(next_input):
"""Returns True if the next input indicates that the user wants to finish the conversation."""
return next_input.lower() == "exit"
# Create a prompt template
template = """
     You are a good psychologist. Please share your thoughts on the following text:
     `{text}`
     Now, could you please ask a question related to this `{text}`?
"""
prompt = PromptTemplate(template=template, input_variables=["text"])
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
# LLM chain with ConversationalBufferMemory object
chain = LLMChain(prompt=prompt, llm=llm, memory = memory, output_parser = StrOutputParser())
st.title("Psychology ChatBot 🧑🏽‍⚕️")
def conversation_chat(query):
result = chain({"text": query, "chat_history": st.session_state['history']})
print(result) # Add this line
print("restult: ",result)
st.session_state['history'].append((query, result["answer"]))
return result["answer"]
def initialize_session_state():
if 'history' not in st.session_state:
st.session_state['history'] = []
if 'generated' not in st.session_state:
st.session_state['generated'] = ["Hello! Ask me anything about 🤗"]
if 'past' not in st.session_state:
st.session_state['past'] = ["Hey! 👋"]
def display_chat_history():
reply_container = st.container()
container = st.container()
with container:
with st.form(key='my_form', clear_on_submit=True):
user_input = st.text_input("Question:", placeholder="I am a psychologist", key='input')
submit_button = st.form_submit_button(label='Send')
if submit_button and user_input:
output = conversation_chat(user_input)
st.session_state['past'].append(user_input)
st.session_state['generated'].append(output)
if st.session_state['generated']:
with reply_container:
for i in range(len(st.session_state['generated'])):
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="thumbs")
message(st.session_state["generated"][i], key=str(i), avatar_style="fun-emoji")
# Initialize session state
initialize_session_state()
# Display chat history
display_chat_history()