File size: 26,514 Bytes
72224e5
 
ad4a98f
 
 
 
 
 
 
 
 
 
 
 
 
508c67d
 
 
 
 
 
f6c90f4
508c67d
 
ad4a98f
 
 
 
 
 
 
 
 
72224e5
 
ad4a98f
72224e5
 
 
 
 
 
 
 
 
 
ad4a98f
72224e5
 
 
 
 
 
 
ad4a98f
 
 
 
508c67d
ad4a98f
508c67d
ad4a98f
f6c90f4
ad4a98f
 
 
 
 
 
508c67d
 
 
 
 
 
 
 
ad4a98f
 
 
 
 
 
 
 
 
 
 
72224e5
 
508c67d
72224e5
 
 
 
 
 
 
 
508c67d
72224e5
 
 
 
 
 
 
 
 
 
ad4a98f
 
508c67d
ad4a98f
 
 
 
 
 
508c67d
 
 
 
 
ad4a98f
 
 
 
 
 
 
 
 
 
 
508c67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6c90f4
508c67d
 
 
 
 
 
 
ad4a98f
 
72224e5
 
508c67d
72224e5
 
 
 
 
508c67d
72224e5
 
508c67d
72224e5
 
 
 
 
 
 
 
 
 
508c67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72224e5
 
508c67d
72224e5
 
 
 
 
 
 
508c67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72224e5
 
508c67d
72224e5
 
 
 
 
508c67d
 
 
 
 
 
72224e5
 
508c67d
72224e5
 
 
 
 
 
 
 
508c67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72224e5
 
508c67d
72224e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508c67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72224e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508c67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72224e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Your First RAQA Application\n",
    "\n",
    "In this notebook, we'll walk you through each of the components that are involved in a simple RAQA application. \n",
    "\n",
    "We won't be leveraging any fancy tools, just the OpenAI Python SDK, Numpy, and some classic Python.\n",
    "\n",
    "This was done with Python 3.11.4."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's look at a rather complicated looking visual representation of a basic RAQA application.\n",
    "\n",
    "<img src=\"https://i.imgur.com/LCNkd1A.png\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Imports and Utility \n",
    "\n",
    "We're just doing some imports and enabling `async` to work within the Jupyter environment here, nothing too crazy!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter\n",
    "from aimakerspace.vectordatabase import VectorDatabase\n",
    "import asyncio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nest_asyncio\n",
    "nest_asyncio.apply()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Documents\n",
    "\n",
    "We'll be concerning ourselves with this part of the flow in the following section:\n",
    "\n",
    "<img src=\"https://i.imgur.com/wBYB2x3.png\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Loading Source Documents\n",
    "\n",
    "So, first things first, we need some documents to work with. \n",
    "\n",
    "While we could work directly with the `.txt` files (or whatever file-types you wanted to extend this to) we can instead do some batch processing of those documents at the beginning in order to store them in a more machine compatible format. \n",
    "\n",
    "In this case, we're going to parse our text file into a single document in memory.\n",
    "\n",
    "Let's look at the relevant bits of the `TextFileLoader` class:\n",
    "\n",
    "```python\n",
    "def load_file(self):\n",
    "        with open(self.path, \"r\", encoding=self.encoding) as f:\n",
    "            self.documents.append(f.read())\n",
    "```\n",
    "\n",
    "We're simply loading the document using the built in `open` method, and storing that output in our `self.documents` list.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text_loader = TextFileLoader(\"data/KingLear.txt\")\n",
    "documents = text_loader.load_documents()\n",
    "len(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ACT I\n",
      "SCENE I. King Lear's palace.\n",
      "Enter KENT, GLOUCESTER, and EDMUND\n",
      "KENT\n",
      "I thought the king had m\n"
     ]
    }
   ],
   "source": [
    "print(documents[0][:100])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Splitting Text Into Chunks\n",
    "\n",
    "As we can see, there is one document - and it's the entire text of King Lear.\n",
    "\n",
    "We'll want to chunk the document into smaller parts so it's easier to pass the most relevant snippets to the LLM. \n",
    "\n",
    "There is no fixed way to split/chunk documents - and you'll need to rely on some intuition as well as knowing your data *very* well in order to build the most robust system.\n",
    "\n",
    "For this toy example, we'll just split blindly on length. \n",
    "\n",
    ">There's an opportunity to clear up some terminology here, for this course we will be stick to the following: \n",
    ">\n",
    ">- \"source documents\" : The `.txt`, `.pdf`, `.html`, ..., files that make up the files and information we start with in its raw format\n",
    ">- \"document(s)\" : single (or more) text object(s)\n",
    ">- \"corpus\" : the combination of all of our documents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's take a peek visually at what we're doing here - and why it might be useful:\n",
    "\n",
    "<img src=\"https://i.imgur.com/rtM6Ci6.png\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see (though it's not specifically true in this toy example) the idea of splitting documents is to break them into managable sized chunks that retain the most relevant local context."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "189"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text_splitter = CharacterTextSplitter()\n",
    "split_documents = text_splitter.split_texts(documents)\n",
    "len(split_documents)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's take a look at some of the documents we've managed to split."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\"\\ufeffACT I\\nSCENE I. King Lear's palace.\\nEnter KENT, GLOUCESTER, and EDMUND\\nKENT\\nI thought the king had more affected the Duke of\\nAlbany than Cornwall.\\nGLOUCESTER\\nIt did always seem so to us: but now, in the\\ndivision of the kingdom, it appears not which of\\nthe dukes he values most; for equalities are so\\nweighed, that curiosity in neither can make choice\\nof either's moiety.\\nKENT\\nIs not this your son, my lord?\\nGLOUCESTER\\nHis breeding, sir, hath been at my charge: I have\\nso often blushed to acknowledge him, that now I am\\nbrazed to it.\\nKENT\\nI cannot conceive you.\\nGLOUCESTER\\nSir, this young fellow's mother could: whereupon\\nshe grew round-wombed, and had, indeed, sir, a son\\nfor her cradle ere she had a husband for her bed.\\nDo you smell a fault?\\nKENT\\nI cannot wish the fault undone, the issue of it\\nbeing so proper.\\nGLOUCESTER\\nBut I have, sir, a son by order of law, some year\\nelder than this, who yet is no dearer in my account:\\nthough this knave came something saucily into the\\nworld before he was se\"]"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "split_documents[0:1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Embeddings and Vectors\n",
    "\n",
    "Next, we have to convert our corpus into a \"machine readable\" format. \n",
    "\n",
    "Loosely, this means turning the text into numbers. \n",
    "\n",
    "There are plenty of resources that talk about this process in great detail - I'll leave this [blog](https://txt.cohere.com/sentence-word-embeddings/) from Cohere:AI as a resource if you want to deep dive a bit. \n",
    "\n",
    "Today, we're going to talk about the actual process of creating, and then storing, these embeddings, and how we can leverage that to intelligently add context to our queries."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While this is all baked into 1 call - let's look at some of the code that powers this process:\n",
    "\n",
    "Let's look at our `VectorDatabase().__init__()`:\n",
    "\n",
    "```python\n",
    "def __init__(self, embedding_model: EmbeddingModel = None):\n",
    "        self.vectors = defaultdict(np.array)\n",
    "        self.embedding_model = embedding_model or EmbeddingModel()\n",
    "```\n",
    "\n",
    "As you can see - our vectors are merely stored as a dictionary of `np.array` objects.\n",
    "\n",
    "Secondly, our `VectorDatabase()` has a default `EmbeddingModel()` which is a wrapper for OpenAI's `text-embedding-ada-002` model. \n",
    "\n",
    "> **Quick Info About `text-embedding-ada-002`**:\n",
    "> - It has a context window of **8192** tokens\n",
    "> - It returns vectors with dimension **1536**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can call the `async_get_embeddings` method of our `EmbeddingModel()` on a list of `str` and receive a list of `float` back!\n",
    "\n",
    "```python\n",
    "async def async_get_embeddings(self, list_of_text: List[str]) -> List[List[float]]:\n",
    "        return await aget_embeddings(\n",
    "            list_of_text=list_of_text, engine=self.embeddings_model_name\n",
    "        )\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We cast those to `np.array` when we build our `VectorDatabase()`:\n",
    "\n",
    "```python\n",
    "async def abuild_from_list(self, list_of_text: List[str]) -> \"VectorDatabase\":\n",
    "        embeddings = await self.embedding_model.async_get_embeddings(list_of_text)\n",
    "        for text, embedding in zip(list_of_text, embeddings):\n",
    "            self.insert(text, np.array(embedding))\n",
    "        return self\n",
    "```\n",
    "\n",
    "And that's all we need to do!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_db = VectorDatabase()\n",
    "vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, to review what we've done so far in natural language:\n",
    "\n",
    "1. We load source documents\n",
    "2. We split those source documents into smaller chunks (documents)\n",
    "3. We send each of those documents to the `text-embedding-ada-002` OpenAI API endpoint\n",
    "4. We store each of the text representations with the vector representations as keys/values in a dictionary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Semantic Similarity\n",
    "\n",
    "The next step is to be able to query our `VectorDatabase()` with a `str` and have it return to us vectors and text that is most relevant from our corpus. \n",
    "\n",
    "We're going to use the following process to achieve this in our toy example:\n",
    "\n",
    "1. We need to embed our query with the same `EmbeddingModel()` as we used to construct our `VectorDatabase()`\n",
    "2. We loop through every vector in our `VectorDatabase()` and use a distance measure to compare how related they are\n",
    "3. We return a list of the top `k` closest vectors, with their text representations\n",
    "\n",
    "There's some very heavy optimization that can be done at each of these steps - but let's just focus on the basic pattern in this notebook.\n",
    "\n",
    "> We are using [cosine similarity](https://www.engati.com/glossary/cosine-similarity) as a distance measure in this example - but there are many many distance measures you could use - like [these](https://flavien-vidal.medium.com/similarity-distances-for-natural-language-processing-16f63cd5ba55)\n",
    "\n",
    "> We are using a rather inefficient way of calculating relative distance between the query vector and all other vectors - there are more advanced approaches that are much more efficient, like [ANN](https://towardsdatascience.com/comprehensive-guide-to-approximate-nearest-neighbors-algorithms-8b94f057d6b6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(\"ng] O my good master!\\nKING LEAR\\nPrithee, away.\\nEDGAR\\n'Tis noble Kent, your friend.\\nKING LEAR\\nA plague upon you, murderers, traitors all!\\nI might have saved her; now she's gone for ever!\\nCordelia, Cordelia! stay a little. Ha!\\nWhat is't thou say'st? Her voice was ever soft,\\nGentle, and low, an excellent thing in woman.\\nI kill'd the slave that was a-hanging thee.\\nCaptain\\n'Tis true, my lords, he did.\\nKING LEAR\\nDid I not, fellow?\\nI have seen the day, with my good biting falchion\\nI would have made them skip: I am old now,\\nAnd these same crosses spoil me. Who are you?\\nMine eyes are not o' the best: I'll tell you straight.\\nKENT\\nIf fortune brag of two she loved and hated,\\nOne of them we behold.\\nKING LEAR\\nThis is a dull sight. Are you not Kent?\\nKENT\\nThe same,\\nYour servant Kent: Where is your servant Caius?\\nKING LEAR\\nHe's a good fellow, I can tell you that;\\nHe'll strike, and quickly too: he's dead and rotten.\\nKENT\\nNo, my good lord; I am the very man,--\\nKING LEAR\\nI'll see that straight.\\nKENT\\nThat,\",\n",
       "  0.821079499257572),\n",
       " (\"her way,\\nThe news is not so tart.--I'll read, and answer.\\nExit\\n\\nALBANY\\nWhere was his son when they did take his eyes?\\nMessenger\\nCome with my lady hither.\\nALBANY\\nHe is not here.\\nMessenger\\nNo, my good lord; I met him back again.\\nALBANY\\nKnows he the wickedness?\\nMessenger\\nAy, my good lord; 'twas he inform'd against him;\\nAnd quit the house on purpose, that their punishment\\nMight have the freer course.\\nALBANY\\nGloucester, I live\\nTo thank thee for the love thou show'dst the king,\\nAnd to revenge thine eyes. Come hither, friend:\\nTell me what more thou know'st.\\nExeunt\\n\\nSCENE III. The French camp near Dover.\\nEnter KENT and a Gentleman\\nKENT\\nWhy the King of France is so suddenly gone back\\nknow you the reason?\\nGentleman\\nSomething he left imperfect in the\\nstate, which since his coming forth is thought\\nof; which imports to the kingdom so much\\nfear and danger, that his personal return was\\nmost required and necessary.\\nKENT\\nWho hath he left behind him general?\\nGentleman\\nThe Marshal of France, Monsieur La \",\n",
       "  0.8195388800733402),\n",
       " (\",\\nLay comforts to your bosom; and bestow\\nYour needful counsel to our business,\\nWhich craves the instant use.\\nGLOUCESTER\\nI serve you, madam:\\nYour graces are right welcome.\\nExeunt\\n\\nSCENE II. Before Gloucester's castle.\\nEnter KENT and OSWALD, severally\\nOSWALD\\nGood dawning to thee, friend: art of this house?\\nKENT\\nAy.\\nOSWALD\\nWhere may we set our horses?\\nKENT\\nI' the mire.\\nOSWALD\\nPrithee, if thou lovest me, tell me.\\nKENT\\nI love thee not.\\nOSWALD\\nWhy, then, I care not for thee.\\nKENT\\nIf I had thee in Lipsbury pinfold, I would make thee\\ncare for me.\\nOSWALD\\nWhy dost thou use me thus? I know thee not.\\nKENT\\nFellow, I know thee.\\nOSWALD\\nWhat dost thou know me for?\\nKENT\\nA knave; a rascal; an eater of broken meats; a\\nbase, proud, shallow, beggarly, three-suited,\\nhundred-pound, filthy, worsted-stocking knave; a\\nlily-livered, action-taking knave, a whoreson,\\nglass-gazing, super-serviceable finical rogue;\\none-trunk-inheriting slave; one that wouldst be a\\nbawd, in way of good service, and art nothing but\\nth\",\n",
       "  0.8179006492282218)]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vector_db.search_by_text(\"Your servant Kent. Where is your servant Caius?\", k=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Prompts\n",
    "\n",
    "In the following section, we'll be looking at the role of prompts - and how they help us to guide our application in the right direction.\n",
    "\n",
    "In this notebook, we're going to rely on the idea of \"zero-shot in-context learning\".\n",
    "\n",
    "This is a lot of words to say: \"We will ask it to perform our desired task in the prompt, and provide no examples.\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### XYZRolePrompt\n",
    "\n",
    "Before we do that, let's stop and think a bit about how OpenAI's chat models work. \n",
    "\n",
    "We know they have roles - as is indicated in the following API [documentation](https://platform.openai.com/docs/api-reference/chat/create#chat/create-messages)\n",
    "\n",
    "There are three roles, and they function as follows (taken directly from [OpenAI](https://platform.openai.com/docs/guides/gpt/chat-completions-api)): \n",
    "\n",
    "- `{\"role\" : \"system\"}` : The system message helps set the behavior of the assistant. For example, you can modify the personality of the assistant or provide specific instructions about how it should behave throughout the conversation. However note that the system message is optional and the model’s behavior without a system message is likely to be similar to using a generic message such as \"You are a helpful assistant.\"\n",
    "- `{\"role\" : \"user\"}` : The user messages provide requests or comments for the assistant to respond to.\n",
    "- `{\"role\" : \"assistant\"}` : Assistant messages store previous assistant responses, but can also be written by you to give examples of desired behavior.\n",
    "\n",
    "The main idea is this: \n",
    "\n",
    "1. You start with a system message that outlines how the LLM should respond, what kind of behaviours you can expect from it, and more\n",
    "2. Then, you can provide a few examples in the form of \"assistant\"/\"user\" pairs\n",
    "3. Then, you prompt the model with the true \"user\" message.\n",
    "\n",
    "In this example, we'll be forgoing the 2nd step for simplicities sake."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimakerspace.openai_utils.prompts import (\n",
    "    UserRolePrompt,\n",
    "    SystemRolePrompt,\n",
    "    AssistantRolePrompt,\n",
    ")\n",
    "\n",
    "from aimakerspace.openai_utils.chatmodel import ChatOpenAI\n",
    "\n",
    "chat_openai = ChatOpenAI()\n",
    "user_prompt_template = \"{content}\"\n",
    "user_role_prompt = UserRolePrompt(user_prompt_template)\n",
    "system_prompt_template = (\n",
    "    \"You are an expert in {expertise}, you always answer in a kind way.\"\n",
    ")\n",
    "system_role_prompt = SystemRolePrompt(system_prompt_template)\n",
    "\n",
    "messages = [\n",
    "    user_role_prompt.create_message(\n",
    "        content=\"What is the best way to write a loop?\"\n",
    "    ),\n",
    "    system_role_prompt.create_message(expertise=\"Python\"),\n",
    "]\n",
    "\n",
    "response = chat_openai.run(messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The \"best\" way to write a loop can vary depending on the specific needs and context of your program. However, in general, following some best practices can help make your loops more efficient and readable:\n",
      "\n",
      "1. Choose the appropriate loop type: Python offers different loop types, such as `for` and `while`. The choice depends on the task at hand. Use a `for` loop when you know the exact number of iterations, and a `while` loop when you want to repeat the loop until a specific condition is met.\n",
      "\n",
      "2. Initialize and update loop variables correctly: Before entering a loop, ensure that any loop variable(s) are properly initialized. Inside the loop, make sure to update the variable(s) in such a way that the loop eventually terminates.\n",
      "\n",
      "3. Keep the loop body concise: Ideally, the loop body should contain only the necessary code to perform the iterations. If the loop body becomes complex, consider breaking it down into smaller functions or using other control structures like `if` statements.\n",
      "\n",
      "4. Use meaningful variable names: It's essential to use descriptive variable names that make it easier for others (including yourself) to understand the purpose of the loop and its variables.\n",
      "\n",
      "5. Consider using built-in functions: Python offers various built-in functions, like `range()`, `enumerate()`, or `zip()`, that can simplify your loop code and make it more efficient. Be sure to explore these functions and see if they can be applied to your specific use case.\n",
      "\n",
      "6. Avoid unnecessary computations or redundant code: Make sure your loop is not performing any calculations or executing any unnecessary code within the loop body. Such calculations, if possible, can be moved outside the loop to optimize performance.\n",
      "\n",
      "7. Add comments when required: If your loop code is complex or non-intuitive, consider adding comments to explain the logic, purpose, or any important details for future readers.\n",
      "\n",
      "Remember, the \"best\" way to write a loop may depend on the specific requirements and constraints of your code. Continuously striving for simplicity, readability, and efficiency will generally lead to well-written loops.\n"
     ]
    }
   ],
   "source": [
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Retrieval Augmented Question Answering Prompt\n",
    "\n",
    "Now we can create a RAQA prompt - which will help our system behave in a way that makes sense!\n",
    "\n",
    "There is much you could do here, many tweaks and improvements to be made!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "RAQA_PROMPT_TEMPLATE = \"\"\"\n",
    "Use the provided context to answer the user's query. \n",
    "\n",
    "You may not answer the user's query unless there is specific context in the following text.\n",
    "\n",
    "If you do not know the answer, or cannot answer, please respond with \"I don't know\".\n",
    "\n",
    "Context:\n",
    "{context}\n",
    "\"\"\"\n",
    "\n",
    "raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)\n",
    "\n",
    "USER_PROMPT_TEMPLATE = \"\"\"\n",
    "User Query:\n",
    "{user_query}\n",
    "\"\"\"\n",
    "\n",
    "user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)\n",
    "\n",
    "class RetrievalAugmentedQAPipeline:\n",
    "    def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:\n",
    "        self.llm = llm\n",
    "        self.vector_db_retriever = vector_db_retriever\n",
    "\n",
    "    def run_pipeline(self, user_query: str) -> str:\n",
    "        context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
    "        \n",
    "        context_prompt = \"\"\n",
    "        for context in context_list:\n",
    "            context_prompt += context[0] + \"\\n\"\n",
    "\n",
    "        formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
    "\n",
    "        formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
    "        \n",
    "        return self.llm.run([formatted_system_prompt, formatted_user_prompt])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
    "    vector_db_retriever=vector_db,\n",
    "    llm=chat_openai\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'King Lear is the main character in William Shakespeare\\'s play, \"King Lear.\" He is the King of Britain and the father of three daughters: Goneril, Regan, and Cordelia. The play focuses on Lear\\'s descent into madness and the consequences of his decision to divide his kingdom between his two elder daughters, who betray and mistreat him.'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieval_augmented_qa_pipeline.run_pipeline(\"Who is King Lear?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I don't know.\""
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieval_augmented_qa_pipeline.run_pipeline(\"Who is Batman?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Cordelia is seen in the French camp with Kent, the Doctor, and a Gentleman. They discuss Cordelia's feelings towards Kent and her gratitude for his goodness. They mention that Cordelia's life will be too short to repay Kent's goodness. The scene does not provide any specific information about what happens to Cordelia after this moment.\""
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieval_augmented_qa_pipeline.run_pipeline(\"What happens to Cordelia?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conclusion\n",
    "\n",
    "In this notebook, we've gone through the steps required to create your own simple RAQA application!\n",
    "\n",
    "Please feel free to extend this as much as you'd like. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bonus Challenges\n",
    "\n",
    "Challenge 1: \n",
    "- Implement a new distance measure\n",
    "- Implement a more efficient vector search\n",
    "\n",
    "Challenge 2: \n",
    "- Create an external VectorStore that can be run/hosted elsewhere\n",
    "- Build an adapter for that VectorStore here"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "buildyourownlangchain",
   "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.11.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}