Create context_aware_chatbot
Browse files- pages/context_aware_chatbot +45 -0
pages/context_aware_chatbot
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import utils
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from streaming import StreamHandler
|
| 4 |
+
|
| 5 |
+
from langchain_openai import ChatOpenAI
|
| 6 |
+
from langchain.chains.conversation.base import ConversationChain
|
| 7 |
+
from langchain.memory.buffer import ConversationBufferMemory
|
| 8 |
+
from langchain.memory import ConversationSummaryMemory
|
| 9 |
+
|
| 10 |
+
st.set_page_config(page_title="Context aware chatbot", page_icon="🧠")
|
| 11 |
+
st.header('Context aware chatbot')
|
| 12 |
+
st.write('Enhancing Chatbot Interactions through Context Awareness')
|
| 13 |
+
|
| 14 |
+
class ContextChatbot:
|
| 15 |
+
|
| 16 |
+
def __init__(self):
|
| 17 |
+
self.openai_model = utils.configure_openai()
|
| 18 |
+
|
| 19 |
+
@st.cache_resource
|
| 20 |
+
def setup_chain(_self):
|
| 21 |
+
summarizer = ChatOpenAI(model_name= "gpt-4o", temperature=0, streaming=True)
|
| 22 |
+
memory = ConversationSummaryMemory(llm = summarizer)
|
| 23 |
+
llm = ChatOpenAI(model_name=_self.openai_model, temperature=0, streaming=True)
|
| 24 |
+
chain = ConversationChain(llm=llm, memory=memory, verbose=True)
|
| 25 |
+
return chain
|
| 26 |
+
|
| 27 |
+
@utils.enable_chat_history
|
| 28 |
+
def main(self):
|
| 29 |
+
chain = self.setup_chain()
|
| 30 |
+
user_query = st.chat_input(placeholder="Ask me anything!")
|
| 31 |
+
if user_query:
|
| 32 |
+
utils.display_msg(user_query, 'user')
|
| 33 |
+
with st.chat_message("assistant"):
|
| 34 |
+
st_cb = StreamHandler(st.empty())
|
| 35 |
+
result = chain.invoke(
|
| 36 |
+
{"input":user_query},
|
| 37 |
+
{"callbacks": [st_cb]}
|
| 38 |
+
)
|
| 39 |
+
response = result["response"]
|
| 40 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
obj = ContextChatbot()
|
| 44 |
+
obj.main()
|
| 45 |
+
|