File size: 44,744 Bytes
cc64171
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
5368c06
 
 
 
cc64171
 
5368c06
 
 
 
 
 
 
cc64171
 
5368c06
 
 
 
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
5368c06
 
 
 
 
cc64171
 
5368c06
 
 
 
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
5368c06
cc64171
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
 
 
 
 
 
 
 
 
 
5368c06
cc64171
 
5368c06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc64171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d0cc4adf",
   "metadata": {},
   "source": [
    "### Question data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "14e3f417",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load metadata.jsonl\n",
    "import json\n",
    "# Load the metadata.jsonl file\n",
    "with open('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": 34,
   "id": "5e2da6fc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================================\n",
      "Task ID: 20194330-9976-4043-8632-f8485c6c71b2\n",
      "Question: The YouTube channel Game Grumps began a Let’s Play of the game Sonic the Hedgehog (2006) in the year 2012. Thirty seconds into the first episode, a phrase is shown on the screen in white letters on a red background. How many times does the letter \"E\" appear in this phrase?\n",
      "Level: 2\n",
      "Final Answer: 4\n",
      "Annotator Metadata: \n",
      "  ├── Steps: \n",
      "  │      ├── 1. Look up \"Game grumps sonic 2006 playthrough\".\n",
      "  │      ├── 2. Click on the first result and verify that it matches the parameters from the question.\n",
      "  │      ├── 3. Scrub to the thirty-second mark in the video.\n",
      "  │      ├── 4. Note the letters in white on the red background.\n",
      "  │      ├── 5. Count the letter \"E\"'s in the phrase.\n",
      "  ├── Number of steps: 5\n",
      "  ├── How long did this take?: 5 minutes\n",
      "  ├── Tools:\n",
      "  │      ├── 1. Web browser\n",
      "  │      ├── 2. YouTube player\n",
      "  │      ├── 3. Color recognition\n",
      "  │      ├── 4. OCR\n",
      "  └── Number of tools: 4\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",
    "\n",
    "import random\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(f\"Annotator Metadata: \")\n",
    "    print(f\"  ├── 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(f\"  ├── How long did this take?: {sample['Annotator Metadata']['How long did this take?']}\")\n",
    "    print(f\"  ├── 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": "code",
   "execution_count": 35,
   "id": "4bb02420",
   "metadata": {},
   "outputs": [],
   "source": [
    "### build a vector database based on the metadata.jsonl\n",
    "# https://python.langchain.com/docs/integrations/vectorstores/supabase/\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain_community.vectorstores import SupabaseVectorStore\n",
    "from supabase.client import Client, create_client\n",
    "\n",
    "\n",
    "load_dotenv()\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") #  dim=768\n",
    "\n",
    "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)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "a070b955",
   "metadata": {},
   "outputs": [],
   "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 = f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\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",
    "# upload the documents to the vector database\n",
    "try:\n",
    "    response = (\n",
    "        supabase.table(\"documents\")\n",
    "        .insert(docs)\n",
    "        .execute()\n",
    "    )\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": "code",
   "execution_count": 37,
   "id": "77fb9dbb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# add items to vector database\n",
    "vector_store = SupabaseVectorStore(\n",
    "    client=supabase,\n",
    "    embedding= embeddings,\n",
    "    table_name=\"documents\",\n",
    "    query_name=\"match_documents_langchain\",\n",
    ")\n",
    "retriever = vector_store.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "12a05971",
   "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, 2)\n",
    "# docs = retriever.invoke(query)\n",
    "# docs[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "1eae5ba4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "List of tools used in all samples:\n",
      "Total number of tools used: 83\n",
      "  ├── web browser: 107\n",
      "  ├── image recognition tools (to identify and parse a figure with three axes): 1\n",
      "  ├── search engine: 101\n",
      "  ├── calculator: 34\n",
      "  ├── unlambda compiler (optional): 1\n",
      "  ├── a web browser.: 2\n",
      "  ├── a search engine.: 2\n",
      "  ├── a calculator.: 1\n",
      "  ├── microsoft excel: 5\n",
      "  ├── google search: 1\n",
      "  ├── ne: 9\n",
      "  ├── pdf access: 7\n",
      "  ├── file handling: 2\n",
      "  ├── python: 3\n",
      "  ├── image recognition tools: 12\n",
      "  ├── jsonld file access: 1\n",
      "  ├── video parsing: 1\n",
      "  ├── python compiler: 1\n",
      "  ├── video recognition tools: 3\n",
      "  ├── pdf viewer: 7\n",
      "  ├── microsoft excel / google sheets: 3\n",
      "  ├── word document access: 1\n",
      "  ├── tool to extract text from images: 1\n",
      "  ├── a word reversal tool / script: 1\n",
      "  ├── counter: 1\n",
      "  ├── excel: 3\n",
      "  ├── image recognition: 5\n",
      "  ├── color recognition: 3\n",
      "  ├── excel file access: 3\n",
      "  ├── xml file access: 1\n",
      "  ├── access to the internet archive, web.archive.org: 1\n",
      "  ├── text processing/diff tool: 1\n",
      "  ├── gif parsing tools: 1\n",
      "  ├── a web browser: 7\n",
      "  ├── a search engine: 7\n",
      "  ├── a speech-to-text tool: 2\n",
      "  ├── code/data analysis tools: 1\n",
      "  ├── audio capability: 2\n",
      "  ├── pdf reader: 1\n",
      "  ├── markdown: 1\n",
      "  ├── a calculator: 5\n",
      "  ├── access to wikipedia: 3\n",
      "  ├── image recognition/ocr: 3\n",
      "  ├── google translate access: 1\n",
      "  ├── ocr: 4\n",
      "  ├── bass note data: 1\n",
      "  ├── text editor: 1\n",
      "  ├── xlsx file access: 1\n",
      "  ├── powerpoint viewer: 1\n",
      "  ├── csv file access: 1\n",
      "  ├── calculator (or use excel): 1\n",
      "  ├── computer algebra system: 1\n",
      "  ├── video processing software: 1\n",
      "  ├── audio processing software: 1\n",
      "  ├── computer vision: 1\n",
      "  ├── google maps: 1\n",
      "  ├── access to excel files: 1\n",
      "  ├── calculator (or ability to count): 1\n",
      "  ├── a file interface: 3\n",
      "  ├── a python ide: 1\n",
      "  ├── spreadsheet editor: 1\n",
      "  ├── tools required: 1\n",
      "  ├── b browser: 1\n",
      "  ├── image recognition and processing tools: 1\n",
      "  ├── computer vision or ocr: 1\n",
      "  ├── c++ compiler: 1\n",
      "  ├── access to google maps: 1\n",
      "  ├── youtube player: 1\n",
      "  ├── natural language processor: 1\n",
      "  ├── graph interaction tools: 1\n",
      "  ├── bablyonian cuniform -> arabic legend: 1\n",
      "  ├── access to youtube: 1\n",
      "  ├── image search tools: 1\n",
      "  ├── calculator or counting function: 1\n",
      "  ├── a speech-to-text audio processing tool: 1\n",
      "  ├── access to academic journal websites: 1\n",
      "  ├── pdf reader/extracter: 1\n",
      "  ├── rubik's cube model: 1\n",
      "  ├── wikipedia: 1\n",
      "  ├── video capability: 1\n",
      "  ├── image processing tools: 1\n",
      "  ├── age recognition software: 1\n",
      "  ├── youtube: 1\n"
     ]
    }
   ],
   "source": [
    "# list of the tools used in all the samples\n",
    "from collections import Counter, OrderedDict\n",
    "\n",
    "tools = []\n",
    "for sample in json_QA:\n",
    "    for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
    "        tool = tool[2:].strip().lower()\n",
    "        if tool.startswith(\"(\"):\n",
    "            tool = tool[11:].strip()\n",
    "        tools.append(tool)\n",
    "tools_counter = OrderedDict(Counter(tools))\n",
    "print(\"List of tools used in all samples:\")\n",
    "print(\"Total number of tools used:\", len(tools_counter))\n",
    "for tool, count in tools_counter.items():\n",
    "    print(f\"  ├── {tool}: {count}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5efee12a",
   "metadata": {},
   "source": [
    "#### Graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "7fe573cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_prompt = \"\"\"\n",
    "You are a helpful assistant tasked with answering questions using a set of tools.\n",
    "If the tool is not available, you can try to find the information online. You can also use your own knowledge to answer the question. \n",
    "You need to provide a step-by-step explanation of how you arrived at the answer.\n",
    "==========================\n",
    "Here is a few examples showing you how to answer the question step by step.\n",
    "\"\"\"\n",
    "for i, samples in enumerate(random_samples):\n",
    "    system_prompt += f\"\\nQuestion {i+1}: {samples['Question']}\\nSteps:\\n{samples['Annotator Metadata']['Steps']}\\nTools:\\n{samples['Annotator Metadata']['Tools']}\\nFinal Answer: {samples['Final answer']}\\n\"\n",
    "system_prompt += \"\\n==========================\\n\"\n",
    "system_prompt += \"Now, please answer the following question step by step.\\n\"\n",
    "\n",
    "# save the system_prompt to a file\n",
    "with open('system_prompt.txt', 'w') as f:\n",
    "    f.write(system_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "d6beb0da",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "You are a helpful assistant tasked with answering questions using a set of tools.\n",
      "If the tool is not available, you can try to find the information online. You can also use your own knowledge to answer the question. \n",
      "You need to provide a step-by-step explanation of how you arrived at the answer.\n",
      "==========================\n",
      "Here is a few examples showing you how to answer the question step by step.\n",
      "\n",
      "Question 1: The YouTube channel Game Grumps began a Let’s Play of the game Sonic the Hedgehog (2006) in the year 2012. Thirty seconds into the first episode, a phrase is shown on the screen in white letters on a red background. How many times does the letter \"E\" appear in this phrase?\n",
      "Steps:\n",
      "1. Look up \"Game grumps sonic 2006 playthrough\".\n",
      "2. Click on the first result and verify that it matches the parameters from the question.\n",
      "3. Scrub to the thirty-second mark in the video.\n",
      "4. Note the letters in white on the red background.\n",
      "5. Count the letter \"E\"'s in the phrase.\n",
      "Tools:\n",
      "1. Web browser\n",
      "2. YouTube player\n",
      "3. Color recognition\n",
      "4. OCR\n",
      "Final Answer: 4\n",
      "\n",
      "==========================\n",
      "Now, please answer the following question step by step.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# load the system prompt from the file\n",
    "with open('system_prompt.txt', 'r') as f:\n",
    "    system_prompt = f.read()\n",
    "print(system_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "42fde0f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import dotenv\n",
    "from langgraph.graph import MessagesState, START, StateGraph\n",
    "from langgraph.prebuilt import tools_condition\n",
    "from langgraph.prebuilt import ToolNode\n",
    "from langchain_google_genai import ChatGoogleGenerativeAI\n",
    "from langchain_groq import ChatGroq\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_community.document_loaders import WikipediaLoader\n",
    "from langchain_community.document_loaders import ArxivLoader\n",
    "from langchain_community.vectorstores import SupabaseVectorStore\n",
    "from langchain.tools.retriever import create_retriever_tool\n",
    "from langchain_core.messages import HumanMessage, SystemMessage\n",
    "from langchain_core.tools import tool\n",
    "from supabase.client import Client, create_client\n",
    "\n",
    "# Define the retriever from supabase\n",
    "load_dotenv()\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") #  dim=768\n",
    "\n",
    "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",
    "vector_store = SupabaseVectorStore(\n",
    "    client=supabase,\n",
    "    embedding= embeddings,\n",
    "    table_name=\"documents\",\n",
    "    query_name=\"match_documents_langchain\",\n",
    ")\n",
    "\n",
    "question_retrieve_tool = create_retriever_tool(\n",
    "    vector_store.as_retriever(),\n",
    "    \"Question Retriever\",\n",
    "    \"Find similar questions in the vector database for the given question.\",\n",
    ")\n",
    "\n",
    "@tool\n",
    "def multiply(a: int, b: int) -> int:\n",
    "    \"\"\"Multiply two numbers.\n",
    "\n",
    "    Args:\n",
    "        a: first int\n",
    "        b: second int\n",
    "    \"\"\"\n",
    "    return a * b\n",
    "\n",
    "@tool\n",
    "def add(a: int, b: int) -> int:\n",
    "    \"\"\"Add two numbers.\n",
    "    \n",
    "    Args:\n",
    "        a: first int\n",
    "        b: second int\n",
    "    \"\"\"\n",
    "    return a + b\n",
    "\n",
    "@tool\n",
    "def subtract(a: int, b: int) -> int:\n",
    "    \"\"\"Subtract two numbers.\n",
    "    \n",
    "    Args:\n",
    "        a: first int\n",
    "        b: second int\n",
    "    \"\"\"\n",
    "    return a - b\n",
    "\n",
    "@tool\n",
    "def divide(a: int, b: int) -> int:\n",
    "    \"\"\"Divide two numbers.\n",
    "    \n",
    "    Args:\n",
    "        a: first int\n",
    "        b: second int\n",
    "    \"\"\"\n",
    "    if b == 0:\n",
    "        raise ValueError(\"Cannot divide by zero.\")\n",
    "    return a / b\n",
    "\n",
    "@tool\n",
    "def modulus(a: int, b: int) -> int:\n",
    "    \"\"\"Get the modulus of two numbers.\n",
    "    \n",
    "    Args:\n",
    "        a: first int\n",
    "        b: second int\n",
    "    \"\"\"\n",
    "    return a % b\n",
    "\n",
    "@tool\n",
    "def wiki_search(query: str) -> str:\n",
    "    \"\"\"Search Wikipedia for a query and return maximum 2 results.\n",
    "    \n",
    "    Args:\n",
    "        query: The search query.\"\"\"\n",
    "    search_docs = WikipediaLoader(query=query, load_max_docs=2).load()\n",
    "    formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
    "        [\n",
    "            f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content}\\n</Document>'\n",
    "            for doc in search_docs\n",
    "        ])\n",
    "    return {\"wiki_results\": formatted_search_docs}\n",
    "\n",
    "@tool\n",
    "def web_search(query: str) -> str:\n",
    "    \"\"\"Search Tavily for a query and return maximum 3 results.\n",
    "    \n",
    "    Args:\n",
    "        query: The search query.\"\"\"\n",
    "    search_docs = TavilySearchResults(max_results=3).invoke(query=query)\n",
    "    formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
    "        [\n",
    "            f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content}\\n</Document>'\n",
    "            for doc in search_docs\n",
    "        ])\n",
    "    return {\"web_results\": formatted_search_docs}\n",
    "\n",
    "@tool\n",
    "def arvix_search(query: str) -> str:\n",
    "    \"\"\"Search Arxiv for a query and return maximum 3 result.\n",
    "    \n",
    "    Args:\n",
    "        query: The search query.\"\"\"\n",
    "    search_docs = ArxivLoader(query=query, load_max_docs=3).load()\n",
    "    formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
    "        [\n",
    "            f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content[:1000]}\\n</Document>'\n",
    "            for doc in search_docs\n",
    "        ])\n",
    "    return {\"arvix_results\": formatted_search_docs}\n",
    "\n",
    "@tool\n",
    "def similar_question_search(question: str) -> str:\n",
    "    \"\"\"Search the vector database for similar questions and return the first results.\n",
    "    \n",
    "    Args:\n",
    "        question: the question human provided.\"\"\"\n",
    "    matched_docs = vector_store.similarity_search(query, 3)\n",
    "    formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
    "        [\n",
    "            f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content[:1000]}\\n</Document>'\n",
    "            for doc in matched_docs\n",
    "        ])\n",
    "    return {\"similar_questions\": formatted_search_docs}\n",
    "\n",
    "tools = [\n",
    "    multiply,\n",
    "    add,\n",
    "    subtract,\n",
    "    divide,\n",
    "    modulus,\n",
    "    wiki_search,\n",
    "    web_search,\n",
    "    arvix_search,\n",
    "    question_retrieve_tool\n",
    "]\n",
    "\n",
    "llm = ChatGroq(model=\"qwen-qwq-32b\", temperature=0)\n",
    "llm_with_tools = llm.bind_tools(tools)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "7dd0716c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the system prompt from the file\n",
    "with open('system_prompt.txt', 'r') as f:\n",
    "    system_prompt = f.read()\n",
    "\n",
    "\n",
    "# System message\n",
    "sys_msg = SystemMessage(content=system_prompt)\n",
    "\n",
    "# Node\n",
    "def assistant(state: MessagesState):\n",
    "    \"\"\"Assistant node\"\"\"\n",
    "    return {\"messages\": [llm_with_tools.invoke([sys_msg] + state[\"messages\"])]}\n",
    "\n",
    "# Build graph\n",
    "builder = StateGraph(MessagesState)\n",
    "builder.add_node(\"assistant\", assistant)\n",
    "builder.add_node(\"tools\", ToolNode(tools))\n",
    "builder.add_edge(START, \"assistant\")\n",
    "builder.add_conditional_edges(\n",
    "    \"assistant\",\n",
    "    # If the latest message (result) from assistant is a tool call -> tools_condition routes to tools\n",
    "    # If the latest message (result) from assistant is a not a tool call -> tools_condition routes to END\n",
    "    tools_condition,\n",
    ")\n",
    "builder.add_edge(\"tools\", \"assistant\")\n",
    "\n",
    "# Compile graph\n",
    "graph = builder.compile()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "f4e77216",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAANgAAAD5CAIAAADKsmwpAAAQAElEQVR4nOzdCVhU5f4H8Hd2ZmGAGfZNRQQEXAMtNTU1TdNccknNNP8u6a2kMm9mllqZde3q1UwzNXPfcNcyV1xRUVEBEQQldhi22Zh9/j+cG3FpICzO8J457+fhmWc458CwfOddz3kP12q1IoJoaVxEEBggQSSwQIJIYIEEkcACCSKBBRJEAgskiPUZdGZFvkGrMmtVJrPJajTQYHhLIGRz+SyRK1fkyvYJFiIaYpFxRBut2pR5Q52doikv0rt780WuHPi/SmVco54Gfx+eC7uiCN48Johjzj1tSLQkpKO4bUcJog8SRAR/gctHyooeVXsFuYREiwPbiRCdGXSW7BR17v3q/AfVPYbJw7q6IjpgehDvXVWe3lUC/7Cu/TyQc1FVGOENBsXkwEm+YinubTBGB/H8/lIOD/Uc5oWcV3mx/uCaggETfIIjsC7pmRvEs3tLZD78Tr3dEQMcWpf/9BC5T7ALwhVDg3hkfUFQuKhzH0ak0ObQ2vyIWGl4DKZNRjZinstHFP5thYxKIRg+K+DmmQpFgR5hiXFBzLylgsen+jtb16Qpxs8Lhmax1YJjHci4ICbEl3Z5jokptAnpILl4SIHww6wg3jpXEREjFUo4iKmgQZJ5S61RmhBmmBXER6maZ4bJELP1HuWZnFCJMMOgID5K03B5bA6Hif2zuoIjxCmXqhBmGPRfeXhX06aDGDnWBx98cOjQIfTknn/++fz8fEQBvgvbK1AAE4AIJwwKYnmJoa3Dg5iWloaeXGFhYUVFBaJMWBdJ3gMtwglTgmjQWRT5eqGEqinXS5cuzZw5s1evXiNGjPjkk08UipqeaUxMTEFBwaefftq3b1/4VK1Wr1u3bvLkybbDVqxYodPpbF/ev3//nTt3Tp8+Hb4kISFh2LBhsHH48OHv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text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "display(Image(graph.get_graph(xray=True).draw_mermaid_png()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "5987d58c",
   "metadata": {},
   "outputs": [],
   "source": [
    "question = \"\"\n",
    "messages = [HumanMessage(content=question)]\n",
    "messages = graph.invoke({\"messages\": messages})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "330cbf17",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "Tool Calls:\n",
      "  wiki_search (call_s48x)\n",
      " Call ID: call_s48x\n",
      "  Args:\n",
      "    query: capital of France\n",
      "=================================\u001b[1m Tool Message \u001b[0m=================================\n",
      "Name: wiki_search\n",
      "\n",
      "{\"wiki_results\": \"<Document source=\\\"https://en.wikipedia.org/wiki/List_of_capitals_of_France\\\" page=\\\"\\\"/>\\nThis is a chronological list of capitals of France. The capital of France has been Paris since its liberation in 1944.\\n\\n\\n== Chronology ==\\nTournai (before 486), current-day Belgium\\nSoissons (486–936)\\nLaon (936–987)\\nParis (987–1419), the residence of the Kings of France, although they were consecrated at Reims.\\nOrléans (1108), one of the few consecrations of a French monarch to occur outside of Reims occurred at Orléans, when Louis VI the Fat was consecrated in Orléans Cathedral by Daimbert, Archbishop of Sens; from 13 December 1560 to 31 January 1561, the French States-General also met in the city.\\nTroyes (1419–1422), for a short time during the Hundred Years' War, the city was the seat of the royal government.\\nBourges (1422–1444), Charles VII was forced to flee from Paris.\\nTours (1444–1527), Louis XI made the Château de Plessis-lez-Tours his residence.\\nParis (1528–1589), Francis I had established his court in Paris.\\nTours (1589–1594), faction of parliamentarians, faithful to King Henry IV sat at Tours.\\nParis (1594–1682)\\nVersailles (1682–1789), from 1682 to 1715, Louis XIV made Versailles his residence and the seat of the French court.\\nParis (1789–1871), on 5 and 6 October 1789, a throng from Paris invaded the castle and forced the royal family to move back to Paris. The National Constituent Assembly followed the King to Paris soon afterward; Versailles lost its role of capital city.\\nProvisional seats of the government:\\n\\nVersailles (1871), the French Third Republic established Versailles as its provisional seat of government in March 1871 after the Paris Commune took control of Paris.\\nBordeaux (September 1914), the government was relocated from Paris to Bordeaux very briefly during World War I, when it was feared that Paris would soon fall into German hands. These fears were alleviated after the German Army was pushed back at the First Battle of the Marne.\\nTours (10–13 June 1940), the city served as the temporary capital of France during World War II after the government fled Paris due to the German advance.\\nBordeaux (June 1940), the government was relocated from Paris to Tours then Bordeaux very briefly during World War II, when it became apparent that Paris would soon fall into German hands.\\nClermont-Ferrand (29 June 1940), the government was relocated from Bordeaux to Clermont-Ferrand, during a single day, before going to Vichy, which had a larger hotel capacity.\\nVichy (1940–1944), the Third Republic was abolished in Vichy and replaced it with the French State.\\nBrazzaville (1940–1943), with metropolitan France under Axis powers rule, Brazzaville was announced as the seat of the Free France government.\\nAlgiers (1943–1944), the city was made the seat of Free France, to be closer to the war in Europe.\\nParis (1945-present day).\\n\\n\\n== References ==\\n</Document>\\n\\n---\\n\\n<Document source=\\\"https://en.wikipedia.org/wiki/Capital_punishment_in_France\\\" page=\\\"\\\"/>\\nCapital punishment in France (French: peine de mort en France) is banned by Article 66-1 of the Constitution of the French Republic, voted as a constitutional amendment by the Congress of the French Parliament on 19 February 2007 and simply stating \\\"No one can be sentenced to the death penalty\\\" (French: Nul ne peut être condamné à la peine de mort). The death penalty was already declared illegal on 9 October 1981 when President François Mitterrand signed a law prohibiting the judicial system from using it and commuting the sentences of the seven people on death row to life imprisonment. The last execution took place by guillotine, being the main legal method since the French Revolution; Hamida Djandoubi, a Tunisian citizen convicted of torture and murder on French soil, was put to death in September 1977 in Marseille.\\nMajor French death penalty abolitionists across time have included philosopher Voltaire; poet Victor Hugo; politicians Léon Gambetta, Jean Jaurès and Aristide Briand; and writers Alphonse de Lamartine and Albert Camus.\\n\\n\\n== History ==\\n\\n\\n=== Ancien Régime ===\\n\\nPrior to 1791, under the Ancien Régime, there existed a variety of means of capital punishment in France, depending on the crime and the status of the condemned person:\\n\\nHanging was the most common punishment.\\nDecapitation by sword, for nobles only.\\nBurning for arson, bestiality, heresy, sodomy, and witchcraft. The convict was occasionally discreetly strangled.\\nBreaking wheel for brigandage and murder. The convict could be strangled before having his limbs broken or after, depending on the atrocity of his crime.\\nDeath by boiling for counterfeiting.\\nDismemberment for high treason, parricide, and regicide.\\nOn 6 July 1750, Jean Diot and Bruno Lenoir were strangled and burned at the stake in Place de Grève for sodomy, the last known execution for sodomy in France. Also in 1750, Jacques Ferron was either hanged or burned at the stake in Vanvres for bestiality, the last known execution for bestiality in France.\\n\\n\\n=== Adoption of the guillotine ===\\n\\nThe first campaign towards the abolition of the death penalty began on 30 May 1791, but on 6 October that year the National Assembly refused to pass a law abolishing the death penalty. However, they did abolish torture, and also declared that there would now be only one method of execution: 'Tout condamné à mort aura la tête tranchée' (All condemned to death will have their heads cut off).\\nIn 1789, physician Joseph-Ignace Guillotin proposed that all executions be carried out by a simple and painless mechanism, which led to the development and eventual adoption of the guillotine. Beheading had previously been reserved only for nobles and carried out manually by handheld axes or blades; commoners would usually be hanged or subjected to more brutal methods. Therefore, the adoption of the guillotine for all criminals regardless of social status not only made executions more efficient and less painful, but it also removed the class divisions in capital punishment altogether. As a result, many felt the device made the death penalty more humane and egalitarian.\\nThe guillotine was first used on Nicolas Jacques Pelletier on 25 April 1792. Guillotine usage then spread to other countries such as Germany (where it had been used since before the revolution), Italy, Sweden (used in a single execution), the Netherlands and French colonies in Africa, Canada, French Guiana and French Indochina. Although other governments employed the device, France has executed more people by guillotine than any other nation.\\n\\n\\n=== Penal Code of 1791 ===\\nOn October 6, 1791, the Penal Code of 1791 was enacted, which abolished capital punishment in the Kingdom of France for bestiality, blasphemy, heresy, pederasty, sacrilege, sodomy, and witchcraft.\\n\\n\\n=== 1939 onwards ===\\n\\nPublic executions were the norm and continued until 1939. From the mid-19th century, the usual time of day for executions changed from around 3 pm to morning and then to dawn. Execution\\n</Document>\"}\n",
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "The capital of France is Paris. According to the provided Wikipedia search results, Paris has been the capital since its liberation in 1944 and remains the capital to the present day. \n",
      "\n",
      "Final Answer: Paris\n"
     ]
    }
   ],
   "source": [
    "for m in messages['messages']:\n",
    "    m.pretty_print()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "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.13.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}