File size: 19,512 Bytes
0ec5d82 |
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 |
{
"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"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1e1d8e79",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 9,
"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",
"load_dotenv()\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"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": 3,
"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)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e7191ac5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================================\n",
"Task ID: 0bdb7c40-671d-4ad1-9ce3-986b159c0ddc\n",
"Question: In NASA's Astronomy Picture of the Day on 2006 January 21, two astronauts are visible, with one appearing much smaller than the other. As of August 2023, out of the astronauts in the NASA Astronaut Group that the smaller astronaut was a member of, which one spent the least time in space, and how many minutes did he spend in space, rounded to the nearest minute? Exclude any astronauts who did not spend any time in space. Give the last name of the astronaut, separated from the number of minutes by a semicolon.\n",
"Level: 3\n",
"Final Answer: White; 5876\n",
"Annotator Metadata: \n",
" βββ Steps: \n",
" β βββ 1. Use search engine to search for \"NASA's Astronomy Picture of the Day 2006 January 21\".\n",
" β βββ 2. Open the link to the image.\n",
" β βββ 3. Read the explanation to find that the image is of astronaut Charles \"Pete\" Conrad reflected in the helmet of astronaut Alan Bean.\n",
" β βββ 4. Observe that the smaller astronaut in the image is the one reflected in the other's helmet, so the smaller astronaut must be Charles \"Pete\" Conrad.\n",
" β βββ 5. Go to the Wikipedia page for Charles \"Pete\" Conrad.\n",
" β βββ 6. Search for \"Astronaut Group\" to find that Conrad was a member of NASA Astronaut Group 2.\n",
" β βββ 7. Open the Wikipedia pages for each member of NASA Astronaut Group 2.\n",
" β βββ 8. For those who are not deceased, go to View history and select the latest version of their Wikipedia page as of August 2023.\n",
" β βββ 9. Compare the times listed in the infobox of each astronaut's Wikipedia page under \"Time in space\", observing that Ed White has the least time in space with 4d 01h 56m, but also that Elliott See does not have a listed \"Time in space\".\n",
" β βββ 10. Read through Elliot See's Wikipedia article to find that he died in an accident before his first space flight, so he should be excluded, making Ed White's 4d 01h 56m the least amount of time in space.\n",
" β βββ 11. Convert 4d 01h 56m to minutes: 4d * 24h/d * 60m/h + 1h * 60m/h + 56m = 5,876m\n",
" β βββ 12. Format the final answer as specified: White; 5,876\n",
" βββ Number of steps: 12\n",
" βββ How long did this take?: 10\n",
" βββ Tools:\n",
" β βββ 1. Web browser\n",
" β βββ 2. Search engine\n",
" β βββ 3. Image processing tools\n",
" β βββ 4. Calculator\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",
"# 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)\n"
]
},
{
"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",
")\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)\n"
]
},
{
"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}]\")\n"
]
},
{
"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)\n"
]
},
{
"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"
]
}
],
"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
}
|