File size: 30,127 Bytes
6a2a4bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e5270bcc",
   "metadata": {},
   "source": [
    "# Final project of Agents course: An Agent that response the GAIA benchmark\n",
    "\n",
    "In this notebook, **we're going to read the GAIA questions from metadata and we'll store in a chroma database to use as retriever**.\n",
    "\n",
    "This notebook is part of the <a href=\"https://www.hf.co/learn/agents-course\">Hugging Face Agents Course</a>, a free course from beginner to expert, where you learn to build Agents.\n",
    "\n",
    "## What we'll do\n",
    "\n",
    "In this notebook, we'll do:\n",
    "\n",
    "1. Reading json metadata with GAIA questions\n",
    "2. Creating chroma vector store\n",
    "3. Querying the database and converting to a retriever to search using\n",
    "4. Loading the database from directory\n",
    "5. Creating supabase vector store\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "1e1d8e79",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "import json\n",
    "from dotenv import load_dotenv\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain_chroma import Chroma\n",
    "import random\n",
    "\n",
    "# from langchain.schema import Document\n",
    "from langchain_core.documents import Document\n",
    "from uuid import uuid4\n",
    "\n",
    "from langchain_community.vectorstores import SupabaseVectorStore\n",
    "from supabase.client import Client, create_client\n",
    "\n",
    "load_dotenv()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "bf2a78a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.chdir(os.path.abspath(\"..\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0513724",
   "metadata": {},
   "source": [
    "<div style=\"background-color:lightblue; color:black; font-weight:bold\">\n",
    "\n",
    "## 1. Reading json metadata\n",
    "\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c8f343d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the metadata.jsonl file\n",
    "with open(\"data/metadata.jsonl\", \"r\") as jsonl_file:\n",
    "    json_list = list(jsonl_file)\n",
    "\n",
    "json_QA = []\n",
    "for json_str in json_list:\n",
    "    json_data = json.loads(json_str)\n",
    "    json_QA.append(json_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e7191ac5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================================\n",
      "Task ID: 56137764-b4e0-45b8-9c52-1866420c3df5\n",
      "Question: Which contributor to the version of OpenCV where support was added for the Mask-RCNN model has the same name as a former Chinese head of government when the names are transliterated to the Latin alphabet?\n",
      "Level: 2\n",
      "Final Answer: Li Peng\n",
      "Annotator Metadata: \n",
      "  ├── Steps: \n",
      "  │      ├── 1. Use search engine to search for \"OpenCV change log\".\n",
      "  │      ├── 2. Open the top result from GitHub and search the page for \"Mask-RCNN\".\n",
      "  │      ├── 3. Observe that support for Mask-RCNN model was added in OpenCV version 4.0.0.\n",
      "  │      ├── 4. Expand the two lists of contributors for version 4.0.0.\n",
      "  │      ├── 5. Go to the Wikipedia page for head of government. \n",
      "  │      ├── 6. Scan through and note that for China, the head of government is the premier.\n",
      "  │      ├── 7. Go to the Wikipedia page for premier of the People's Republic of China.\n",
      "  │      ├── 8. Go to the linked page for List of premiers of the People's Republic of China.\n",
      "  │      ├── 9. Compare the list of OpenCV version 4.0.0 contributors' names and the list of premiers of China to find that Li Peng is present in both lists.\n",
      "  ├── Number of steps: 9\n",
      "  ├── How long did this take?: 5 minutes\n",
      "  ├── Tools:\n",
      "  │      ├── 1. Web browser\n",
      "  │      ├── 2. Search engine\n",
      "  └── Number of tools: 2\n",
      "==================================================\n"
     ]
    }
   ],
   "source": [
    "# randomly select 3 samples\n",
    "# {\"task_id\": \"c61d22de-5f6c-4958-a7f6-5e9707bd3466\", \"Question\": \"A paper about AI regulation that was originally submitted to arXiv.org in June 2022 shows a figure with three axes, where each axis has a label word at both ends. Which of these words is used to describe a type of society in a Physics and Society article submitted to arXiv.org on August 11, 2016?\", \"Level\": 2, \"Final answer\": \"egalitarian\", \"file_name\": \"\", \"Annotator Metadata\": {\"Steps\": \"1. Go to arxiv.org and navigate to the Advanced Search page.\\n2. Enter \\\"AI regulation\\\" in the search box and select \\\"All fields\\\" from the dropdown.\\n3. Enter 2022-06-01 and 2022-07-01 into the date inputs, select \\\"Submission date (original)\\\", and submit the search.\\n4. Go through the search results to find the article that has a figure with three axes and labels on each end of the axes, titled \\\"Fairness in Agreement With European Values: An Interdisciplinary Perspective on AI Regulation\\\".\\n5. Note the six words used as labels: deontological, egalitarian, localized, standardized, utilitarian, and consequential.\\n6. Go back to arxiv.org\\n7. Find \\\"Physics and Society\\\" and go to the page for the \\\"Physics and Society\\\" category.\\n8. Note that the tag for this category is \\\"physics.soc-ph\\\".\\n9. Go to the Advanced Search page.\\n10. Enter \\\"physics.soc-ph\\\" in the search box and select \\\"All fields\\\" from the dropdown.\\n11. Enter 2016-08-11 and 2016-08-12 into the date inputs, select \\\"Submission date (original)\\\", and submit the search.\\n12. Search for instances of the six words in the results to find the paper titled \\\"Phase transition from egalitarian to hierarchical societies driven by competition between cognitive and social constraints\\\", indicating that \\\"egalitarian\\\" is the correct answer.\", \"Number of steps\": \"12\", \"How long did this take?\": \"8 minutes\", \"Tools\": \"1. Web browser\\n2. Image recognition tools (to identify and parse a figure with three axes)\", \"Number of tools\": \"2\"}}\n",
    "# random.seed(42)\n",
    "random_samples = random.sample(json_QA, 1)\n",
    "for sample in random_samples:\n",
    "    print(\"=\" * 50)\n",
    "    print(f\"Task ID: {sample['task_id']}\")\n",
    "    print(f\"Question: {sample['Question']}\")\n",
    "    print(f\"Level: {sample['Level']}\")\n",
    "    print(f\"Final Answer: {sample['Final answer']}\")\n",
    "    print(\"Annotator Metadata: \")\n",
    "    print(\"  ├── Steps: \")\n",
    "    for step in sample[\"Annotator Metadata\"][\"Steps\"].split(\"\\n\"):\n",
    "        print(f\"  │      ├── {step}\")\n",
    "    print(f\"  ├── Number of steps: {sample['Annotator Metadata']['Number of steps']}\")\n",
    "    print(\n",
    "        f\"  ├── How long did this take?: {sample['Annotator Metadata']['How long did this take?']}\"\n",
    "    )\n",
    "    print(\"  ├── Tools:\")\n",
    "    for tool in sample[\"Annotator Metadata\"][\"Tools\"].split(\"\\n\"):\n",
    "        print(f\"  │      ├── {tool}\")\n",
    "    print(f\"  └── Number of tools: {sample['Annotator Metadata']['Number of tools']}\")\n",
    "print(\"=\" * 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81c30287",
   "metadata": {},
   "source": [
    "<div style=\"background-color:lightblue; color:black; font-weight:bold\">\n",
    "\n",
    "## 2. Creating chroma vector store\n",
    "\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "046462f4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "87ec1aea91cf4cf799c882f649ef7e8c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "modules.json:   0%|          | 0.00/349 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\ee5011\\Anaconda3\\envs\\llm-huggingface-agents-course-env\\Lib\\site-packages\\huggingface_hub\\file_download.py:143: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\\Users\\ee5011\\.cache\\huggingface\\hub\\models--sentence-transformers--all-mpnet-base-v2. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.\n",
      "To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development\n",
      "  warnings.warn(message)\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e0df64b800c14d0eaca2214438eaf4e0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "config_sentence_transformers.json:   0%|          | 0.00/116 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fe6e89ddbb5540b4869935bda0ededc0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "README.md:   0%|          | 0.00/10.4k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6ac82a744f0b4d33a64b21346af272d2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "sentence_bert_config.json:   0%|          | 0.00/53.0 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "877342a7a662471cb133598c298f6304",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "config.json:   0%|          | 0.00/571 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Xet Storage is enabled for this repo, but the 'hf_xet' package is not installed. Falling back to regular HTTP download. For better performance, install the package with: `pip install huggingface_hub[hf_xet]` or `pip install hf_xet`\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "29fdd3411b504b2ca875d7e0007db775",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "model.safetensors:   0%|          | 0.00/438M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "102778342b534cddb8b84d3698371c89",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer_config.json:   0%|          | 0.00/363 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "209ab2f278b949e5846abd5b60e42130",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "vocab.txt:   0%|          | 0.00/232k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "aced6d0bf212458a89c05dde7a22411b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer.json:   0%|          | 0.00/466k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "105ea3c52b7444f281aa22bddf40d582",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "special_tokens_map.json:   0%|          | 0.00/239 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "abbfcff9883645de86ea66f61931d31a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "config.json:   0%|          | 0.00/190 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Necessary packages:\n",
    "#   - langchain-chroma>=0.1.2\n",
    "#   - langchain-huggingface\n",
    "# Source:\n",
    "#   http://python.langchain.com/docs/integrations/vectorstores/chroma/\n",
    "\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\")\n",
    "vector_store = Chroma(\n",
    "    collection_name=\"gaia_dataset\",\n",
    "    embedding_function=embeddings,\n",
    "    persist_directory=\"./data/chroma_langchain_db\",  # Where to save data locally, remove if not necessary\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69e1f1b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# wrap the metadata.jsonl's questions and answers into a list of document\n",
    "docs = []\n",
    "for i, sample in enumerate(json_QA):\n",
    "    content = (\n",
    "        f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\n",
    "    )\n",
    "    doc = Document(\n",
    "        page_content=content,\n",
    "        metadata={\"source\": sample[\"task_id\"]},\n",
    "        id=i,\n",
    "    )\n",
    "    docs.append(doc)\n",
    "\n",
    "# upload the documents to the vector database\n",
    "try:\n",
    "    uuids = [str(uuid4()) for _ in range(len(docs))]\n",
    "    vector_store.add_documents(documents=docs, ids=uuids)\n",
    "except Exception as exception:\n",
    "    print(\"Error inserting data into Supabase:\", exception)\n",
    "\n",
    "# ALTERNATIVE : Save the documents (a list of dict) into a csv file, and manually upload it to Supabase\n",
    "# import pandas as pd\n",
    "# df = pd.DataFrame(docs)\n",
    "# df.to_csv('supabase_docs.csv', index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1701d7c",
   "metadata": {},
   "source": [
    "<div style=\"background-color:lightblue; color:black; font-weight:bold\">\n",
    "\n",
    "## 3. Querying the database and converting to a retriever to search using\n",
    "\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a7763a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Question : How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\n",
      "\n",
      "Final answer : 3 [{'source': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be'}]\n",
      "* Question : It is 1999. Before you party like it is 1999, please assist me in settling a bet.\n",
      "\n",
      "Fiona Apple and Paula Cole released albums prior to 1999. Of these albums, which didn't receive a letter grade from Robert Christgau? Provide your answer as a comma delimited list of album titles, sorted alphabetically.\n",
      "\n",
      "Final answer : Harbinger, Tidal [{'source': 'f46b4380-207e-4434-820b-f32ce04ae2a4'}]\n"
     ]
    }
   ],
   "source": [
    "# Querying directly from the vector database\n",
    "query = \"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\"\n",
    "\n",
    "results = vector_store.similarity_search(\n",
    "    query=query,\n",
    "    k=2,\n",
    ")\n",
    "for res in results:\n",
    "    print(f\"* {res.page_content} [{res.metadata}]\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05895e6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Querying using a retriever\n",
    "# Conver to a retriever\n",
    "retriever = vector_store.as_retriever(\n",
    "    search_type=\"mmr\", search_kwargs={\"k\": 1, \"fetch_k\": 5}\n",
    ")\n",
    "results = retriever.invoke(input=query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "31649cce",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Document(id='454c552a-b27f-4eba-ac9a-d37300e515cd', metadata={'source': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be'}, page_content='Question : How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\\n\\nFinal answer : 3')]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ccfa3c25",
   "metadata": {},
   "source": [
    "<div style=\"background-color:lightblue; color:black; font-weight:bold\">\n",
    "\n",
    "## 4. Loading the database from directory\n",
    "\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4715fbd1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set the proxy for the HuggingFaceEmbeddings and SUpabase client\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f734773",
   "metadata": {},
   "outputs": [],
   "source": [
    "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\")\n",
    "vector_store_loaded = Chroma(\n",
    "    collection_name=\"gaia_dataset\",\n",
    "    embedding_function=embeddings,\n",
    "    persist_directory=\"./data/chroma_langchain_db\",  # Where to save data locally, remove if not necessary\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0fefcdf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Question : How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\n",
      "\n",
      "Final answer : 3 [{'source': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be'}]\n",
      "* Question : It is 1999. Before you party like it is 1999, please assist me in settling a bet.\n",
      "\n",
      "Fiona Apple and Paula Cole released albums prior to 1999. Of these albums, which didn't receive a letter grade from Robert Christgau? Provide your answer as a comma delimited list of album titles, sorted alphabetically.\n",
      "\n",
      "Final answer : Harbinger, Tidal [{'source': 'f46b4380-207e-4434-820b-f32ce04ae2a4'}]\n"
     ]
    }
   ],
   "source": [
    "query = \"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\"\n",
    "\n",
    "results = vector_store_loaded.similarity_search(\n",
    "    query=query,\n",
    "    k=2,\n",
    ")\n",
    "for res in results:\n",
    "    print(f\"* {res.page_content} [{res.metadata}]\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9a42742c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(id='454c552a-b27f-4eba-ac9a-d37300e515cd', metadata={'source': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be'}, page_content='Question : How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\\n\\nFinal answer : 3')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2749a453",
   "metadata": {},
   "source": [
    "<div style=\"background-color:lightblue; color:black; font-weight:bold\">\n",
    "\n",
    "## 5. Creating supabase vector store\n",
    "\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9138e761",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set the proxy for the HuggingFaceEmbeddings and SUpabase client\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb4e2b68",
   "metadata": {},
   "outputs": [],
   "source": [
    "supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
    "supabase_key = os.environ.get(\"SUPABASE_SERVICE_KEY\")\n",
    "supabase: Client = create_client(supabase_url, supabase_key)\n",
    "\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c49c6926",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "768\n"
     ]
    }
   ],
   "source": [
    "# Review the length of the vector dimensions\n",
    "vector = embeddings.embed_query(\"test\")\n",
    "print(len(vector))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74f48c63",
   "metadata": {},
   "source": [
    "<div style=\"color:red;font-weight:bold\">\n",
    "IMPORTANT: you need to create before run any code with supabase the table:\n",
    "</div>\n",
    "\n",
    "```sql\n",
    "-- enable the vector extension once if not already enabled\n",
    "create extension if not exists vector;\n",
    "\n",
    "-- create your vectorstore table\n",
    "create table gaia_dataset (\n",
    "  id uuid primary key default uuid_generate_v4(),\n",
    "  content text,\n",
    "  embedding vector(768),\n",
    "  metadata jsonb\n",
    ");\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb3608d4",
   "metadata": {},
   "source": [
    "- Option 1) with sql statements\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "02fc6c68",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of documents to insert: 165\n"
     ]
    }
   ],
   "source": [
    "# wrap the metadata.jsonl's questions and answers into a list of document\n",
    "# from langchain.schema import Document\n",
    "docs = []\n",
    "for sample in json_QA:\n",
    "    content = (\n",
    "        f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\n",
    "    )\n",
    "    doc = {\n",
    "        \"content\": content,\n",
    "        \"metadata\": {  # meatadata的格式必须时source键,否则会报错\n",
    "            \"source\": sample[\"task_id\"]\n",
    "        },\n",
    "        \"embedding\": embeddings.embed_query(content),\n",
    "    }\n",
    "    docs.append(doc)\n",
    "\n",
    "print(f\"Number of documents to insert: {len(docs)}\")\n",
    "# upload the documents to the vector database\n",
    "try:\n",
    "    response = supabase.table(\"gaia_dataset\").insert(docs).execute()\n",
    "except Exception as exception:\n",
    "    print(\"Error inserting data into Supabase:\", exception)\n",
    "\n",
    "# ALTERNATIVE : Save the documents (a list of dict) into a csv file, and manually upload it to Supabase\n",
    "# import pandas as pd\n",
    "# df = pd.DataFrame(docs)\n",
    "# df.to_csv('supabase_docs.csv', index=False)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ff670b5",
   "metadata": {},
   "source": [
    "- Option 2) with class of langchain\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c20877a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# wrap the metadata.jsonl's questions and answers into a list of document\n",
    "docs = []\n",
    "for i, sample in enumerate(json_QA):\n",
    "    content = (\n",
    "        f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\n",
    "    )\n",
    "    doc = Document(\n",
    "        page_content=content,\n",
    "        metadata={\"source\": sample[\"task_id\"]},\n",
    "        id=i,\n",
    "    )\n",
    "    docs.append(doc)\n",
    "\n",
    "# Initialize the vector store with Supabase\n",
    "vectorstore = SupabaseVectorStore(\n",
    "    client=supabase, embedding=embeddings, table_name=\"gaia_dataset\"\n",
    ")\n",
    "\n",
    "# upload the documents to the vector database\n",
    "try:\n",
    "    vector_store = SupabaseVectorStore.from_documents(\n",
    "        docs,\n",
    "        embeddings,\n",
    "        client=supabase,\n",
    "        table_name=\"gaia_dataset\",\n",
    "        query_name=\"match_documents\",\n",
    "        # chunk_size=500,\n",
    "    )\n",
    "except Exception as exception:\n",
    "    print(\"Error inserting data into Supabase:\", exception)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32ea05c4",
   "metadata": {},
   "source": [
    "Let's connect to the table and do some retrieval\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9aaf97c0",
   "metadata": {},
   "source": [
    "<div style=\"color:red;font-weight:bold\">\n",
    "IMPORTANT: you also need to create the match_documents function with SQL:\n",
    "</div>\n",
    "\n",
    "```sql\n",
    "create or replace function match_documents(query_embedding vector(768), match_count int default 5)\n",
    "returns table (\n",
    "  id uuid,\n",
    "  content text,\n",
    "  embedding vector(768),\n",
    "  metadata jsonb,\n",
    "  similarity float\n",
    ")\n",
    "language sql\n",
    "as $$\n",
    "  select\n",
    "    id,\n",
    "    content,\n",
    "    embedding,\n",
    "    metadata,\n",
    "    1 - (embedding <=> query_embedding) as similarity\n",
    "  from gaia_dataset\n",
    "  order by embedding <=> query_embedding\n",
    "  limit match_count;\n",
    "$$;\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da2db9cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_store = SupabaseVectorStore(\n",
    "    embedding=embeddings,\n",
    "    client=supabase,\n",
    "    table_name=\"gaia_dataset\",\n",
    "    query_name=\"match_documents\",\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eec1f65f",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?\"\n",
    "matched_docs = vector_store.similarity_search(query)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "1e09d302",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Document(metadata={'source': '840bfca7-4f7b-481a-8794-c560c340185d'}, page_content='Question : On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?\\n\\nFinal answer : 80GSFC21M0002'),\n",
       " Document(metadata={'source': 'a7feb290-76bb-4cb7-8800-7edaf7954f2f'}, page_content='Question : How many High Energy Physics - Lattice articles listed in January 2020 on Arxiv had ps versions available?\\n\\nFinal answer : 31'),\n",
       " Document(metadata={'source': '0e9e85b8-52b9-4de4-b402-5f635ab9631f'}, page_content=\"Question : What is the latest chronological year date written in the image on the webpage found when following the first citation reference link on the latest version of Carl Nebel's Wikipedia page as of August 2023?\\n\\nFinal answer : 1927\"),\n",
       " Document(metadata={'source': 'bec74516-02fc-48dc-b202-55e78d0e17cf'}, page_content='Question : What is the average number of pre-2020 works on the open researcher and contributor identification pages of the people whose identification is in this file?\\n\\nFinal answer : 26.4')]"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matched_docs"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llm-huggingface-agents-course-env",
   "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.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}