209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366 | class ChromaStore:
def __init__(
self,
rag_model_name,
crawled_files_data_path,
chroma_file_path,
generation_llm,
) -> None:
self.rag_model_name = rag_model_name
self.device = find_device()
self.hf_embedding_function = HuggingFaceBgeEmbeddings(
model_name=self.rag_model_name,
model_kwargs={"device": self.device},
encode_kwargs={"normalize_embeddings": True},
)
self.crawled_files_data_path = crawled_files_data_path
self.chroma_file_path = chroma_file_path
self.system_prompt = (
"You are an assistant for question-answering tasks related to OpenML. "
"Use the following pieces of retrieved context to answer "
"the question. You must return instructions with code, always with code"
"\n\n"
"{context}"
)
self.contextualize_q_system_prompt = (
"Given a chat history and the latest user question "
"which might reference context in the chat history about OpenML, "
"formulate a standalone question which can be understood "
"without the chat history. If the question can be answer withou previous context"
"also reformulate the question. Do NOT answer the question, "
"just reformulate it if needed and otherwise return it as is."
)
self.generation_llm = generation_llm
def read_data_and_embed(self): # inference
"""
Description: This function is used to read the crawled data and embed it using the Hugging Face model.
"""
if not os.path.exists(self.crawled_files_data_path):
print("Crawled data does not exist. Please run the crawler first.")
return
df = pd.read_csv(self.crawled_files_data_path)
df["joined"] = df.apply(self._join_columns, axis=1)
docs = DataFrameLoader(df, page_content_column="joined").load()
# Splitting the document texts into smaller chunks
docs_texts = self._split_documents(docs)
# Convert metadata values to strings
for doc in docs_texts:
doc.metadata = {k: str(v) for k, v in doc.metadata.items()}
print("Creating the vector store")
Chroma.from_documents(
documents=docs_texts,
embedding=self.hf_embedding_function,
persist_directory=self.chroma_file_path,
)
def _join_columns(self, row) -> str:
"""
Joins specified columns of a row into a single string.
"""
columns = [
"URL",
"Body Text",
"Header Links Text",
"H1",
"H2",
"H3",
"H4",
"Title",
]
return ", ".join(
f"{col.lower().replace(' ', '_')}: {row[col]}" for col in columns
)
def _split_documents(self, docs):
"""
Splits documents into chunks using RecursiveCharacterTextSplitter.
"""
splitter = RecursiveCharacterTextSplitter(
chunk_size=5000, chunk_overlap=0, separators=[" ", ",", "\n"]
)
return splitter.split_documents(docs)
def setup_inference(self, session_id: str) -> None:
"""
Description: This function is used to setup the inference for the bot.
"""
self.store = {}
self.session_id = session_id
self.vectorstore = Chroma(
persist_directory=self.chroma_file_path,
embedding_function=self.hf_embedding_function,
)
self.retriever = self.vectorstore.as_retriever(search_kwargs={"k": 1})
def openml_page_search(self, input: str):
"""
Description: Use the Chroma vector store to search for the most relevant page to the input question , contextualize the question and answer it.
"""
### Contextualize question ###
contextualize_q_prompt = ChatPromptTemplate.from_messages(
[
("system", self.contextualize_q_system_prompt),
MessagesPlaceholder("chat_history"),
("human", "{input}"),
]
)
history_aware_retriever = create_history_aware_retriever(
self.generation_llm, self.retriever, contextualize_q_prompt
)
### Answer question ###
qa_prompt = ChatPromptTemplate.from_messages(
[
("system", self.system_prompt),
MessagesPlaceholder("chat_history"),
("human", "{input}"),
]
)
question_answer_chain = create_stuff_documents_chain(
self.generation_llm, qa_prompt
)
rag_chain = create_retrieval_chain(
history_aware_retriever, question_answer_chain
)
conversational_rag_chain = RunnableWithMessageHistory(
rag_chain,
get_session_history,
input_messages_key="input",
history_messages_key="chat_history",
output_messages_key="answer",
)
answer = conversational_rag_chain.stream(
{"input": f"{input}"},
config={
"configurable": {"session_id": self.session_id}
}, # constructs a key "abc123" in `store`.
)
return answer
|