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
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
{
 "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",
    "> NOTE: 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": [
    "!pip install -q -U numpy matplotlib plotly pandas scipy scikit-learn openai python-dotenv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter\n",
    "from aimakerspace.vectordatabase import VectorDatabase\n",
    "import asyncio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "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": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 4,
     "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": 5,
   "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": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "189"
      ]
     },
     "execution_count": 6,
     "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": 7,
   "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": 7,
     "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": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import openai\n",
    "from getpass import getpass\n",
    "\n",
    "openai.api_key = getpass(\"OpenAI API Key: \")\n",
    "os.environ[\"OPENAI_API_KEY\"] = openai.api_key"
   ]
  },
  {
   "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": 9,
   "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": 10,
   "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.8210900574380693),\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.8195972501864015),\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.8179890218803361)]"
      ]
     },
     "execution_count": 10,
     "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": "markdown",
   "metadata": {},
   "source": [
    "#### Utility Functions\n",
    "\n",
    "You'll notice that we're using some utility functions from the `aimakerspace` module - let's take a peek at these and see what they're doing!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### XYZRolePrompt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we have our `system`, `user`, and `assistant` role prompts. \n",
    "\n",
    "Let's take a peek at what they look like:\n",
    "\n",
    "```python\n",
    "class BasePrompt:\n",
    "    def __init__(self, prompt):\n",
    "        \"\"\"\n",
    "        Initializes the BasePrompt object with a prompt template.\n",
    "\n",
    "        :param prompt: A string that can contain placeholders within curly braces\n",
    "        \"\"\"\n",
    "        self.prompt = prompt\n",
    "        self._pattern = re.compile(r\"\\{([^}]+)\\}\")\n",
    "\n",
    "    def format_prompt(self, **kwargs):\n",
    "        \"\"\"\n",
    "        Formats the prompt string using the keyword arguments provided.\n",
    "\n",
    "        :param kwargs: The values to substitute into the prompt string\n",
    "        :return: The formatted prompt string\n",
    "        \"\"\"\n",
    "        matches = self._pattern.findall(self.prompt)\n",
    "        return self.prompt.format(**{match: kwargs.get(match, \"\") for match in matches})\n",
    "\n",
    "    def get_input_variables(self):\n",
    "        \"\"\"\n",
    "        Gets the list of input variable names from the prompt string.\n",
    "\n",
    "        :return: List of input variable names\n",
    "        \"\"\"\n",
    "        return self._pattern.findall(self.prompt)\n",
    "```\n",
    "\n",
    "Then we have our `RolePrompt` which laser focuses us on the role pattern found in most API endpoints for LLMs.\n",
    "\n",
    "```python\n",
    "class RolePrompt(BasePrompt):\n",
    "    def __init__(self, prompt, role: str):\n",
    "        \"\"\"\n",
    "        Initializes the RolePrompt object with a prompt template and a role.\n",
    "\n",
    "        :param prompt: A string that can contain placeholders within curly braces\n",
    "        :param role: The role for the message ('system', 'user', or 'assistant')\n",
    "        \"\"\"\n",
    "        super().__init__(prompt)\n",
    "        self.role = role\n",
    "\n",
    "    def create_message(self, **kwargs):\n",
    "        \"\"\"\n",
    "        Creates a message dictionary with a role and a formatted message.\n",
    "\n",
    "        :param kwargs: The values to substitute into the prompt string\n",
    "        :return: Dictionary containing the role and the formatted message\n",
    "        \"\"\"\n",
    "        return {\"role\": self.role, \"content\": self.format_prompt(**kwargs)}\n",
    "```\n",
    "\n",
    "We'll look at how the `SystemRolePrompt` is constructed to get a better idea of how that extension works:\n",
    "\n",
    "```python\n",
    "class SystemRolePrompt(RolePrompt):\n",
    "    def __init__(self, prompt: str):\n",
    "        super().__init__(prompt, \"system\")\n",
    "```\n",
    "\n",
    "That pattern is repeated for our `UserRolePrompt` and our `AssistantRolePrompt` as well."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### ChatOpenAI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we have our model, which is converted to a format analagous to libraries like LangChain and LlamaIndex.\n",
    "\n",
    "Let's take a peek at how that is constructed:\n",
    "\n",
    "```python\n",
    "class ChatOpenAI:\n",
    "    def __init__(self, model_name: str = \"gpt-3.5-turbo\"):\n",
    "        self.model_name = model_name\n",
    "        self.openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n",
    "        if self.openai_api_key is None:\n",
    "            raise ValueError(\"OPENAI_API_KEY is not set\")\n",
    "\n",
    "    def run(self, messages, text_only: bool = True):\n",
    "        if not isinstance(messages, list):\n",
    "            raise ValueError(\"messages must be a list\")\n",
    "\n",
    "        openai.api_key = self.openai_api_key\n",
    "        response = openai.ChatCompletion.create(\n",
    "            model=self.model_name, messages=messages\n",
    "        )\n",
    "\n",
    "        if text_only:\n",
    "            return response.choices[0].message.content\n",
    "\n",
    "        return response\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Creating and Prompting OpenAI's `gpt-3.5-turbo`!\n",
    "\n",
    "Let's tie all these together and use it to prompt `gpt-3.5-turbo`!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "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": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "There is no one \"best\" way to write a loop, as it depends on the specific requirements and context of your program. However, I can provide some general tips to help you write efficient and effective loops:\n",
      "\n",
      "1. Choose the appropriate loop construct: In most cases, the `for` and `while` loops are the commonly used constructs. The choice depends on whether you know the number of iterations in advance (`for` loop) or if the loop needs to continue until a certain condition is met (`while` loop).\n",
      "\n",
      "2. Define the loop condition carefully: When using a `while` loop, ensure that the condition specifies when the loop should terminate. Make sure to increment or decrement any necessary variables within the loop to avoid infinite loops.\n",
      "\n",
      "3. Keep the loop body concise: To improve readability, only include essential code within the loop body. If possible, move complex calculations or repetitive operations outside the loop.\n",
      "\n",
      "4. Use loop control statements wisely: Utilize loop control statements like `break` and `continue` when necessary. `break` allows you to exit the loop prematurely, while `continue` lets you skip the remaining code within a particular iteration.\n",
      "\n",
      "5. Consider using built-in functions: Python provides several built-in functions like `range()` and `enumerate()` that can simplify loop iterations. They offer convenient ways to generate sequences or access indices and values simultaneously.\n",
      "\n",
      "6. Optimize performance when needed: If efficiency is crucial, consider using techniques such as list comprehension or generator expressions. These approaches can often provide faster execution compared to traditional loops.\n",
      "\n",
      "7. Ensure code clarity and maintainability: Write your loops in a way that is easy to understand and maintain. Use meaningful variable names and add comments when necessary to clarify the purpose and logic of the loop.\n",
      "\n",
      "Remember, the best way to write a loop depends on the specific requirements of your program, so choose an approach that suits your needs and improves the overall readability and efficiency of your code.\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": 13,
   "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": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
    "    vector_db_retriever=vector_db,\n",
    "    llm=chat_openai\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'King Lear is a character in the play \"King Lear\" by William Shakespeare. He is a king who, in his old age, decides to divide his kingdom among his three daughters based on how much they profess to love him. However, he soon realizes that his decision was a mistake, and he descends into madness as his family turns against him.'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieval_augmented_qa_pipeline.run_pipeline(\"Who is King Lear?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visibility Tooling\n",
    "\n",
    "This is great, but what if we wanted to add some visibility to our pipeline?\n",
    "\n",
    "Let's use Weights and Biases as a visibility tool!\n",
    "\n",
    "The first thing we'll need to do is create a Weights and Biases account and get an API key. \n",
    "\n",
    "You can follow the process outlined [here](https://docs.wandb.ai/quickstart) to do exactly that!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can get the Weights and Biases dependency and add our key to our env. to begin!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -q -U wandb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "wandb_key = getpass(\"Weights and Biases API Key: \")\n",
    "os.environ[\"WANDB_API_KEY\"] = wandb_key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import wandb\n",
    "\n",
    "os.environ[\"WANDB_NOTEBOOK_NAME\"] = \"Python RAQA Example.ipynb\"\n",
    "wandb.init(project=\"Visibility Example\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can integrate Weights and Biases into our `RetrievalAugmentedQAPipeline`.\n",
    "\n",
    "```python\n",
    "if self.wandb_project:\n",
    "            root_span = Trace(\n",
    "                name=\"root_span\",\n",
    "                kind=\"llm\",\n",
    "                status_code=status,\n",
    "                status_message=status_message,\n",
    "                start_time_ms=start_time,\n",
    "                end_time_ms=end_time,\n",
    "                metadata={\n",
    "                    \"token_usage\" : token_usage\n",
    "                },\n",
    "                inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
    "                outputs= {\"response\" : response_text}\n",
    "            )\n",
    "\n",
    "            root_span.log(name=\"openai_trace\")\n",
    "```\n",
    "\n",
    "The main things to consider here are how to populate the various fields to make sure we're tracking useful information. \n",
    "\n",
    "We'll use the `text_only` flag to ensure we can get detailed information about our LLM call!\n",
    "\n",
    "You can check out all the parameters for Weights and Biases `Trace` [here](https://github.com/wandb/wandb/blob/653015a014281f45770aaf43627f64d9c4f04a32/wandb/sdk/data_types/trace_tree.py#L166)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "from wandb.sdk.data_types.trace_tree import Trace\n",
    "\n",
    "class RetrievalAugmentedQAPipeline:\n",
    "    def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase, wandb_project = None) -> None:\n",
    "        self.llm = llm\n",
    "        self.vector_db_retriever = vector_db_retriever\n",
    "        self.wandb_project = wandb_project\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",
    "        \n",
    "        start_time = datetime.datetime.now().timestamp() * 1000\n",
    "\n",
    "        try:\n",
    "            openai_response = self.llm.run([formatted_system_prompt, formatted_user_prompt], text_only=False)\n",
    "            end_time = datetime.datetime.now().timestamp() * 1000\n",
    "            status = \"success\"\n",
    "            status_message = (None, )\n",
    "            response_text = openai_response.choices[0].message.content\n",
    "            token_usage = openai_response[\"usage\"].to_dict()\n",
    "            model = openai_response[\"model\"]\n",
    "\n",
    "        except Exception as e:\n",
    "            end_time = datetime.datetime.now().timestamp() * 1000\n",
    "            status = \"error\"\n",
    "            status_message = str(e)\n",
    "            response_text = \"\"\n",
    "            token_usage = {}\n",
    "            model = \"\"\n",
    "\n",
    "        if self.wandb_project:\n",
    "            root_span = Trace(\n",
    "                name=\"root_span\",\n",
    "                kind=\"llm\",\n",
    "                status_code=status,\n",
    "                status_message=status_message,\n",
    "                start_time_ms=start_time,\n",
    "                end_time_ms=end_time,\n",
    "                metadata={\n",
    "                    \"token_usage\" : token_usage,\n",
    "                    \"model_name\" : model\n",
    "                },\n",
    "                inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
    "                outputs= {\"response\" : response_text}\n",
    "            )\n",
    "\n",
    "            root_span.log(name=\"openai_trace\")\n",
    "        \n",
    "        return response_text if response_text else \"We ran into an error. Please try again later. Full Error Message: \" + status_message"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
    "    vector_db_retriever=vector_db,\n",
    "    llm=chat_openai,\n",
    "    wandb_project=\"LLM Visibility Example\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I don't know.\""
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieval_augmented_qa_pipeline.run_pipeline(\"Who is Batman?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Cordelia dies in King Lear's arms.\""
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieval_augmented_qa_pipeline.run_pipeline(\"What happens to Cordelia?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Navigate to the Weights and Biases \"run\" link to see how your LLM is performing!\n",
    "\n",
    "```\n",
    "View run at YOUR LINK HERE\n",
    "```"
   ]
  },
  {
   "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.9.18"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}