akshansh36 commited on
Commit
9ad8bbc
·
verified ·
1 Parent(s): f0102d1

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +362 -0
  2. config.py +2 -0
  3. requirements.txt +0 -0
app.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import streamlit_chat
3
+ import json
4
+ import os
5
+ from config import app_name
6
+ from config import website_name
7
+ from pymongo import MongoClient
8
+ from bson import ObjectId
9
+ from dotenv import load_dotenv
10
+ import pinecone
11
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
12
+ from langchain_google_genai import ChatGoogleGenerativeAI
13
+ from langchain_core.prompts import ChatPromptTemplate
14
+ import re
15
+
16
+ st.set_page_config(layout="wide", page_title=app_name, page_icon="📄")
17
+ load_dotenv()
18
+ import logging
19
+ from pytz import timezone, utc
20
+ from datetime import datetime
21
+
22
+ logging.basicConfig(
23
+ level=logging.DEBUG, # This is for your application logs
24
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25
+ datefmt='%Y-%m-%d %H:%M:%S'
26
+ )
27
+
28
+ # Suppress pymongo debug logs by setting the pymongo logger to a higher level
29
+ pymongo_logger = logging.getLogger('pymongo')
30
+ pymongo_logger.setLevel(logging.WARNING)
31
+ FLASH_API = os.getenv("FLASH_API")
32
+ PINECONE_API = os.getenv("PINECONE_API_KEY")
33
+ MONGO_URI = os.getenv("MONGO_URI")
34
+ DATABASE=os.getenv("DATABASE")
35
+ CHAT_COLLECTION=os.getenv("CHAT_COLLECTION")
36
+ PINECONE_INDEX=os.getenv("PINECONE_INDEX")
37
+
38
+ pc = pinecone.Pinecone(
39
+ api_key=PINECONE_API
40
+ )
41
+
42
+ index = pc.Index(PINECONE_INDEX)
43
+ # MongoDB connection setup
44
+
45
+ client = MongoClient(MONGO_URI)
46
+ db = client[DATABASE]
47
+ chat_sessions = db[CHAT_COLLECTION]
48
+
49
+
50
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=FLASH_API)
51
+ llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0, max_tokens=None, google_api_key=FLASH_API)
52
+
53
+ # Load the extracted JSON data
54
+
55
+ # Initialize session state for current chat session
56
+ if 'current_chat_id' not in st.session_state:
57
+ st.session_state['current_chat_id'] = None
58
+ if 'chat_history' not in st.session_state:
59
+ st.session_state['chat_history'] = []
60
+ if 'regenerate' not in st.session_state:
61
+ st.session_state['regenerate'] = False # Track regenerate button state
62
+
63
+
64
+ # Function to create a new chat session in MongoDB
65
+ def create_new_chat_session():
66
+ # Get the current time in IST
67
+ ind_time = datetime.now(timezone("Asia/Kolkata"))
68
+ # Convert IST time to UTC for storing in MongoDB
69
+ utc_time = ind_time.astimezone(utc)
70
+
71
+ new_session = {
72
+ "created_at": utc_time, # Store in UTC
73
+ "messages": [] # Empty at first
74
+ }
75
+ session_id = chat_sessions.insert_one(new_session).inserted_id
76
+ return str(session_id)
77
+
78
+
79
+ # Function to load a chat session by MongoDB ID
80
+ # Function to load the chat session by MongoDB ID (load full history for display)
81
+ def load_chat_session(session_id):
82
+ session = chat_sessions.find_one({"_id": ObjectId(session_id)})
83
+ if session:
84
+ # Load the full chat history (no slicing here)
85
+ st.session_state['chat_history'] = session['messages']
86
+
87
+
88
+ # Function to update chat session in MongoDB (store last 15 question-answer pairs)
89
+ # Function to update chat session in MongoDB (store entire chat history)
90
+ def update_chat_session(session_id, question, answer, improved_question):
91
+ # Append the new question-answer pair to the full messages array
92
+ chat_sessions.update_one(
93
+ {"_id": ObjectId(session_id)},
94
+ {"$push": {
95
+ "messages": {"$each": [{"question": question, 'improved_question': improved_question, "answer": answer}]}}}
96
+ )
97
+
98
+
99
+ # Function to replace the last response in MongoDB
100
+ def replace_last_response_in_mongo(session_id, new_answer):
101
+ last_message_index = len(st.session_state['chat_history']) - 1
102
+ if last_message_index >= 0:
103
+ # Replace the last response in MongoDB
104
+ chat_sessions.update_one(
105
+ {"_id": ObjectId(session_id)},
106
+ {"$set": {f"messages.{last_message_index}.answer": new_answer}}
107
+ )
108
+
109
+
110
+ # Function to regenerate the response
111
+ def regenerate_response():
112
+ try:
113
+ if st.session_state['chat_history']:
114
+ last_question = st.session_state['chat_history'][-1]["question"] # Get the last question
115
+ # Exclude the last response from the history when sending the question to LLM
116
+ previous_history = st.session_state['chat_history'][:-1] # Exclude the last Q&A pair
117
+
118
+ with st.spinner("Please wait, regenerating the response!"):
119
+ # Generate a new response for the last question using only the previous history
120
+
121
+ query = get_context_from_messages(last_question, previous_history)
122
+ if query:
123
+ logging.info(f"Extracted query is :{query}\n")
124
+ extracted_query = get_query_from_llm_answer(query)
125
+ if extracted_query:
126
+ query = extracted_query
127
+ else:
128
+ query = last_question
129
+
130
+ query_embedding = embeddings.embed_query(query)
131
+ search_results = index.query(vector=query_embedding, top_k=10, include_metadata=True)
132
+ matches = search_results['matches']
133
+
134
+ content = ""
135
+ for i, match in enumerate(matches):
136
+ chunk = match['metadata']['chunk']
137
+ url = match['metadata']['url']
138
+ content += f"chunk{i}: {chunk}\n" + f"url{i}: {url}\n"
139
+
140
+ new_reply = generate_summary(content, query, previous_history)
141
+
142
+ st.session_state['chat_history'][-1]["answer"] = new_reply
143
+
144
+ # Update MongoDB with the new response
145
+ if st.session_state['current_chat_id']:
146
+ replace_last_response_in_mongo(st.session_state['current_chat_id'], new_reply)
147
+
148
+ st.session_state['regenerate'] = False # Reset regenerate flag
149
+ st.rerun()
150
+
151
+ except Exception as e:
152
+ st.error("Error occured in Regenerating response, please try again later.")
153
+
154
+
155
+ def generate_summary(chunks, query, chat_history):
156
+ try:
157
+ # Limit the history sent to the LLM to the latest 3 question-answer pairs
158
+ limited_history = chat_history[-3:] if len(chat_history) > 3 else chat_history
159
+
160
+ # Create conversation history for the LLM, only using the last 15 entries
161
+ history_text = "\n".join([f"User: {q['improved_question']}\nLLM: {q['answer']}" for q in limited_history])
162
+
163
+ # Define the system and user prompts including the limited history
164
+ prompt = ChatPromptTemplate.from_messages([
165
+ ("system", f"""You are a website-specific chatbot specializing in answering user queries about {website_name}. You will be provided with data chunks sourced from {website_name}, and each chunk has an associated URL. When formulating your responses:
166
+ 1. Clarity and Completeness
167
+ - Always strive to deliver thorough, concise, and direct answers.
168
+ - If the user’s query is ambiguous or there are multiple possible answers, ask for clarification with a clear rationale.
169
+ 2. No Chunk Names
170
+ - Do not reference chunk filenames or mention the term “chunk” in your replies.
171
+ - Instead, present the information in a natural, conversational style.
172
+
173
+ 3. Use of Conversation History
174
+ - Refer back to conversation history for consistency and to get context for a follow up question.
175
+ - If there are previous statements like “The answer is not available,” ignore them unless still relevant to the current query.
176
+
177
+ 4. Handling Off-Topic Queries
178
+ - If the user sends greetings, introductions, or queries unrelated to {website_name}, respond politely and conversationally without forcing a website-related answer.
179
+
180
+ 5. Source URLs
181
+ - Always provide the URLs you used to answer the query under a “Sources” heading at the end of your reply.
182
+ - If the same URL appears in multiple relevant chunks, list that URL only once in the sources section.
183
+ - Only include the URLs that genuinely informed or supported your answer.
184
+ - if the answer itself contains url, then quote it properly
185
+
186
+ 6. No Direct Chunk Quotes
187
+ - Summarize or paraphrase the original content instead of quoting chunk names or raw text verbatim (unless absolutely necessary for clarity).
188
+ 7. Relevance Check
189
+ - Thoroughly check the provided data chunks before replying.
190
+ - If you can’t find an answer in the chunks, or if the query is irrelevant politely ask for clarification or explain that you cannot answer.
191
+
192
+ 8. Formatting
193
+ - Present your answers in a well-structured format—either bullet points or clear paragraphs—to ensure maximum readability.
194
+
195
+
196
+ """),
197
+
198
+ ("human", f'''
199
+ "Query":\n {query}\n
200
+ Below are the pinecone chunks that should be used to answer the user query:
201
+ "Extracted Data": \n{chunks}\n
202
+ Below is the previous conversation history:
203
+ "Previous Conversation History": \n{history_text}\n
204
+ '''
205
+ )
206
+ ])
207
+
208
+ # Chain the prompt with LLM for response generation
209
+ chain = prompt | llm
210
+ result = chain.invoke({"Query": query, "Extracted Data": chunks, "Previous Conversation History": history_text})
211
+
212
+ # Return the generated response
213
+ logging.info(f"LLM answer is :{result}")
214
+ return result.content
215
+
216
+ except Exception as e:
217
+ st.error(f"Error answering your question: {e}")
218
+ return None
219
+
220
+
221
+ def get_context_from_messages(query, chat_history):
222
+ try:
223
+
224
+ logging.info(f"Getting context from original query: {query}")
225
+
226
+ # Limit the history sent to the LLM to the latest 3 question-answer pairs
227
+ limited_history = chat_history[-3:] if len(chat_history) > 3 else chat_history
228
+
229
+ # Create conversation history for the LLM, only using the last 15 entries
230
+ history_text = "\n".join([f"User: {q['question']}\nLLM: {q['answer']}" for q in limited_history])
231
+
232
+ # Define the system and user prompts including the limited history
233
+ prompt = ChatPromptTemplate.from_messages([
234
+ ("system", f""""I will provide you with a user query and up to the last 3 messages from the chat history which includes both questions and answers.Your task is to understand the user query nicely and restructure it if required such that it makes complete sense and is completely self contained.
235
+ The provided queries are related to {website_name}.
236
+ 1. If the query is a follow-up, use the provided chat history to reconstruct a well-defined, contextually complete query that can stand alone."
237
+ 2. if the query is self contained, if applicable try to improve it to make is coherent.
238
+ 3. if the user query is salutations, greetings or not relevant in that case give the query back as it is.
239
+ I have provided an output format below, stricly follow it. Do not give anything else other than just the output.
240
+ expected_output_format: "query: String or None"
241
+ """),
242
+ ("human", f'''
243
+ "Query":\n {query}\n
244
+ "Previous Conversation History": \n{history_text}\n
245
+ '''
246
+ )
247
+ ])
248
+
249
+ # Chain the prompt with LLM for response generation
250
+ chain = prompt | llm
251
+ result = chain.invoke({"Query": query, "Previous Conversation History": history_text})
252
+ logging.info(f"llm answer for query extraction is :{result}")
253
+
254
+ # Return the generated response
255
+ return result.content
256
+
257
+ except Exception as e:
258
+ logging.error(f"exception occured in getting query from original query :{e}")
259
+ return None
260
+
261
+
262
+ def get_query_from_llm_answer(llm_output):
263
+ match = re.search(r'query:\s*(.*)', llm_output)
264
+ if match:
265
+ query = match.group(1).strip().strip('"') # Remove leading/trailing spaces and quotes
266
+ return None if query.lower() == "none" else query
267
+ return None
268
+
269
+
270
+ # Sidebar for showing chat sessions and creating new sessions
271
+ st.sidebar.header("Chat Sessions")
272
+
273
+ # Button for creating a new chat
274
+ if st.sidebar.button("New Chat"):
275
+ new_chat_id = create_new_chat_session()
276
+ st.session_state['current_chat_id'] = new_chat_id
277
+ st.session_state['chat_history'] = []
278
+
279
+ # List existing chat sessions with delete button (dustbin icon)
280
+ existing_sessions = chat_sessions.find().sort("created_at", -1)
281
+ for session in existing_sessions:
282
+ session_id = str(session['_id'])
283
+
284
+ # Retrieve stored UTC time and convert it to IST for display
285
+ utc_time = session['created_at']
286
+ ist_time = utc_time.replace(tzinfo=utc).astimezone(timezone("Asia/Kolkata"))
287
+ session_date = ist_time.strftime("%Y-%m-%d %H:%M:%S") # Format for display
288
+
289
+ col1, col2 = st.sidebar.columns([8, 1])
290
+ with col1:
291
+ if st.button(f"Session {session_date}", key=session_id):
292
+ st.session_state['current_chat_id'] = session_id
293
+ load_chat_session(session_id)
294
+
295
+ # Display delete icon (dustbin)
296
+ with col2:
297
+ if st.button("🗑️", key=f"delete_{session_id}"):
298
+ chat_sessions.delete_one({"_id": ObjectId(session_id)})
299
+ st.rerun() # Refresh the app to remove the deleted session from the sidebar
300
+
301
+ # Main chat interface
302
+ st.markdown('<div class="fixed-header"><h1>Welcome To RITES Chatbot</h1></div>', unsafe_allow_html=True)
303
+ st.markdown("<hr>", unsafe_allow_html=True)
304
+
305
+ # Input box for the question
306
+ user_question = st.chat_input(f"Ask a Question related to {website_name}")
307
+
308
+ if user_question:
309
+ # Automatically create a new session if none exists
310
+ if not st.session_state['current_chat_id']:
311
+ new_chat_id = create_new_chat_session()
312
+ st.session_state['current_chat_id'] = new_chat_id
313
+
314
+ with st.spinner("Please wait, I am thinking!!"):
315
+ # Store the user's question and get the assistant's response
316
+ query = get_context_from_messages(user_question, st.session_state['chat_history'])
317
+ if query:
318
+ logging.info(f"Extracted query is :{query}\n")
319
+ extracted_query = get_query_from_llm_answer(query)
320
+ if extracted_query:
321
+ query = extracted_query
322
+ else:
323
+ query = user_question
324
+
325
+ query_embedding = embeddings.embed_query(query)
326
+ search_results = index.query(vector=query_embedding, top_k=10, include_metadata=True)
327
+ matches = search_results['matches']
328
+
329
+ content = ""
330
+ for i, match in enumerate(matches):
331
+ chunk = match['metadata']['chunk']
332
+ url = match['metadata']['url']
333
+ content += f"chunk{i}: {chunk}\n" + f"url{i}: {url}\n"
334
+
335
+ print(f"content being passed is {content}")
336
+ reply = generate_summary(content, query, st.session_state['chat_history'])
337
+
338
+ if reply:
339
+ # Append the new question-answer pair to chat history
340
+ st.session_state['chat_history'].append(
341
+ {"question": user_question, "answer": reply, "improved_question": query})
342
+
343
+ # Update the current chat session in MongoDB
344
+ if st.session_state['current_chat_id']:
345
+ update_chat_session(st.session_state['current_chat_id'], user_question, reply, query)
346
+
347
+ else:
348
+ st.error("Error processing your request, Please try again later.")
349
+ else:
350
+ st.error("Error processing your request, Please try again later.")
351
+ # Display the updated chat history (show last 15 question-answer pairs)
352
+ for i, pair in enumerate(st.session_state['chat_history']):
353
+ question = pair["question"]
354
+ answer = pair["answer"]
355
+ streamlit_chat.message(question, is_user=True, key=f"chat_message_user_{i}")
356
+ streamlit_chat.message(answer, is_user=False, key=f"chat_message_assistant_{i}")
357
+
358
+ # Display regenerate button under the last response
359
+ if st.session_state['chat_history'] and not st.session_state['regenerate']:
360
+ if st.button("🔄 Regenerate", key="regenerate_button"):
361
+ st.session_state['regenerate'] = True
362
+ regenerate_response()
config.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ app_name="Rites Chatbot"
2
+ website_name="Rail India Technical and Economic Service (RITES)"
requirements.txt ADDED
Binary file (4.42 kB). View file