File size: 1,791 Bytes
b36da2d
6e0077a
b36da2d
 
 
6e0077a
 
 
 
 
 
b36da2d
 
 
 
 
 
 
 
 
 
6e0077a
b36da2d
 
6e0077a
 
 
b36da2d
 
6e0077a
b36da2d
 
 
6e0077a
 
 
154634b
eb5a023
b36da2d
 
 
154634b
 
b36da2d
 
 
 
154634b
6597aa1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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)