the-confused-coder's picture
Update app.py
eb5a023 verified
from langchain_google_genai import ChatGoogleGenerativeAI
import os, streamlit as st
from dotenv import load_dotenv
# function for clearing user input after submit button press
def clear_txt_on_submit():
st.session_state.usr_text = st.session_state.txt_input
st.session_state.txt_input = ''
# api key config
load_dotenv()
os.environ["GOOGLE_API_KEY"] = os.getenv('GOOGLE_API_KEY')
# using gemini
llm_gemini = ChatGoogleGenerativeAI(model="gemini-pro")
# page config
st.set_page_config(
page_title="Chatbot",
page_icon="πŸ€–"
)
# using session state for storing chat history and user input text
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = []
if 'usr_text' not in st.session_state:
st.session_state['usr_text'] = ''
# other page configs
st.title("Basic Chatbot with History")
st.text_input("Enter Query", key='txt_input', on_change=clear_txt_on_submit)
submit_button = st.button("Submit")
# action on user entering text and pressing Submit button
if submit_button and st.session_state['usr_text']:
response = llm_gemini.invoke(st.session_state['usr_text'])
st.subheader("Answer:")
st.write(response.content)
st.session_state.chat_history.append(f'User: {st.session_state["usr_text"]} \nAI: {response.content}')
# for displaying chat history
chat_history_text = "\n\n".join(st.session_state.chat_history)
history_container = st.empty()
history_container.text_area("**Chat History**", value=chat_history_text, height=300)
# button for clearing chat history
clr_btn = st.button("Clear Chat History")
if clr_btn:
st.session_state['chat_history']=[]
chat_history_text = "\n\n".join(st.session_state.chat_history)
history_container.text_area("**Chat History**", value=chat_history_text, height=300)