Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,107 @@
|
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import streamlit as st
|
| 3 |
+
from langchain_chroma import Chroma
|
| 4 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 5 |
+
from langchain.memory import ConversationBufferMemory
|
| 6 |
+
from langchain.prompts import PromptTemplate
|
| 7 |
+
from langchain_groq import ChatGroq
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
|
| 11 |
+
st.title("Chatbot")
|
| 12 |
+
|
| 13 |
+
# Load environment variables
|
| 14 |
+
load_dotenv()
|
| 15 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 16 |
+
assert GROQ_API_KEY, "GROQ_API_KEY environment variable not set."
|
| 17 |
+
|
| 18 |
+
# One-time setup in session state
|
| 19 |
+
if 'initialized' not in st.session_state:
|
| 20 |
+
st.session_state.initialized = False
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
with st.spinner("Initializing..."):
|
| 24 |
+
# Initialize embeddings model
|
| 25 |
+
model_path = "sentence-transformers/all-MiniLM-L12-v2"
|
| 26 |
+
st.session_state.embedding_function = HuggingFaceEmbeddings(
|
| 27 |
+
model_name=model_path,
|
| 28 |
+
model_kwargs={'device': 'cpu'},
|
| 29 |
+
encode_kwargs={'normalize_embeddings': False}
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Set up document search
|
| 33 |
+
persist_directory = "doc_db"
|
| 34 |
+
st.session_state.docsearch = Chroma(
|
| 35 |
+
persist_directory=persist_directory,
|
| 36 |
+
embedding_function=st.session_state.embedding_function
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# Initialize ChatGroq model
|
| 40 |
+
st.session_state.chat_model = ChatGroq(
|
| 41 |
+
model="llama-3.1-8b-instant",
|
| 42 |
+
temperature=0,
|
| 43 |
+
api_key=GROQ_API_KEY
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Define prompt template and memory
|
| 47 |
+
template = """You are a chatbot having a conversation with a human. Your name is Devrim.
|
| 48 |
+
Given the following extracted parts of a long document and a question, create a final answer. If the answer is not in the document or irrelevant, just say that you don't know, don't try to make up an answer.
|
| 49 |
+
{context}
|
| 50 |
+
{chat_history}
|
| 51 |
+
Human: {human_input}
|
| 52 |
+
Chatbot:"""
|
| 53 |
+
|
| 54 |
+
prompt = PromptTemplate(
|
| 55 |
+
input_variables=["chat_history", "human_input", "context"], template=template
|
| 56 |
+
)
|
| 57 |
+
st.session_state.memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input")
|
| 58 |
+
|
| 59 |
+
# Load QA chain
|
| 60 |
+
st.session_state.qa_chain = load_qa_chain(
|
| 61 |
+
llm=st.session_state.chat_model,
|
| 62 |
+
chain_type="question_answering",
|
| 63 |
+
memory=st.session_state.memory,
|
| 64 |
+
prompt=prompt
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
st.session_state.initialized = True
|
| 68 |
+
st.success("Initialization successful.")
|
| 69 |
+
|
| 70 |
+
except Exception as e:
|
| 71 |
+
st.session_state.initialized = False
|
| 72 |
+
st.error(f"Initialization failed: {e}")
|
| 73 |
+
|
| 74 |
+
# Clear chat history buttons
|
| 75 |
+
if st.button("Clear Chat History"):
|
| 76 |
+
if 'memory' in st.session_state and st.session_state.memory:
|
| 77 |
+
st.session_state.memory.clear()
|
| 78 |
+
st.experimental_rerun() # Refresh the app to reflect the cleared history
|
| 79 |
+
|
| 80 |
+
# Display chat history if initialized
|
| 81 |
+
if st.session_state.initialized and 'memory' in st.session_state and st.session_state.memory:
|
| 82 |
+
if st.session_state.memory.buffer_as_messages:
|
| 83 |
+
for message in st.session_state.memory.buffer_as_messages:
|
| 84 |
+
if message.type == "ai":
|
| 85 |
+
st.chat_message(name="ai", avatar="🤖").write(message.content)
|
| 86 |
+
else:
|
| 87 |
+
st.chat_message(name="human", avatar="👤").write(message.content)
|
| 88 |
+
|
| 89 |
+
# Input for new query
|
| 90 |
+
if 'initialized' in st.session_state and st.session_state.initialized:
|
| 91 |
+
query = st.chat_input("Ask something")
|
| 92 |
+
if query:
|
| 93 |
+
try:
|
| 94 |
+
with st.spinner("Answering..."):
|
| 95 |
+
# Perform similarity search and get response
|
| 96 |
+
docs = st.session_state.docsearch.similarity_search(query, k=1)
|
| 97 |
+
response = st.session_state.qa_chain(
|
| 98 |
+
{"input_documents": docs, "human_input": query},
|
| 99 |
+
return_only_outputs=True
|
| 100 |
+
)["output_text"]
|
| 101 |
+
|
| 102 |
+
# Display new message
|
| 103 |
+
st.chat_message(name="human", avatar="👤").write(query)
|
| 104 |
+
st.chat_message(name="ai", avatar="🤖").write(response)
|
| 105 |
+
|
| 106 |
+
except Exception as e:
|
| 107 |
+
st.error(f"An error occurred: {e}")
|