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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import openai\n",
    "\n",
    "from langchain_openai.chat_models import ChatOpenAI\n",
    "from langchain.chains import ConversationalRetrievalChain\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_community.document_loaders import TextLoader\n",
    "from langchain_community.vectorstores import Chroma\n",
    "from langchain.memory import ConversationBufferWindowMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv()) # read local .env file\n",
    "\n",
    "openai.api_key  = os.environ['OPENAI_API_KEY']\n",
    "\n",
    "llm_name = \"gpt-3.5-turbo\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_db(file, chain_type, k):\n",
    "    # load transcript\n",
    "    transcript = TextLoader(file).load()\n",
    "    # split documents\n",
    "    text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=70)\n",
    "    docs = text_splitter.split_documents(transcript)\n",
    "    # define embedding\n",
    "    embeddings = OpenAIEmbeddings()                                                     # will be different for Cohere AI\n",
    "    # create vector database from data\n",
    "    db = Chroma.from_documents(docs, embeddings)\n",
    "    # define retriever\n",
    "    retriever = db.as_retriever(search_type=\"similarity\", search_kwargs={\"k\": k})\n",
    "    # retrieval_chain = create_retrieval_chain(retriever, combine_docs_chain)\n",
    "\n",
    "    # create a chatbot chain. Memory is managed externally.\n",
    "    qa = ConversationalRetrievalChain.from_llm(\n",
    "        llm = ChatOpenAI(temperature=0),                      #### Prompt Template is yet to be created\n",
    "        chain_type=chain_type,                                #### Refine \n",
    "        retriever=retriever, \n",
    "        return_source_documents=True,\n",
    "        return_generated_question=True,\n",
    "        # memory=memory\n",
    "    )\n",
    "    \n",
    "    return qa "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def buffer(history, buff):\n",
    "    # basically a filter function\n",
    "    # takes the chat history, ensures only buff latest elements exist\n",
    "    if len(history) > buff :\n",
    "        print(len(history)>buff)\n",
    "        return history[-buff:]\n",
    "    else:\n",
    "        return history"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "chat_history = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/maxx/.conda/envs/vcdeploy/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    }
   ],
   "source": [
    "qa = load_db(\"./sample.txt\", 'stuff', 4)\n",
    "query = \"Namaste! I need your help\"\n",
    "result = qa({'question': query, 'chat_history': chat_history}) #######################################"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "langchain.chains.conversational_retrieval.base.ConversationalRetrievalChain"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(qa)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Namaste! I'm here to help. What do you need assistance with?\""
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "answer = result['answer']\n",
    "answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'question': 'Namaste! I need your help',\n",
       " 'chat_history': [],\n",
       " 'answer': \"Namaste! I'm here to help. What do you need assistance with?\",\n",
       " 'source_documents': [Document(page_content='~160~Aurora nodded and waved her magic wand, casting a spell that spread throughout the forest. From that day on, the animals frolicked and played in harmony, their hearts filled with joy and gratitude.\\n~180~As Sammy climbed down from the Golden Acorn Tree, he felt a warm glow of happiness inside. He may have only found one golden acorn, but he had discovered something even more precious – the power of kindness and the magic of friendship.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~120~\"Yes, indeed! And I am here to grant you a wish for finding the Golden Acorn Tree,\" said Aurora with a smile.\\n~140~Sammy thought for a moment, his little squirrel brain buzzing with ideas. Finally, he knew exactly what he wanted. \"I wish for all the animals in the forest to be happy and healthy forever,\" he declared.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~10~Once upon a time in the lush green forest,\\n~13~there lived a curious little squirrel named Sammy.\\n~25~Sammy had soft, brown fur and big, bright eyes that sparkled with excitement. He loved exploring every nook and cranny of the forest, searching for new adventures.', metadata={'source': './sample.txt'})],\n",
       " 'generated_question': 'Namaste! I need your help'}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "chat_history.extend([(query, result['answer'])])\n",
    "chat_history = buffer(chat_history,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What is the moral of the story?\"\n",
    "result = qa({\"question\": query, \"chat_history\": chat_history}) #######################################"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'question': 'What is the moral of the story?',\n",
       " 'chat_history': [('Namaste! I need your help',\n",
       "   \"Namaste! I'm here to help. What do you need assistance with?\")],\n",
       " 'answer': 'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.',\n",
       " 'source_documents': [Document(page_content='~160~Aurora nodded and waved her magic wand, casting a spell that spread throughout the forest. From that day on, the animals frolicked and played in harmony, their hearts filled with joy and gratitude.\\n~180~As Sammy climbed down from the Golden Acorn Tree, he felt a warm glow of happiness inside. He may have only found one golden acorn, but he had discovered something even more precious – the power of kindness and the magic of friendship.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~200~And so, with a twinkle in his eye and a skip in his step, Sammy the squirrel continued his adventures in the enchanted forest, knowing that with a little bit of courage and a lot of love, anything was possible.\\n~220~The end.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~80~Excitedly, Sammy climbed up the tree and plucked a golden acorn from a branch. Suddenly, he heard a tiny voice coming from the acorn. \"Hello there, young squirrel! I am Aurora, the guardian of the Golden Acorn Tree,\" said the voice.\\n~100~Sammy looked around in amazement until he spotted a tiny fairy perched on the golden acorn. \"Wow, you\\'re a fairy!\" exclaimed Sammy, his eyes shining with delight.', metadata={'source': './sample.txt'})],\n",
       " 'generated_question': 'What is the moral of the story?'}"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "answer = result['answer']\n",
    "answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "chat_history.extend([(query,result['answer'])])\n",
    "chat_history = buffer(chat_history,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"Can you give a relevant title to the story?\"\n",
    "result = qa({\"question\": query, \"chat_history\": chat_history}) #######################################"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'question': 'Can you give a relevant title to the story?',\n",
       " 'chat_history': [('Namaste! I need your help',\n",
       "   \"Namaste! I'm here to help. What do you need assistance with?\"),\n",
       "  ('What is the moral of the story?',\n",
       "   'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.')],\n",
       " 'answer': 'A relevant title for the story could be \"Sammy\\'s Enchanted Forest Adventure.\"',\n",
       " 'source_documents': [Document(page_content='~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~160~Aurora nodded and waved her magic wand, casting a spell that spread throughout the forest. From that day on, the animals frolicked and played in harmony, their hearts filled with joy and gratitude.\\n~180~As Sammy climbed down from the Golden Acorn Tree, he felt a warm glow of happiness inside. He may have only found one golden acorn, but he had discovered something even more precious – the power of kindness and the magic of friendship.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~200~And so, with a twinkle in his eye and a skip in his step, Sammy the squirrel continued his adventures in the enchanted forest, knowing that with a little bit of courage and a lot of love, anything was possible.\\n~220~The end.', metadata={'source': './sample.txt'}),\n",
       "  Document(page_content='~10~Once upon a time in the lush green forest,\\n~13~there lived a curious little squirrel named Sammy.\\n~25~Sammy had soft, brown fur and big, bright eyes that sparkled with excitement. He loved exploring every nook and cranny of the forest, searching for new adventures.', metadata={'source': './sample.txt'})],\n",
       " 'generated_question': 'What is a relevant title for the story?'}"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A relevant title for the story could be \"Sammy\\'s Enchanted Forest Adventure.\"'"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "answer = result['answer']\n",
    "answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "chat_history.extend([(query,result['answer'])])\n",
    "chat_history = buffer(chat_history,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"which timestamp resembles moral of the story?\"\n",
    "result = qa({\"question\": query, \"chat_history\": chat_history}) #######################################"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The timestamp ~180~ where Sammy discovers the power of kindness and the magic of friendship best represents the moral of the story.'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "answer = result['answer']\n",
    "answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "chat_history.extend([(query,result['answer'])])\n",
    "chat_history = buffer(chat_history,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('What is the moral of the story?',\n",
       "  'The moral of the story is that kindness, friendship, courage, and love can lead to magical adventures and wonderful experiences.'),\n",
       " ('Can you give a relevant title to the story?',\n",
       "  'A relevant title for the story could be \"Sammy\\'s Enchanted Forest Adventure.\"'),\n",
       " ('which timestamp resembles moral of the story?',\n",
       "  'The timestamp ~180~ where Sammy discovers the power of kindness and the magic of friendship best represents the moral of the story.')]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat_history"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**The Defalut Buffer Memory that store entire chat and provides it as context to the next conversation** ⬆"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Memory : Conv Buffer Window Memory (k=6) / Conv Summ Buff Memory (max_token_limit=650)\n",
    "- Chain Type : Refine\n",
    "- Prompt : Template Fine-Tuning\n",
    "- Deployment : Gunicorn / Streamlit ? "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "References: \n",
    "https://python.langchain.com/docs/use_cases/question_answering/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://python.langchain.com/docs/modules/memory/types/token_buffer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'~40~One sunny morning, as Sammy scampered through the trees, he stumbled upon a mysterious path he had never seen before. Intrigued, he decided to follow it. The path led him deeper and deeper into the forest until he reached a clearing filled with colorful flowers and fluttering butterflies.'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict(result['source_documents'][1])['page_content']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "pattern = r'~(\\d+)~'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "backlinked_docs = [result['source_documents'][i].page_content for i in range(len(result['source_documents']))]\n",
    "timestamps = list(map(lambda s: int(re.search(pattern, s).group(1)) if re.search(pattern, s) else None, backlinked_docs))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'timestamps': [160, 40, 120, 10],\n",
       " 'answer': \"Namaste! I'm here to help. What do you need assistance with?\"}"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict(timestamps=timestamps, answer=result['answer'])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "vchad",
   "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.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}