Harshdhsvguyt commited on
Commit
9d21329
·
verified ·
1 Parent(s): a45a1af

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +130 -0
  2. requirements.txt +12 -3
  3. temp.pdf +0 -0
app.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## RAG Q&A Conversation With PDF Including Chat History
2
+ import streamlit as st
3
+ from langchain.chains import create_history_aware_retriever, create_retrieval_chain
4
+ from langchain.chains.combine_documents import create_stuff_documents_chain
5
+ from langchain_chroma import Chroma
6
+ from langchain_community.chat_message_histories import ChatMessageHistory
7
+ from langchain_core.chat_history import BaseChatMessageHistory
8
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
9
+ from langchain_groq import ChatGroq
10
+ from langchain_core.runnables.history import RunnableWithMessageHistory
11
+ from langchain_huggingface import HuggingFaceEmbeddings
12
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
13
+ from langchain_community.document_loaders import PyPDFLoader
14
+ import os
15
+
16
+ from dotenv import load_dotenv
17
+ load_dotenv()
18
+
19
+ os.environ['HF_TOKEN'] = os.getenv("HF_TOKEN")
20
+ embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
21
+
22
+ ## Set up Streamlit
23
+ st.title("Conversational RAG With PDF uploads and chat history")
24
+ st.write("Upload PDFs and chat with their content")
25
+
26
+ ## Input the Groq API Key
27
+ api_key = st.text_input("Enter your Groq API key:", type="password")
28
+
29
+ ## Check if Groq API key is provided
30
+ if api_key:
31
+ llm = ChatGroq(groq_api_key=api_key, model_name="Gemma2-9b-It")
32
+
33
+ ## Chat interface
34
+ session_id = st.text_input("Session ID", value="default_session")
35
+
36
+ ## Statefully manage chat history
37
+ if 'store' not in st.session_state:
38
+ st.session_state.store = {}
39
+
40
+ uploaded_files = st.file_uploader("Choose a PDF file", type="pdf", accept_multiple_files=True)
41
+
42
+ ## Process uploaded PDFs
43
+ if uploaded_files:
44
+ documents = []
45
+ for uploaded_file in uploaded_files:
46
+ temppdf = f"./temp.pdf"
47
+ with open(temppdf, "wb") as file:
48
+ file.write(uploaded_file.getvalue())
49
+ file_name = uploaded_file.name
50
+
51
+ loader = PyPDFLoader(temppdf)
52
+ docs = loader.load()
53
+ documents.extend(docs)
54
+
55
+ # Split and create embeddings for the documents
56
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=500)
57
+ splits = text_splitter.split_documents(documents)
58
+ vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)
59
+ retriever = vectorstore.as_retriever()
60
+
61
+ contextualize_q_system_prompt = (
62
+ "Given a chat history and the latest user question "
63
+ "which might reference context in the chat history, "
64
+ "formulate a standalone question which can be understood "
65
+ "without the chat history. Do NOT answer the question, "
66
+ "just reformulate it if needed and otherwise return it as is."
67
+ )
68
+ contextualize_q_prompt = ChatPromptTemplate.from_messages(
69
+ [
70
+ ("system", contextualize_q_system_prompt),
71
+ MessagesPlaceholder("chat_history"),
72
+ ("human", "{input}"),
73
+ ]
74
+ )
75
+
76
+ history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_q_prompt)
77
+
78
+ ## Answer question
79
+ system_prompt = (
80
+ "You are an assistant for question-answering tasks. "
81
+ "Use the following pieces of retrieved context to answer "
82
+ "the question. If you don't know the answer, say that you "
83
+ "don't know. Use three sentences maximum and keep the "
84
+ "answer concise."
85
+ "\n\n"
86
+ "{context}"
87
+ )
88
+ qa_prompt = ChatPromptTemplate.from_messages(
89
+ [
90
+ ("system", system_prompt),
91
+ MessagesPlaceholder("chat_history"),
92
+ ("human", "{input}"),
93
+ ]
94
+ )
95
+
96
+ question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
97
+ rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
98
+
99
+ def get_session_history(session: str) -> BaseChatMessageHistory:
100
+ if session_id not in st.session_state.store:
101
+ st.session_state.store[session_id] = ChatMessageHistory()
102
+ return st.session_state.store[session_id]
103
+
104
+ conversational_rag_chain = RunnableWithMessageHistory(
105
+ rag_chain,
106
+ get_session_history,
107
+ input_messages_key="input",
108
+ history_messages_key="chat_history",
109
+ output_messages_key="answer"
110
+ )
111
+
112
+ user_input = st.text_input("Your question:")
113
+ if user_input:
114
+ session_history = get_session_history(session_id)
115
+ response = conversational_rag_chain.invoke(
116
+ {"input": user_input},
117
+ config={
118
+ "configurable": {"session_id": session_id}
119
+ },
120
+ )
121
+ st.write(st.session_state.store)
122
+ st.write("Assistant:", response['answer'])
123
+ st.write("Chat History:", session_history.messages)
124
+ else:
125
+ st.warning("Please enter the Groq API Key")
126
+
127
+
128
+
129
+
130
+
requirements.txt CHANGED
@@ -1,3 +1,12 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ langchain
3
+ langchain-community
4
+ langchain-chroma
5
+ langchain-core
6
+ langchain-huggingface
7
+ langchain-groq
8
+ chromadb
9
+ pypdf
10
+ python-dotenv
11
+ sentence-transformers
12
+ huggingface-hub
temp.pdf ADDED
Binary file (32 kB). View file