-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot_with_temporary_memory.py
84 lines (67 loc) · 2.51 KB
/
bot_with_temporary_memory.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import streamlit as st
import os
from dotenv import load_dotenv
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
# Load environment variables
load_dotenv()
# Initialize store for chat history
store = {}
def get_session_history(session_id: str) -> BaseChatMessageHistory:
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]
# Initialize LLM and chat chain
@st.cache_resource
def init_chat_chain():
llm = ChatGroq(
model="gemma2-9b-it",
groq_api_key=os.getenv("GROQ_API_KEY")
)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant please answer the question."),
("human", "{input}")
])
chain = prompt | llm
return RunnableWithMessageHistory(
chain,
get_session_history,
)
def main():
st.title("💬 Chatbot with Memory")
# Initialize session state for messages
if "messages" not in st.session_state:
st.session_state.messages = []
st.session_state.session_id = str(hash(str(st.session_state)))
# Initialize chat chain
chat_chain = init_chat_chain()
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("What would you like to know?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Get bot response
with st.chat_message("assistant"):
config = {"configurable": {"session_id": st.session_state.session_id}}
with st.spinner("Thinking..."):
response = chat_chain.invoke(
{"input": prompt},
config=config,
)
# Display bot response
st.markdown(response.content)
# Add bot response to chat history
st.session_state.messages.append(
{"role": "assistant", "content": response.content}
)
if __name__ == "__main__":
main()