File size: 28,643 Bytes
337af81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.append(\"..\")\n",
    "import os.path\n",
    "import pandas as pd\n",
    "import time\n",
    "from tqdm import tqdm\n",
    "import chromadb\n",
    "from openai import OpenAI\n",
    "import json\n",
    "\n",
    "from langchain.vectorstores import Chroma\n",
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.chains import RetrievalQAWithSourcesChain\n",
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.vectorstores import Qdrant\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.memory import ConversationSummaryMemory, ConversationBufferMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class DeepInfraEmbeddings:\n",
    "    def __init__(self, api_key, base_url, model=\"BAAI/bge-base-en-v1.5\"):\n",
    "        self.client = OpenAI(api_key=api_key, base_url=base_url)\n",
    "        self.model = model\n",
    "\n",
    "    def embed_documents(self, texts):\n",
    "        if isinstance(texts, str):\n",
    "            texts = [texts]\n",
    "\n",
    "        embeddings = self.client.embeddings.create(\n",
    "            model=self.model,\n",
    "            input=texts,\n",
    "            encoding_format=\"float\"\n",
    "        )\n",
    "\n",
    "        return [embedding.embedding for embedding in embeddings.data]\n",
    "\n",
    "    def embed_query(self, text):\n",
    "        return self.embed_documents([text])[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/rupesh/miniconda3/envs/test/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:141: LangChainDeprecationWarning: The class `Chroma` was deprecated in LangChain 0.2.9 and will be removed in 0.4. An updated version of the class exists in the langchain-chroma package and should be used instead. To use it run `pip install -U langchain-chroma` and import as `from langchain_chroma import Chroma`.\n",
      "  warn_deprecated(\n"
     ]
    }
   ],
   "source": [
    "COLLECTION_NAME = \"big-basket-products-all\"\n",
    "\n",
    "# Create Chroma client\n",
    "# client = chromadb.Client()\n",
    "client = chromadb.PersistentClient(path=os.path.join(os.getcwd(), 'vector_stores'))\n",
    "\n",
    "# Load data\n",
    "file_path = os.path.join('./data/bigBasketProducts.csv')\n",
    "df = pd.read_csv(file_path)\n",
    "# df = df[:1000]\n",
    "metadatas = [{'source': int(df.loc[i][0]), 'row': i} for i in range(len(df))]\n",
    "docs = df.apply(lambda x: x.to_json(), axis=1).tolist()\n",
    "\n",
    "# Initialize DeepInfraEmbeddings with your API key and base URL\n",
    "embeddings = DeepInfraEmbeddings(\n",
    "    api_key=\"7E4hdDQrPP9mLi52rX4zCkJ2rFKIadOk\",\n",
    "    base_url=\"https://api.deepinfra.com/v1/openai\"\n",
    ")\n",
    "\n",
    "# Create Chroma collection\n",
    "vector_store = Chroma(\n",
    "    collection_name=COLLECTION_NAME,\n",
    "    embedding_function=embeddings,  # Pass the DeepInfraEmbeddings instance\n",
    "    client=client,\n",
    "    persist_directory = os.path.join(os.getcwd(), 'vector_stores')\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "retriever = vector_store.as_retriever(search_kwargs={\"k\": 5})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/rupesh/miniconda3/envs/test/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:141: LangChainDeprecationWarning: The method `BaseRetriever.get_relevant_documents` was deprecated in langchain-core 0.1.46 and will be removed in 0.3.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    }
   ],
   "source": [
    "docs = retriever.get_relevant_documents(\"what is skin care?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "id None\n",
      "metadata {'row': 20544, 'source': 20545}\n",
      "page_content {\"index\":20545,\"product\":\"Vitamin E Face Wash\",\"category\":\"Beauty & Hygiene\",\"sub_category\":\"Skin Care\",\"brand\":\"INATUR \",\"sale_price\":315.0,\"market_price\":450.0,\"type\":\"Face Care\",\"rating\":null,\"description\":\"Inatur Vitamin E Face Cleanser is a mild and creamy formulation that removes dirt, impurities, and make-up gently. Being rich in anti-oxidants, it is effective in preserving the moisture balance of the skin. It leaves the skin nourished and hydrated making it look, soft, clean & healthy.\"}\n",
      "type Document\n",
      "id None\n",
      "metadata {'row': 8225, 'source': 8226}\n",
      "page_content {\"index\":8226,\"product\":\"Face Wash - Oily Skin\",\"category\":\"Beauty & Hygiene\",\"sub_category\":\"Men's Grooming\",\"brand\":\"USTRAA\",\"sale_price\":194.0,\"market_price\":199.0,\"type\":\"Face & Body\",\"rating\":3.0,\"description\":\"This face wash with basil and lime extracts gives a younger, fresher and oil-free appearance. This face wash checks acne and controls oil on the face with the help of salicylic acid. If you have an oily skin, then this is the skin care you need. This product is completely paraben and sulphate free.\"}\n",
      "type Document\n",
      "id None\n",
      "metadata {'row': 16313, 'source': 16314}\n",
      "page_content {\"index\":16314,\"product\":\"Face Wash - Oily Skin\",\"category\":\"Beauty & Hygiene\",\"sub_category\":\"Skin Care\",\"brand\":\"USTRAA\",\"sale_price\":194.0,\"market_price\":199.0,\"type\":\"Face & Body\",\"rating\":3.0,\"description\":\"This face wash with basil and lime extracts gives a younger, fresher and oil-free appearance. This face wash checks acne and controls oil on the face with the help of salicylic acid. If you have an oily skin, then this is the skin care you need. This product is completely paraben and sulphate free.\"}\n",
      "type Document\n",
      "id None\n",
      "metadata {'row': 7248, 'source': 7249}\n",
      "page_content {\"index\":7249,\"product\":\"Active Range Radiance Face Elixir Serum\",\"category\":\"Beauty & Hygiene\",\"sub_category\":\"Skin Care\",\"brand\":\"Organic Harvest\",\"sale_price\":1695.75,\"market_price\":1995.0,\"type\":\"Face Care\",\"rating\":null,\"description\":\"A light weight organic beauty fluid for face brightening and anti ageing. It is a special formulation of organic ingredients that help the skin retain its youthful appearance. The beauty serum is a unique blend of oils and organic ingredients formulated to help skin look young and healthy. Aimed to give a glowing skin and to provide deep nourishment, relieve dark circles and repairs pigmentation specially formulated to help fight the signs of skin ageing.\"}\n",
      "type Document\n",
      "id None\n",
      "metadata {'row': 4102, 'source': 4103}\n",
      "page_content {\"index\":4103,\"product\":\"Party Glow Facial Kit\",\"category\":\"Beauty & Hygiene\",\"sub_category\":\"Skin Care\",\"brand\":\"Vlcc\",\"sale_price\":167.05,\"market_price\":257.0,\"type\":\"Face Care\",\"rating\":4.1,\"description\":\"A revolutionary, 6 Step Facial System that helps you get that Facial Glow at the convenience of your home. It is a Do It Yourself Facial Kit, which allows you to get your facial done, all by yourself. It comes in the form of a Kit which combines all the steps. It helps in sloughing off dead skin cells. It also hydrates the skin and maintains its oil balance. This facial kit helps achieve a blemish-free, radiant complexion. It targets the skin areas for dullness and dehydration, making the skin soft and beautiful.Tip: Following a regular skin care regime can help you achieve flawless skin. For more tips on skin care, visit bigbasket lifestyle blog, Click Here to visit bigbasket\\u2019s lifestyle blog\"}\n",
      "type Document\n"
     ]
    }
   ],
   "source": [
    "for doc in docs:\n",
    "    for k, v in doc:\n",
    "        print(k, v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "class NeuralSearcher:\n",
    "\n",
    "    def __init__(self, collection_name: str):\n",
    "        self.client = chromadb.PersistentClient(path=os.path.join(os.getcwd(), 'vector_stores'))\n",
    "        \n",
    "        self.embeddings = DeepInfraEmbeddings(\n",
    "                        api_key=\"7E4hdDQrPP9mLi52rX4zCkJ2rFKIadOk\",\n",
    "                        base_url=\"https://api.deepinfra.com/v1/openai\"\n",
    "                    )\n",
    "        self.vector_store = Chroma(\n",
    "                        collection_name=COLLECTION_NAME,\n",
    "                        embedding_function=self.embeddings,  # Pass the DeepInfraEmbeddings instance\n",
    "                        client=self.client,\n",
    "                        persist_directory = os.path.join(os.getcwd(), 'vector_stores')\n",
    "                    )\n",
    "        \n",
    "        self.llm = ChatOpenAI(\n",
    "            model='meta-llama/Meta-Llama-3.1-70B-Instruct',\n",
    "            api_key=\"7E4hdDQrPP9mLi52rX4zCkJ2rFKIadOk\",\n",
    "            base_url=\"https://api.deepinfra.com/v1/openai\",\n",
    "            max_tokens = 70000\n",
    "        )\n",
    "        \n",
    "        self.memory = ConversationSummaryMemory(\n",
    "            llm=self.llm,\n",
    "            memory_key=\"chat_history\",\n",
    "            return_messages=True,\n",
    "            input_key=\"question\",\n",
    "            output_key='answer'\n",
    "        )\n",
    "        \n",
    "        prompt_template = '''\n",
    "        About: You are a Product Recommendation Agent who gets his context from the retrieved descriptions of the products that matches best with the User's query. \n",
    "        User is a human who, as a customer, wants to buy a product from this application.\n",
    "\n",
    "        Given below is the summary of conversation between you (AI) and the user (Human):\n",
    "        Context: {chat_history}\n",
    "\n",
    "        Now use this summary of previous conversations and the retrieved descriptions of products to answer the following question asked by the user:\n",
    "        Question: {question}\n",
    "\n",
    "        Note: \n",
    "        - Give your answer in a compreshenive manner in enumerated format.\n",
    "        - Do not generate any information on your own, striclty stick to the provided data. \n",
    "        - Also, do not repeat the information that is already present in the context.\n",
    "        - If, you feel there is redundant information (or) an product is being described twice, specify that as well in the response.\n",
    "        - The tone of the answer should be like a polite and friendly AI Assistant.\n",
    "        '''\n",
    "        self.PROMPT = PromptTemplate(\n",
    "            template=prompt_template, input_variables=[\"chat_history\", \"question\"]\n",
    "        )\n",
    "\n",
    "    def search(self, question: str, num_results: int, filter_: dict = None) -> dict:\n",
    "        chain = RetrievalQAWithSourcesChain.from_chain_type(\n",
    "            llm=self.llm,\n",
    "            chain_type=\"stuff\",\n",
    "            retriever=self.vector_store.as_retriever(search_kwargs={'k':num_results}),\n",
    "            memory=self.memory,\n",
    "            return_source_documents=True,\n",
    "        )\n",
    "\n",
    "        gen_prompt = self.PROMPT.format(question=question, chat_history=self.memory.load_memory_variables({})['chat_history'][0].content)\n",
    "        start_time = time.time()\n",
    "        res = chain(gen_prompt)\n",
    "        print(f\"Search took {time.time() - start_time} seconds\")\n",
    "\n",
    "        ret = {}\n",
    "        ret['answer'] = res['answer']\n",
    "\n",
    "        srcs = [json.loads(row.page_content) for row in res['source_documents']]\n",
    "\n",
    "        df = pd.DataFrame(srcs)\n",
    "        df = df.fillna('null')\n",
    "        # df.set_index('product', inplace=True)\n",
    "\n",
    "        # df1 = df[['product','brand', 'sale_price', 'rating', 'description', 'category', 'sub_category']]\n",
    "        df1 = df\n",
    "\n",
    "        # Remove duplicates\n",
    "        df1 = df1.drop_duplicates()\n",
    "\n",
    "        ret['products'] = df1.to_dict(orient='records')\n",
    "        return ret\n",
    "    \n",
    "    def check_memory_history(self):\n",
    "        return self.memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "neural_searcher = NeuralSearcher(collection_name=COLLECTION_NAME)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Search took 4.530710458755493 seconds\n"
     ]
    }
   ],
   "source": [
    "q = \"Suggest me some top 5 Beverages products?\"\n",
    "num_results = 5\n",
    "res = neural_searcher.search(question=q, num_results=num_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I don't know.\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(res['answer'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'answer': \"I don't know.\\n\\n\",\n",
       " 'products': [{'index': 14541,\n",
       "   'product': 'Perfume - Ultra Sensual',\n",
       "   'category': 'Beauty & Hygiene',\n",
       "   'sub_category': \"Men's Grooming\",\n",
       "   'brand': 'Wild Stone',\n",
       "   'sale_price': 569.05,\n",
       "   'market_price': 599.0,\n",
       "   'type': \"Men's Deodorants\",\n",
       "   'rating': 4.5,\n",
       "   'description': 'A bright, fresh and energetic fragrance with a touch of Woody & Musky notes that give it an exciting twist  For Beauty tips, tricks & more visitÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'index': 24485,\n",
       "   'product': 'Perfume - Ultra Sensual',\n",
       "   'category': 'Beauty & Hygiene',\n",
       "   'sub_category': 'Fragrances & Deos',\n",
       "   'brand': 'Wild Stone',\n",
       "   'sale_price': 569.05,\n",
       "   'market_price': 599.0,\n",
       "   'type': \"Men's Deodorants\",\n",
       "   'rating': 4.5,\n",
       "   'description': 'A bright, fresh and energetic fragrance with a touch of Woody & Musky notes that give it an exciting twist  For Beauty tips, tricks & more visitÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'index': 7382,\n",
       "   'product': 'Be Tempted Eau De Parfum',\n",
       "   'category': 'Beauty & Hygiene',\n",
       "   'sub_category': 'Fragrances & Deos',\n",
       "   'brand': 'Dkny',\n",
       "   'sale_price': 3485.0,\n",
       "   'market_price': 4100.0,\n",
       "   'type': 'Eau De Parfum',\n",
       "   'rating': 5.0,\n",
       "   'description': 'Have you ever wondered if you should? \\xa0If you dare? \\xa0Give in to the temptation with DKNY Be Tempted, a provocative delectably addictive new fragrance that expresses an overt willing and wants for sensorial seduction.'},\n",
       "  {'index': 19717,\n",
       "   'product': 'Perfume - Forest Spice',\n",
       "   'category': 'Beauty & Hygiene',\n",
       "   'sub_category': \"Men's Grooming\",\n",
       "   'brand': 'Wild Stone',\n",
       "   'sale_price': 359.4,\n",
       "   'market_price': 599.0,\n",
       "   'type': \"Men's Deodorants\",\n",
       "   'rating': 3.0,\n",
       "   'description': 'A bright, fresh and energetic fragrance with a touch of Woody & Oriental notes that give it an exciting twist  For Beauty tips, tricks & more visitÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'index': 2919,\n",
       "   'product': 'Body Deodorant - Aqua Fresh',\n",
       "   'category': 'Beauty & Hygiene',\n",
       "   'sub_category': 'Fragrances & Deos',\n",
       "   'brand': 'Wild Stone',\n",
       "   'sale_price': 169.15,\n",
       "   'market_price': 199.0,\n",
       "   'type': \"Men's Deodorants\",\n",
       "   'rating': 'null',\n",
       "   'description': 'The ultimate range of irresistible masculine fragrances. Makes Its Happen  For Beauty tips, tricks & more visitÂÂ\\xa0https://bigbasket.blog/'}]}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "mem = neural_searcher.check_memory_history()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='The human is seeking product recommendations from the Product Recommendation Agent, specifically asking for the top 5 Kitchen, Garden & Pets products, and later asks for the top 5 Beverages products. The AI is unsure and responds with \"I don\\'t know\" to both requests.')]\n"
     ]
    }
   ],
   "source": [
    "print(mem[\"chat_history\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'chat_history': [SystemMessage(content='Here is the new summary:\\n\\nThe human asks the AI for top 5 hair product suggestions. The AI provides a list of 5 hair products based on the retrieved descriptions, including a professional brush, hair roller, hair gel, and an Ayurvedic balm. The AI notes that two of the products, the Professional Brush and Professional Brush - Roller, seem to be similar, with the only difference being the addition of \"Roller\" in the latter. The human asks for more information about the first product, which is the Professional Brush. The AI provides additional details about the Professional Brush, including its category, sub-category, brand, price, type, rating, and description, and reiterates that it seems similar to the Professional Brush - Roller product. The human then asks if there are any other similar products, and the AI responds by mentioning the Professional Brush - Roller as a similar product, noting that it has almost identical specifications and description as the Professional Brush.')]}"
      ]
     },
     "execution_count": 128,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mem"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Search took 26.596819162368774 seconds\n"
     ]
    }
   ],
   "source": [
    "q = \"Tell me more about the first product\"\n",
    "num_results = 5\n",
    "res = neural_searcher.search(question=q, num_results=num_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm happy to help you with your question about the first product!\n",
      "\n",
      "Based on our previous conversation, the first product I mentioned was the \"Professional Brush\". Here are some additional details about this product:\n",
      "\n",
      "1. **Product Name**: Professional Brush\n",
      "2. **Category**: Beauty & Hygiene\n",
      "3. **Sub-Category**: Hair Care\n",
      "4. **Brand**: Salon\n",
      "5. **Sale Price**: ₹500.0\n",
      "6. **Market Price**: ₹500.0\n",
      "7. **Type**: Tools & Accessories\n",
      "8. **Rating**: 5.0\n",
      "9. **Description**: The best brushes will render application effortless and optimise the performance of your makeup products to their full potential.\n",
      "\n",
      "Please note that this product seems to be similar to the \"Professional Brush - Roller\" product, with the only difference being the addition of \"Roller\" in the latter. If you'd like to know more about the differences between these two products, I'd be happy to help!\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(res['answer'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'answer': 'I\\'m happy to help you with your question about the first product!\\n\\nBased on our previous conversation, the first product I mentioned was the \"Professional Brush\". Here are some additional details about this product:\\n\\n1. **Product Name**: Professional Brush\\n2. **Category**: Beauty & Hygiene\\n3. **Sub-Category**: Hair Care\\n4. **Brand**: Salon\\n5. **Sale Price**: ₹500.0\\n6. **Market Price**: ₹500.0\\n7. **Type**: Tools & Accessories\\n8. **Rating**: 5.0\\n9. **Description**: The best brushes will render application effortless and optimise the performance of your makeup products to their full potential.\\n\\nPlease note that this product seems to be similar to the \"Professional Brush - Roller\" product, with the only difference being the addition of \"Roller\" in the latter. If you\\'d like to know more about the differences between these two products, I\\'d be happy to help!\\n\\n',\n",
       " 'products': [{'product': 'Professional Brush - Roller',\n",
       "   'brand': 'Salon',\n",
       "   'sale_price': 500.0,\n",
       "   'rating': 4.0,\n",
       "   'description': 'The bestÀš\\xa0brushesÀš\\xa0will render application effortless and optimise the performance of your makeup products to their full potential  For Beauty tips, tricks & more visit\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Professional Brush',\n",
       "   'brand': 'Salon',\n",
       "   'sale_price': 500.0,\n",
       "   'rating': 5.0,\n",
       "   'description': 'The bestÂÂ\\xa0brushesÂÂ\\xa0will render application effortless and optimise the performance of your makeup products to their full potential  For Beauty tips, tricks & more visitÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Hair Roller - Medium 20 mm',\n",
       "   'brand': 'Daiou',\n",
       "   'sale_price': 300.0,\n",
       "   'rating': 4.0,\n",
       "   'description': 'For Hair stylers  For Beauty tips, tricks & more visitÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Balm - Ultra Power',\n",
       "   'brand': 'Zandu',\n",
       "   'sale_price': 42.0,\n",
       "   'rating': 4.4,\n",
       "   'description': 'Ayurvedic Proprietary Medicine For External Use Only  For Beauty tips, tricks & more visitÂÂÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Hair Care Kit - Anti Hair Fall',\n",
       "   'brand': 'Mamaearth',\n",
       "   'sale_price': 999.0,\n",
       "   'rating': 2.8,\n",
       "   'description': 'Hi! I am Mamaearths Anti Hair Fall Control Kit. I am full of natural and organic bio-actives which help promote hair fall control & hair regrowth. I follow a 4 step process from root to tip to ensure I fix all your hair issues. Use me regularly and you wont ever need another hair products.'}]}"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Search took 21.11023235321045 seconds\n"
     ]
    }
   ],
   "source": [
    "q = \"Are there any other similar products?\"\n",
    "num_results = 5\n",
    "res = neural_searcher.search(question=q, num_results=num_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Based on the provided data, here are some similar products to the Professional Brush:\n",
      "\n",
      "1. **Professional Brush - Roller**: This product seems to be very similar to the Professional Brush, with the only difference being the addition of \"Roller\" in the name. The description and specifications are almost identical. (\n"
     ]
    }
   ],
   "source": [
    "print(res['answer'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'answer': 'Based on the provided data, here are some similar products to the Professional Brush:\\n\\n1. **Professional Brush - Roller**: This product seems to be very similar to the Professional Brush, with the only difference being the addition of \"Roller\" in the name. The description and specifications are almost identical. (',\n",
       " 'products': [{'product': 'Professional Brush - Roller',\n",
       "   'brand': 'Salon',\n",
       "   'sale_price': 500.0,\n",
       "   'rating': 4.0,\n",
       "   'description': 'The bestÀš\\xa0brushesÀš\\xa0will render application effortless and optimise the performance of your makeup products to their full potential  For Beauty tips, tricks & more visit\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Professional Brush',\n",
       "   'brand': 'Salon',\n",
       "   'sale_price': 500.0,\n",
       "   'rating': 5.0,\n",
       "   'description': 'The bestÂÂ\\xa0brushesÂÂ\\xa0will render application effortless and optimise the performance of your makeup products to their full potential  For Beauty tips, tricks & more visitÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Hair Roller - Medium 20 mm',\n",
       "   'brand': 'Daiou',\n",
       "   'sale_price': 300.0,\n",
       "   'rating': 4.0,\n",
       "   'description': 'For Hair stylers  For Beauty tips, tricks & more visitÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Balm - Ultra Power',\n",
       "   'brand': 'Zandu',\n",
       "   'sale_price': 42.0,\n",
       "   'rating': 4.4,\n",
       "   'description': 'Ayurvedic Proprietary Medicine For External Use Only  For Beauty tips, tricks & more visitÂÂÂ\\xa0https://bigbasket.blog/'},\n",
       "  {'product': 'Hair Spray',\n",
       "   'brand': 'Novagold',\n",
       "   'sale_price': 1200.0,\n",
       "   'rating': 1.0,\n",
       "   'description': 'Info not in English  For Beauty tips, tricks & more visitÀš\\xa0https://bigbasket.blog/'}]}"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import yaml\n",
    "# Read YAML file\n",
    "with open(\"config.yaml\", 'r') as stream:\n",
    "    data_loaded = yaml.safe_load(stream)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'COLLECTION_NAME': 'big-basket-products-all', 'API_KEY': ''}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data_loaded"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "test",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}