File size: 41,806 Bytes
48c4cb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
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
973
974
975
976
977
978
979
980
981
982
983
984
985
{
 "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": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -q -U numpy matplotlib plotly pandas scipy scikit-learn openai python-dotenv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter\n",
    "from aimakerspace.vectordatabase import VectorDatabase\n",
    "import asyncio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "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": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 5,
     "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": 6,
   "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": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "189"
      ]
     },
     "execution_count": 7,
     "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": 8,
   "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": 8,
     "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": 9,
   "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": 10,
   "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": 11,
   "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.8344666931475854),\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.8218615790372595),\n",
       " (\" 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, from your first of difference and decay,\\nHave follow'd your sad steps.\\nKING LEAR\\nYou are welcome hither.\\nKENT\\nNor no man else: all's cheerless, dark, and deadly.\\nYour eldest daughters have fordone them selves,\\nAnd desperately are dead.\\nKING LEAR\\nAy, so I think.\\nALBANY\\nHe knows not what he says: and vain it is\\nThat we present us to him.\\nEDGAR\\nVery bootless.\\nEnter a Captain\\n\\nCaptain\\nEdmund is dead, my lord.\\nALBANY\\nThat's but a trifle here.\\nYou lords and noble friends, know our intent.\\nWhat comfort to this great decay may come\\nShall be applied: for us we will resign,\\nDuring the life of this old majesty,\\nTo him our absolute power:\\nTo EDGAR and KENT\\n\\nyou, to your rights:\\nWith boot, and such addition as your honours\\nHave more than merited. All friends shall taste\\nThe wages of their virtue, and \",\n",
       "  0.8210514859927185)]"
      ]
     },
     "execution_count": 11,
     "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": 14,
   "metadata": {},
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'prompts'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32m/home/rlpeter70/LLMO-Cohort-3/Week 1/Thursday - Retrieval Augmented Generation QA Application /Python RAQA Example.ipynb Cell 34\u001b[0m line \u001b[0;36m7\n\u001b[1;32m      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39maimakerspace\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mopenai_utils\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mprompts\u001b[39;00m \u001b[39mimport\u001b[39;00m (\n\u001b[1;32m      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=1'>2</a>\u001b[0m     UserRolePrompt,\n\u001b[1;32m      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=2'>3</a>\u001b[0m     SystemRolePrompt,\n\u001b[1;32m      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=3'>4</a>\u001b[0m     AssistantRolePrompt,\n\u001b[1;32m      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=4'>5</a>\u001b[0m )\n\u001b[0;32m----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=6'>7</a>\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39maimakerspace\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mopenai_utils\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mchatmodel\u001b[39;00m \u001b[39mimport\u001b[39;00m ChatOpenAI\n\u001b[1;32m      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a>\u001b[0m chat_openai \u001b[39m=\u001b[39m ChatOpenAI()\n\u001b[1;32m     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>\u001b[0m user_prompt_template \u001b[39m=\u001b[39m \u001b[39m\"\u001b[39m\u001b[39m{content}\u001b[39;00m\u001b[39m\"\u001b[39m\n",
      "File \u001b[0;32m~/LLMO-Cohort-3/Week 1/Thursday - Retrieval Augmented Generation QA Application /aimakerspace/openai_utils/chatmodel.py:3\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mopenai\u001b[39;00m \u001b[39mimport\u001b[39;00m OpenAI\n\u001b[1;32m      2\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mdotenv\u001b[39;00m \u001b[39mimport\u001b[39;00m load_dotenv\n\u001b[0;32m----> 3\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mprompts\u001b[39;00m \u001b[39mimport\u001b[39;00m UserRolePrompt, SystemRolePrompt\n\u001b[1;32m      4\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mos\u001b[39;00m\n\u001b[1;32m      6\u001b[0m load_dotenv()\n",
      "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'prompts'"
     ]
    }
   ],
   "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": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The best way to write a loop depends on the specific requirements and context of the problem you are trying to solve. However, here are some general principles that can help you write an effective loop:\n",
      "\n",
      "1. Identify the type of loop needed: There are different types of loops, such as `for` loops and `while` loops. Choose the one that suits your situation best.\n",
      "\n",
      "2. Set an appropriate loop condition: Make sure the loop condition is set correctly to ensure that the loop runs as intended. If using a `for` loop, ensure the iterable is suitable for the loop.\n",
      "\n",
      "3. Initialize variables outside the loop when necessary: If you need to use a variable within the loop, make sure to initialize it outside the loop, so it doesn't get reset with each iteration unless desired.\n",
      "\n",
      "4. Use meaningful variable names: Choose variable names that are descriptive and help others (including your future self) understand the purpose of the loop and its associated variables.\n",
      "\n",
      "5. Keep the loop body concise and focused: Ensure that the tasks performed within the loop are clear and concise. If your loop body becomes too long or complex, consider moving some functionality into separate functions or methods for better readability and maintainability.\n",
      "\n",
      "6. Avoid infinite loops: Make sure your loop has a proper termination condition to prevent it from running indefinitely. Otherwise, your program may hang or crash.\n",
      "\n",
      "7. Test and debug: After writing your loop, thoroughly test it with different inputs to ensure it behaves as expected. Use debugging tools if necessary to identify and fix any errors or logical issues.\n",
      "\n",
      "Remember, programming is a creative process, and there can be multiple valid approaches to writing a loop. Consider the specific requirements of your problem, and choose the approach that best suits your needs while maintaining readability and maintainability.\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": null,
   "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": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
    "    vector_db_retriever=vector_db,\n",
    "    llm=chat_openai\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'King Lear is a character in the play \"King Lear\" by William Shakespeare. He is the king of Britain and the protagonist of the play. In the context provided, King Lear is questioning his own identity and is struggling with the actions of his daughters.'"
      ]
     },
     "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": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -q -U wandb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "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": null,
   "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 = dict(openai_response.usage)\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": null,
   "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": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I don't know.\""
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieval_augmented_qa_pipeline.run_pipeline(\"Who is Batman?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Cordelia is dead. In the provided context, King Lear enters with Cordelia dead in his arms, expressing his grief and howling for her loss. King Lear realizes that she is gone forever and mourns her death. There is no further information about what specifically caused Cordelia's death.\""
      ]
     },
     "execution_count": 46,
     "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.11.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}