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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "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)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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)"
   ],
   "id": "fcf876fdfc43c154",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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)"
   ],
   "id": "9be49655bf7b1506",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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)"
   ],
   "id": "3a8f1a5fef11a6a0",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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()"
   ],
   "id": "b1b720c17d34d0dc",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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]"
   ],
   "id": "49b8420a90e4dd76",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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}\")"
   ],
   "id": "6280689c6bf3255e",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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)"
   ],
   "id": "d850bbc4a908a98b",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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)"
   ],
   "id": "85fce16b57c00eaa",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "import os\n",
    "from dotenv import load_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 = ChatGoogleGenerativeAI(model=\"gemini-2.0-flash\")\n",
    "# llm = ChatGroq(model=\"qwen-qwq-32b\", temperature=0)\n",
    "llm_with_tools = llm.bind_tools(tools)"
   ],
   "id": "2d049ca6773dd05e",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "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",
    "\n",
    "from IPython.display import Image, display\n",
    "\n",
    "display(Image(graph.get_graph(xray=True).draw_mermaid_png()))"
   ],
   "id": "f1d17cb6cac71a7a",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "cell_type": "code",
   "source": [
    "question = \"What are the EC numbers of the two most commonly used chemicals for the virus testing method in the paper about SPFMV and SPCSV in the Pearl Of Africa from 2016? Return the semicolon-separated numbers in the order of the alphabetized chemicals.\"\n",
    "messages = [HumanMessage(content=question)]\n",
    "messages = graph.invoke({\"messages\": messages})\n",
    "\n",
    "for m in messages['messages']:\n",
    "    m.pretty_print()"
   ],
   "id": "a1a5be38e7e98476",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}