akshansh36 commited on
Commit
d8d147e
·
verified ·
1 Parent(s): 2a993af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -167
app.py CHANGED
@@ -1,26 +1,24 @@
1
  import streamlit as st
2
  import streamlit_chat
 
3
  import os
 
4
  from bson import ObjectId
5
  from dotenv import load_dotenv
6
  import pinecone
7
- from pinecone import Pinecone, ServerlessSpec # Import the Pinecone class
8
  from langchain_google_genai import GoogleGenerativeAIEmbeddings
9
  from langchain_google_genai import ChatGoogleGenerativeAI
10
  from langchain_core.prompts import ChatPromptTemplate
11
  import re
12
- import logging
13
- from pytz import timezone, utc
14
- from datetime import datetime
15
- from concurrent.futures import ThreadPoolExecutor
16
- from pymongo import MongoClient
17
 
18
  st.set_page_config(layout="wide", page_title="IOCL Chatbot", page_icon="📄")
19
  load_dotenv()
 
 
 
20
 
21
- # Logging Configuration
22
  logging.basicConfig(
23
- level=logging.INFO, # Set to INFO to reduce verbosity
24
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25
  datefmt='%Y-%m-%d %H:%M:%S'
26
  )
@@ -29,13 +27,12 @@ logging.basicConfig(
29
  pymongo_logger = logging.getLogger('pymongo')
30
  pymongo_logger.setLevel(logging.WARNING)
31
 
32
- # API and Service Initialization
33
  PINECONE_API = os.getenv("PINECONE_API_KEY")
34
- pc = Pinecone(api_key=PINECONE_API) # Create an instance of the Pinecone class
35
-
 
36
  index_name = "iocl2"
37
- index = pc.Index(index_name) # Access the index through the Pinecone client instance
38
-
39
  # MongoDB connection setup
40
  MONGO_URI = os.getenv("MONGO_URI")
41
  client = MongoClient(MONGO_URI)
@@ -47,6 +44,8 @@ FLASH_API = os.getenv("FLASH_API")
47
  embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=FLASH_API)
48
  llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0, max_tokens=None, google_api_key=FLASH_API)
49
 
 
 
50
  # Initialize session state for current chat session
51
  if 'current_chat_id' not in st.session_state:
52
  st.session_state['current_chat_id'] = None
@@ -55,6 +54,7 @@ if 'chat_history' not in st.session_state:
55
  if 'regenerate' not in st.session_state:
56
  st.session_state['regenerate'] = False # Track regenerate button state
57
 
 
58
  # Function to create a new chat session in MongoDB
59
  def create_new_chat_session():
60
  # Get the current time in IST
@@ -69,21 +69,27 @@ def create_new_chat_session():
69
  session_id = chat_sessions.insert_one(new_session).inserted_id
70
  return str(session_id)
71
 
 
 
72
  # Function to load the chat session by MongoDB ID (load full history for display)
73
  def load_chat_session(session_id):
74
  session = chat_sessions.find_one({"_id": ObjectId(session_id)})
75
  if session:
76
- # Load the full chat history
77
  st.session_state['chat_history'] = session['messages']
78
 
 
 
79
  # Function to update chat session in MongoDB (store entire chat history)
80
  def update_chat_session(session_id, question, answer, improved_question):
81
  # Append the new question-answer pair to the full messages array
82
  chat_sessions.update_one(
83
  {"_id": ObjectId(session_id)},
84
- {"$push": {"messages": {"$each": [{"question": question, 'improved_question': improved_question, "answer": answer}]}}}
 
85
  )
86
 
 
87
  # Function to replace the last response in MongoDB
88
  def replace_last_response_in_mongo(session_id, new_answer):
89
  last_message_index = len(st.session_state['chat_history']) - 1
@@ -94,6 +100,7 @@ def replace_last_response_in_mongo(session_id, new_answer):
94
  {"$set": {f"messages.{last_message_index}.answer": new_answer}}
95
  )
96
 
 
97
  # Function to regenerate the response
98
  def regenerate_response():
99
  try:
@@ -105,83 +112,71 @@ def regenerate_response():
105
  with st.spinner("Please wait, regenerating the response!"):
106
  # Generate a new response for the last question using only the previous history
107
 
108
- # Use threading to parallelize operations
109
- with ThreadPoolExecutor() as executor:
110
- # Start context extraction and chat history fetch in parallel
111
- context_task = executor.submit(get_context_from_messages, last_question, previous_history)
112
-
113
- # Wait for context extraction
114
- query = context_task.result()
 
115
 
116
- if query:
117
- logging.info(f"Extracted query is: {query}")
118
- extracted_query = get_query_from_llm_answer(query)
119
- if extracted_query:
120
- query = extracted_query
121
- else:
122
- query = last_question
123
 
124
- # Start embedding generation and Pinecone query in parallel
125
- embedding_task = executor.submit(embeddings.embed_query, query)
126
- query_embedding = embedding_task.result()
 
 
127
 
128
- pinecone_task = executor.submit(query_pinecone_sync, query_embedding)
129
 
130
- search_results = pinecone_task.result()
131
- matches = search_results['matches']
132
 
133
- content = ""
134
- for i, match in enumerate(matches):
135
- chunk = match['metadata']['chunk']
136
- url = match['metadata']['url']
137
- content += f"chunk{i}: {chunk}\n" + f"url{i}: {url}\n"
138
 
139
- new_reply = generate_summary(content, query, previous_history)
140
-
141
- st.session_state['chat_history'][-1]["answer"] = new_reply
142
-
143
- # Update MongoDB with the new response
144
- if st.session_state['current_chat_id']:
145
- replace_last_response_in_mongo(st.session_state['current_chat_id'], new_reply)
146
-
147
- st.session_state['regenerate'] = False # Reset regenerate flag
148
- st.rerun()
149
 
150
  except Exception as e:
151
- st.error("Error occurred in regenerating response, please try again later.")
152
- logging.error(f"Exception in regenerate_response: {e}")
153
 
154
  def generate_summary(chunks, query, chat_history):
155
  try:
156
  # Limit the history sent to the LLM to the latest 3 question-answer pairs
157
  limited_history = chat_history[-3:] if len(chat_history) > 3 else chat_history
158
 
159
- # Create conversation history for the LLM
160
- history_text = "\n".join([f"User: {q.get('improved_question', q['question'])}\nLLM: {q['answer']}" for q in limited_history])
161
 
162
  # Define the system and user prompts including the limited history
163
  prompt = ChatPromptTemplate.from_messages([
164
- ("system", """You are a chatbot specializing in answering queries related to Indian Oil Corporation Limited (IOCL). You will be provided with chunks of data from the IOCL website to answer user queries. Each chunk will include associated URLs, you must give the URL of the chunks which you are using to answer the query.
165
- Key Guidelines:
166
- 1. If the user query is not clear, or you think multiple answers are possible, you should ask for clarification with proper reasoning.
167
- 2. Do not mention chunk name in any of your replies.
168
- 3. Detailed and Clear: Provide thorough, clear, and concise responses without omitting relevant information from the data chunks.
169
- 4. Natural Summarization: When answering, you must not directly quote chunk names, formats. Instead, summarize or interpret the data naturally and conversationally.
170
- 5. Use Conversation History: Refer back to the conversation history to maintain consistency and build on prior responses, if applicable.
171
- 6. Ignore Unanswered Queries: If the conversation history contains previous responses like "The answer is not available in the context," disregard them when formulating your current response.
172
- 7. Graceful Handling of General Queries: If a user sends greetings, introduction, salutations, or unrelated questions, respond appropriately and conversationally.
173
- 8. Include Source URLs: Always include the URLs from the relevant chunks of data that you're using to answer the query.
174
- 9. Thoroughly look for answer to the query in the provided chunks before replying, if you feel the query is irrelevant or answer is not present then you can ask user to clarify or tell that it cannot be answered.
175
- 10. Sometimes chunks might contain very less data still use it if it's relevant.
176
- """),
177
 
178
  ("human", f'''
179
- "Query":\n{query}\n
180
- Below are the pinecone chunks that should be used to answer the user query:
181
- "Extracted Data":\n{chunks}\n
182
- Below is the previous conversation history:
183
- "Previous Conversation History":\n{history_text}\n
184
- '''
185
  )
186
  ])
187
 
@@ -190,53 +185,55 @@ def generate_summary(chunks, query, chat_history):
190
  result = chain.invoke({"Query": query, "Extracted Data": chunks, "Previous Conversation History": history_text})
191
 
192
  # Return the generated response
193
- logging.info(f"LLM answer is: {result}")
194
  return result.content
195
 
196
  except Exception as e:
197
  st.error(f"Error answering your question: {e}")
198
- logging.error(f"Exception in generate_summary: {e}")
199
  return None
200
 
 
201
  def get_context_from_messages(query, chat_history):
202
  try:
 
203
  logging.info(f"Getting context from original query: {query}")
204
 
205
  # Limit the history sent to the LLM to the latest 3 question-answer pairs
206
  limited_history = chat_history[-3:] if len(chat_history) > 3 else chat_history
207
 
208
- # Create conversation history for the LLM
209
  history_text = "\n".join([f"User: {q['question']}\nLLM: {q['answer']}" for q in limited_history])
210
 
211
  # Define the system and user prompts including the limited history
212
  prompt = ChatPromptTemplate.from_messages([
213
- ("system", """"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.
214
- The provided queries are related to Indian Oil Corporation Limited (IOCL).
215
- 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.
216
- 2. If the query is self-contained, if applicable try to improve it to make it coherent.
217
- 3. If the user query is salutations, greetings or not relevant, in that case give the query back as it is.
218
- I have provided an output format below, strictly follow it. Do not give anything else other than just the output.
219
- expected_output_format: "query: String or None"
220
- """),
221
- ("human", f'''
222
- "Query":\n{query}\n
223
- "Previous Conversation History":\n{history_text}\n
224
- '''
225
  )
226
  ])
227
 
228
  # Chain the prompt with LLM for response generation
229
  chain = prompt | llm
230
  result = chain.invoke({"Query": query, "Previous Conversation History": history_text})
231
- logging.info(f"LLM answer for query extraction is: {result}")
232
 
233
  # Return the generated response
234
  return result.content
235
 
236
  except Exception as e:
237
- logging.error(f"Exception occurred in getting query from original query: {e}")
238
  return None
239
 
 
240
  def get_query_from_llm_answer(llm_output):
241
  match = re.search(r'query:\s*(.*)', llm_output)
242
  if match:
@@ -244,60 +241,6 @@ def get_query_from_llm_answer(llm_output):
244
  return None if query.lower() == "none" else query
245
  return None
246
 
247
- # Functions for multithreading
248
- def fetch_chat_history_sync(session_id):
249
- try:
250
- session = chat_sessions.find_one({"_id": ObjectId(session_id)})
251
- return session["messages"] if session else []
252
- except Exception as e:
253
- logging.error(f"Error fetching chat history: {e}")
254
- return []
255
-
256
- def query_pinecone_sync(query_embedding):
257
- try:
258
- # Update the query method to match the new Pinecone client usage
259
- # Assuming that the Index class methods remain similar
260
- search_results = index.query(vector=query_embedding, top_k=6, include_metadata=True)
261
- return search_results
262
- except Exception as e:
263
- logging.error(f"Error querying Pinecone: {e}")
264
- return {'matches': []}
265
-
266
- def handle_user_query(user_question, session_id):
267
- """Handles the user query by parallelizing tasks."""
268
- with ThreadPoolExecutor() as executor:
269
- # Start context extraction
270
- context_task = executor.submit(get_context_from_messages, user_question, st.session_state['chat_history'])
271
-
272
- # Wait for context extraction
273
- query = context_task.result()
274
-
275
- if query:
276
- logging.info(f"Extracted query is: {query}")
277
- extracted_query = get_query_from_llm_answer(query)
278
- if extracted_query:
279
- query = extracted_query
280
- else:
281
- query = user_question
282
-
283
- # Start embedding generation and Pinecone query in parallel
284
- embedding_task = executor.submit(embeddings.embed_query, query)
285
- query_embedding = embedding_task.result()
286
-
287
- pinecone_task = executor.submit(query_pinecone_sync, query_embedding)
288
- search_results = pinecone_task.result()
289
- matches = search_results['matches']
290
-
291
- content = ""
292
- for i, match in enumerate(matches):
293
- chunk = match['metadata']['chunk']
294
- url = match['metadata']['url']
295
- content += f"chunk{i}: {chunk}\n" + f"url{i}: {url}\n"
296
-
297
- response = generate_summary(content, query, st.session_state['chat_history'])
298
- return response, query
299
- else:
300
- return None, None
301
 
302
  # Sidebar for showing chat sessions and creating new sessions
303
  st.sidebar.header("Chat Sessions")
@@ -330,13 +273,12 @@ for session in existing_sessions:
330
  chat_sessions.delete_one({"_id": ObjectId(session_id)})
331
  st.rerun() # Refresh the app to remove the deleted session from the sidebar
332
 
333
-
334
  # Main chat interface
335
  st.markdown('<div class="fixed-header"><h1>Welcome To IOCL Chatbot</h1></div>', unsafe_allow_html=True)
336
  st.markdown("<hr>", unsafe_allow_html=True)
337
 
338
  # Input box for the question
339
- user_question = st.chat_input("Ask a Question related to IOCL Website")
340
 
341
  if user_question:
342
  # Automatically create a new session if none exists
@@ -345,27 +287,43 @@ if user_question:
345
  st.session_state['current_chat_id'] = new_chat_id
346
 
347
  with st.spinner("Please wait, I am thinking!!"):
348
- response, improved_query = handle_user_query(user_question, st.session_state['current_chat_id'])
349
-
350
- if response:
351
- # Update chat history
352
- st.session_state['chat_history'].append({
353
- "question": user_question,
354
- "answer": response,
355
- "improved_question": improved_query
356
- })
357
-
358
- # Save to MongoDB
359
- update_chat_session(
360
- st.session_state['current_chat_id'],
361
- user_question,
362
- response,
363
- improved_query
364
- )
365
- else:
366
- st.error("Error processing your request, please try again later.")
 
 
 
367
 
368
- # Display the updated chat history
 
 
 
 
 
 
 
 
 
 
 
 
 
369
  for i, pair in enumerate(st.session_state['chat_history']):
370
  question = pair["question"]
371
  answer = pair["answer"]
@@ -376,4 +334,4 @@ for i, pair in enumerate(st.session_state['chat_history']):
376
  if st.session_state['chat_history'] and not st.session_state['regenerate']:
377
  if st.button("🔄 Regenerate", key="regenerate_button"):
378
  st.session_state['regenerate'] = True
379
- regenerate_response()
 
1
  import streamlit as st
2
  import streamlit_chat
3
+ import json
4
  import os
5
+ from pymongo import MongoClient
6
  from bson import ObjectId
7
  from dotenv import load_dotenv
8
  import pinecone
 
9
  from langchain_google_genai import GoogleGenerativeAIEmbeddings
10
  from langchain_google_genai import ChatGoogleGenerativeAI
11
  from langchain_core.prompts import ChatPromptTemplate
12
  import re
 
 
 
 
 
13
 
14
  st.set_page_config(layout="wide", page_title="IOCL Chatbot", page_icon="📄")
15
  load_dotenv()
16
+ import logging
17
+ from pytz import timezone, utc
18
+ from datetime import datetime
19
 
 
20
  logging.basicConfig(
21
+ level=logging.DEBUG, # This is for your application logs
22
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
23
  datefmt='%Y-%m-%d %H:%M:%S'
24
  )
 
27
  pymongo_logger = logging.getLogger('pymongo')
28
  pymongo_logger.setLevel(logging.WARNING)
29
 
 
30
  PINECONE_API = os.getenv("PINECONE_API_KEY")
31
+ pc = pinecone.Pinecone(
32
+ api_key=PINECONE_API
33
+ )
34
  index_name = "iocl2"
35
+ index = pc.Index(index_name)
 
36
  # MongoDB connection setup
37
  MONGO_URI = os.getenv("MONGO_URI")
38
  client = MongoClient(MONGO_URI)
 
44
  embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=FLASH_API)
45
  llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0, max_tokens=None, google_api_key=FLASH_API)
46
 
47
+ # Load the extracted JSON data
48
+
49
  # Initialize session state for current chat session
50
  if 'current_chat_id' not in st.session_state:
51
  st.session_state['current_chat_id'] = None
 
54
  if 'regenerate' not in st.session_state:
55
  st.session_state['regenerate'] = False # Track regenerate button state
56
 
57
+
58
  # Function to create a new chat session in MongoDB
59
  def create_new_chat_session():
60
  # Get the current time in IST
 
69
  session_id = chat_sessions.insert_one(new_session).inserted_id
70
  return str(session_id)
71
 
72
+
73
+ # Function to load a chat session by MongoDB ID
74
  # Function to load the chat session by MongoDB ID (load full history for display)
75
  def load_chat_session(session_id):
76
  session = chat_sessions.find_one({"_id": ObjectId(session_id)})
77
  if session:
78
+ # Load the full chat history (no slicing here)
79
  st.session_state['chat_history'] = session['messages']
80
 
81
+
82
+ # Function to update chat session in MongoDB (store last 15 question-answer pairs)
83
  # Function to update chat session in MongoDB (store entire chat history)
84
  def update_chat_session(session_id, question, answer, improved_question):
85
  # Append the new question-answer pair to the full messages array
86
  chat_sessions.update_one(
87
  {"_id": ObjectId(session_id)},
88
+ {"$push": {
89
+ "messages": {"$each": [{"question": question, 'improved_question': improved_question, "answer": answer}]}}}
90
  )
91
 
92
+
93
  # Function to replace the last response in MongoDB
94
  def replace_last_response_in_mongo(session_id, new_answer):
95
  last_message_index = len(st.session_state['chat_history']) - 1
 
100
  {"$set": {f"messages.{last_message_index}.answer": new_answer}}
101
  )
102
 
103
+
104
  # Function to regenerate the response
105
  def regenerate_response():
106
  try:
 
112
  with st.spinner("Please wait, regenerating the response!"):
113
  # Generate a new response for the last question using only the previous history
114
 
115
+ query = get_context_from_messages(last_question, previous_history)
116
+ if query:
117
+ logging.info(f"Extracted query is :{query}\n")
118
+ extracted_query = get_query_from_llm_answer(query)
119
+ if extracted_query:
120
+ query = extracted_query
121
+ else:
122
+ query = last_question
123
 
124
+ query_embedding = embeddings.embed_query(query)
125
+ search_results = index.query(vector=query_embedding, top_k=6, include_metadata=True)
126
+ matches = search_results['matches']
 
 
 
 
127
 
128
+ content = ""
129
+ for i, match in enumerate(matches):
130
+ chunk = match['metadata']['chunk']
131
+ url = match['metadata']['url']
132
+ content += f"chunk{i}: {chunk}\n" + f"url{i}: {url}\n"
133
 
134
+ new_reply = generate_summary(content, query, previous_history)
135
 
136
+ st.session_state['chat_history'][-1]["answer"] = new_reply
 
137
 
138
+ # Update MongoDB with the new response
139
+ if st.session_state['current_chat_id']:
140
+ replace_last_response_in_mongo(st.session_state['current_chat_id'], new_reply)
 
 
141
 
142
+ st.session_state['regenerate'] = False # Reset regenerate flag
143
+ st.rerun()
 
 
 
 
 
 
 
 
144
 
145
  except Exception as e:
146
+ st.error("Error occured in Regenerating response, please try again later.")
147
+
148
 
149
  def generate_summary(chunks, query, chat_history):
150
  try:
151
  # Limit the history sent to the LLM to the latest 3 question-answer pairs
152
  limited_history = chat_history[-3:] if len(chat_history) > 3 else chat_history
153
 
154
+ # Create conversation history for the LLM, only using the last 15 entries
155
+ history_text = "\n".join([f"User: {q['improved_question']}\nLLM: {q['answer']}" for q in limited_history])
156
 
157
  # Define the system and user prompts including the limited history
158
  prompt = ChatPromptTemplate.from_messages([
159
+ ("system", """You are a chatbot specializing in answering queries related to Indian Oil Corporation Limited (IOCL). You will be provided with chunks of data from the IOCL website to answer user queries. Each chunk will include associated URLs, You must give the url of the chunks which you are using to answer the query.
160
+ Key Guidelines:
161
+ 1.If the user query is not clear, or you think multiple answers are possbile, you should ask for clarification with proper reasoning.
162
+ 2.Do not mention chunk name in any of your replies.
163
+ 2.Detailed and Clear: Provide thorough, clear, and concise responses without omitting relevant information from the data chunks.
164
+ 3.Natural Summarization: When answering, you must not directly quote chunk names,formats. Instead, summarize or interpret the data naturally and conversationally.
165
+ 4.Use Conversation History: Refer back to the conversation history to maintain consistency and build on prior responses, if applicable.
166
+ 5.Ignore Unanswered Queries: If the conversation history contains previous responses like "The answer is not available in the context," disregard them when formulating your current response.
167
+ 6.Graceful Handling of General Queries: If a user sends greetings, introduction, salutations, or unrelated questions, respond appropriately and conversationally.
168
+ 7.Include Source URLs: Always include the URLs from the relevant chunks of data that you're using to answer the query.
169
+ 8.Thoroughly looks for answer to the query in the provided chunks before replying, if you feel the query is irrelevant or answer is not present then you can ask user to clarify or tell that it cannot be answered.
170
+ 9.Sometimes chunks might contain very less data still use it if its relevant.
171
+ """),
172
 
173
  ("human", f'''
174
+ "Query":\n {query}\n
175
+ Below are the pinecone chunks that should be used to answer the user query:
176
+ "Extracted Data": \n{chunks}\n
177
+ Below is the previous conversation history:
178
+ "Previous Conversation History": \n{history_text}\n
179
+ '''
180
  )
181
  ])
182
 
 
185
  result = chain.invoke({"Query": query, "Extracted Data": chunks, "Previous Conversation History": history_text})
186
 
187
  # Return the generated response
188
+ logging.info(f"LLM answer is :{result}")
189
  return result.content
190
 
191
  except Exception as e:
192
  st.error(f"Error answering your question: {e}")
 
193
  return None
194
 
195
+
196
  def get_context_from_messages(query, chat_history):
197
  try:
198
+
199
  logging.info(f"Getting context from original query: {query}")
200
 
201
  # Limit the history sent to the LLM to the latest 3 question-answer pairs
202
  limited_history = chat_history[-3:] if len(chat_history) > 3 else chat_history
203
 
204
+ # Create conversation history for the LLM, only using the last 15 entries
205
  history_text = "\n".join([f"User: {q['question']}\nLLM: {q['answer']}" for q in limited_history])
206
 
207
  # Define the system and user prompts including the limited history
208
  prompt = ChatPromptTemplate.from_messages([
209
+ ("system", """"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.
210
+ The provided queries are related to Indian Oil Corporation limited (IOCL).
211
+ 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."
212
+ 2. if the query is self contained, if applicable try to improve it to make is coherent.
213
+ 3. if the user query is salutations, greetings or not relevant in that case give the query back as it is.
214
+ I have provided an output format below, stricly follow it. Do not give anything else other than just the output.
215
+ expected_output_format: "query: String or None"
216
+ """),
217
+ ("human", f'''
218
+ "Query":\n {query}\n
219
+ "Previous Conversation History": \n{history_text}\n
220
+ '''
221
  )
222
  ])
223
 
224
  # Chain the prompt with LLM for response generation
225
  chain = prompt | llm
226
  result = chain.invoke({"Query": query, "Previous Conversation History": history_text})
227
+ logging.info(f"llm answer for query extraction is :{result}")
228
 
229
  # Return the generated response
230
  return result.content
231
 
232
  except Exception as e:
233
+ logging.error(f"exception occured in getting query from original query :{e}")
234
  return None
235
 
236
+
237
  def get_query_from_llm_answer(llm_output):
238
  match = re.search(r'query:\s*(.*)', llm_output)
239
  if match:
 
241
  return None if query.lower() == "none" else query
242
  return None
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  # Sidebar for showing chat sessions and creating new sessions
246
  st.sidebar.header("Chat Sessions")
 
273
  chat_sessions.delete_one({"_id": ObjectId(session_id)})
274
  st.rerun() # Refresh the app to remove the deleted session from the sidebar
275
 
 
276
  # Main chat interface
277
  st.markdown('<div class="fixed-header"><h1>Welcome To IOCL Chatbot</h1></div>', unsafe_allow_html=True)
278
  st.markdown("<hr>", unsafe_allow_html=True)
279
 
280
  # Input box for the question
281
+ user_question = st.chat_input(f"Ask a Question related to IOCL Website")
282
 
283
  if user_question:
284
  # Automatically create a new session if none exists
 
287
  st.session_state['current_chat_id'] = new_chat_id
288
 
289
  with st.spinner("Please wait, I am thinking!!"):
290
+ # Store the user's question and get the assistant's response
291
+ query = get_context_from_messages(user_question, st.session_state['chat_history'])
292
+ if query:
293
+ logging.info(f"Extracted query is :{query}\n")
294
+ extracted_query = get_query_from_llm_answer(query)
295
+ if extracted_query:
296
+ query = extracted_query
297
+ else:
298
+ query = user_question
299
+
300
+ query_embedding = embeddings.embed_query(query)
301
+ search_results = index.query(vector=query_embedding, top_k=6, include_metadata=True)
302
+ matches = search_results['matches']
303
+
304
+ content = ""
305
+ for i, match in enumerate(matches):
306
+ chunk = match['metadata']['chunk']
307
+ url = match['metadata']['url']
308
+ content += f"chunk{i}: {chunk}\n" + f"url{i}: {url}\n"
309
+
310
+ print(f"content being passed is {content}")
311
+ reply = generate_summary(content, query, st.session_state['chat_history'])
312
 
313
+ if reply:
314
+ # Append the new question-answer pair to chat history
315
+ st.session_state['chat_history'].append(
316
+ {"question": user_question, "answer": reply, "improved_question": query})
317
+
318
+ # Update the current chat session in MongoDB
319
+ if st.session_state['current_chat_id']:
320
+ update_chat_session(st.session_state['current_chat_id'], user_question, reply, query)
321
+
322
+ else:
323
+ st.error("Error processing your request, Please try again later.")
324
+ else:
325
+ st.error("Error processing your request, Please try again later.")
326
+ # Display the updated chat history (show last 15 question-answer pairs)
327
  for i, pair in enumerate(st.session_state['chat_history']):
328
  question = pair["question"]
329
  answer = pair["answer"]
 
334
  if st.session_state['chat_history'] and not st.session_state['regenerate']:
335
  if st.button("🔄 Regenerate", key="regenerate_button"):
336
  st.session_state['regenerate'] = True
337
+ regenerate_response()