{
"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'\\n{doc.page_content}\\n'\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'\\n{doc.page_content}\\n'\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'\\n{doc.page_content[:1000]}\\n'\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'\\n{doc.page_content[:1000]}\\n'\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
}