|
|
|
|
|
from langchain_openai import OpenAI
|
|
from langchain.chains import ConversationChain
|
|
from langchain.chains.conversation.memory import (ConversationBufferMemory,
|
|
ConversationSummaryMemory,
|
|
ConversationBufferWindowMemory
|
|
)
|
|
import tiktoken
|
|
from langchain.memory import ConversationTokenBufferMemory
|
|
import streamlit as st
|
|
from streamlit_chat import message
|
|
import os
|
|
|
|
|
|
|
|
|
|
if 'conversation' not in st.session_state:
|
|
st.session_state['conversation'] =None
|
|
if 'messages' not in st.session_state:
|
|
st.session_state['messages'] =[]
|
|
|
|
|
|
|
|
|
|
st.set_page_config(page_title="Chat GPT Clone", page_icon=":robot_face:")
|
|
st.markdown("<h1 style='text-align: center;'>How can I assist you? </h1>", unsafe_allow_html=True)
|
|
st.sidebar.title("😎")
|
|
|
|
summarise_button = st.sidebar.button("Summarise the conversation", key="summarise")
|
|
if summarise_button:
|
|
summarise_placeholder = st.sidebar.write("Nice chatting with you my friend ❤️:\n\n"+st.session_state['conversation'].memory.buffer)
|
|
|
|
|
|
def getresponse(userInput):
|
|
"""
|
|
This function takes user input and api key as arguments, and returns the model's response.
|
|
"""
|
|
if st.session_state['conversation'] is None:
|
|
llm = OpenAI(
|
|
temperature=0,
|
|
|
|
|
|
model_name='gpt-3.5-turbo-instruct'
|
|
)
|
|
|
|
|
|
st.session_state['conversation'] = ConversationChain(
|
|
llm=llm,
|
|
verbose=True,
|
|
memory=ConversationSummaryMemory(llm=llm)
|
|
)
|
|
|
|
response=st.session_state['conversation'].predict(input=userInput)
|
|
print(st.session_state['conversation'].memory.buffer)
|
|
return response
|
|
|
|
|
|
def clear():
|
|
"""
|
|
This function clears the conversation and messages from the session state.
|
|
"""
|
|
if st.session_state['conversation']:
|
|
st.session_state['conversation'].memory.clear()
|
|
st.session_state['messages'] =[]
|
|
|
|
|
|
|
|
|
|
|
|
response_container = st.container()
|
|
container = st.container()
|
|
|
|
|
|
|
|
|
|
with container:
|
|
with st.form(key='my_form', clear_on_submit=True):
|
|
user_input = st.text_area("Your question goes here:", key='input', height=100)
|
|
col1, col2 = st.columns(2)
|
|
with col1:
|
|
submit_button = st.form_submit_button(label='Send')
|
|
with col2:
|
|
clear_button = st.form_submit_button(label="Clear")
|
|
|
|
|
|
if submit_button:
|
|
st.session_state['messages'].append(user_input)
|
|
model_response=getresponse(user_input)
|
|
st.session_state['messages'].append(model_response)
|
|
|
|
|
|
with response_container:
|
|
for i in range(len(st.session_state['messages'])):
|
|
if (i % 2) == 0:
|
|
message(st.session_state['messages'][i], is_user=True, key=str(i) + '_user')
|
|
else:
|
|
message(st.session_state['messages'][i], key=str(i) + '_AI')
|
|
|
|
|
|
if clear_button:
|
|
clear()
|
|
|