Spaces:
Runtime error
Runtime error
File size: 40,893 Bytes
694d535 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Install any required libraries"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"!pip install -U -q langchain langchain-openai langchain_core langchain-community langchainhub openai"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"!pip install -qU faiss_cpu pymupdf pandas"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"!pip install -qU ragas"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set environment variables"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import openai\n",
"from getpass import getpass\n",
"\n",
"openai.api_key = getpass(\"Please provide your OpenAI Key: \")\n",
"os.environ[\"OPENAI_API_KEY\"] = openai.api_key"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Load Data"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.document_loaders import PyMuPDFLoader\n",
"\n",
"loader = PyMuPDFLoader(\n",
" \"input_data/nvidia_10k.pdf\",\n",
")\n",
"\n",
"documents = loader.load()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'source': 'input_data/nvidia_10k.pdf',\n",
" 'file_path': 'input_data/nvidia_10k.pdf',\n",
" 'page': 0,\n",
" 'total_pages': 96,\n",
" 'format': 'PDF 1.4',\n",
" 'title': '0001045810-24-000029',\n",
" 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group',\n",
" 'subject': 'Form 10-K filed on 2024-02-21 for the period ending 2024-01-28',\n",
" 'keywords': '0001045810-24-000029; ; 10-K',\n",
" 'creator': 'EDGAR Filing HTML Converter',\n",
" 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0',\n",
" 'creationDate': \"D:20240221173732-05'00'\",\n",
" 'modDate': \"D:20240221173744-05'00'\",\n",
" 'trapped': '',\n",
" 'encryption': 'Standard V2 R3 128-bit RC4'}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"documents[0].metadata"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Transform - Split documents into chunks"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
"\n",
"text_splitter = RecursiveCharacterTextSplitter(\n",
" chunk_size = 700,\n",
" chunk_overlap = 50\n",
")\n",
"\n",
"documents = text_splitter.split_documents(documents)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"624"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(documents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Load OpenAI Embeddings model"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"from langchain_openai import OpenAIEmbeddings\n",
"\n",
"embeddings = OpenAIEmbeddings(\n",
" model=\"text-embedding-3-small\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a FAISS Vector Store"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.vectorstores import FAISS\n",
"\n",
"vector_store = FAISS.from_documents(documents, embeddings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a Retriever"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"retriever = vector_store.as_retriever()\n",
"retrieved_documents = retriever.invoke(\"Who is the E-VP, Operations - and how old are they?\")"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"page_content=\"Debora Shoquist\\n69\\nExecutive Vice President, Operations\\nTimothy S. Teter\\n57\\nExecutive Vice President and General Counsel\\nJen-Hsun Huang co-founded NVIDIA in 1993 and has served as our President, Chief Executive Officer, and a member of the Board of Directors since our\\ninception. From 1985 to 1993, Mr. Huang was employed at LSI Logic Corporation, a computer chip manufacturer, where he held a variety of positions including\\nas Director of Coreware, the business unit responsible for LSI's SOC. From 1983 to 1985, Mr. Huang was a microprocessor designer for AMD, a semiconductor\\ncompany. Mr. Huang holds a B.S.E.E. degree from Oregon State University and an M.S.E.E. degree from Stanford University.\" metadata={'source': 'input_data/nvidia_10k.pdf', 'file_path': 'input_data/nvidia_10k.pdf', 'page': 11, 'total_pages': 96, 'format': 'PDF 1.4', 'title': '0001045810-24-000029', 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group', 'subject': 'Form 10-K filed on 2024-02-21 for the period ending 2024-01-28', 'keywords': '0001045810-24-000029; ; 10-K', 'creator': 'EDGAR Filing HTML Converter', 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', 'creationDate': \"D:20240221173732-05'00'\", 'modDate': \"D:20240221173744-05'00'\", 'trapped': '', 'encryption': 'Standard V2 R3 128-bit RC4'}\n",
"page_content='supports diverse hiring, retention, and employee engagement, which we believe makes NVIDIA a great place to work.\\nDuring fiscal year 2025, we will continue to have a flexible work environment and maintain our company wide 2-days off a quarter for employees to rest and\\nrecharge.\\nInformation About Our Executive Officers\\nThe following sets forth certain information regarding our executive officers, their ages, and positions as of February\\xa016, 2024:\\nName\\nAge\\nPosition\\nJen-Hsun Huang\\n60\\nPresident and Chief Executive Officer\\nColette M. Kress\\n56\\nExecutive Vice President and Chief Financial Officer\\nAjay K. Puri\\n69\\nExecutive Vice President, Worldwide Field Operations\\nDebora Shoquist\\n69' metadata={'source': 'input_data/nvidia_10k.pdf', 'file_path': 'input_data/nvidia_10k.pdf', 'page': 11, 'total_pages': 96, 'format': 'PDF 1.4', 'title': '0001045810-24-000029', 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group', 'subject': 'Form 10-K filed on 2024-02-21 for the period ending 2024-01-28', 'keywords': '0001045810-24-000029; ; 10-K', 'creator': 'EDGAR Filing HTML Converter', 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', 'creationDate': \"D:20240221173732-05'00'\", 'modDate': \"D:20240221173744-05'00'\", 'trapped': '', 'encryption': 'Standard V2 R3 128-bit RC4'}\n",
"page_content='Puri previously held marketing, management consulting, and product development positions at Hewlett-Packard, an information technology company, Booz Allen\\nHamilton Inc., a management and technology consulting company, and Texas Instruments Incorporated. Mr. Puri holds a B.S.E.E. degree from the University of\\nMinnesota, an M.S.E.E. degree from the California Institute of Technology and an M.B.A. degree from Harvard Business School.\\nDebora Shoquist joined NVIDIA in 2007 as Senior Vice President of Operations and in 2009 became Executive Vice President of Operations. Prior to NVIDIA,' metadata={'source': 'input_data/nvidia_10k.pdf', 'file_path': 'input_data/nvidia_10k.pdf', 'page': 12, 'total_pages': 96, 'format': 'PDF 1.4', 'title': '0001045810-24-000029', 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group', 'subject': 'Form 10-K filed on 2024-02-21 for the period ending 2024-01-28', 'keywords': '0001045810-24-000029; ; 10-K', 'creator': 'EDGAR Filing HTML Converter', 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', 'creationDate': \"D:20240221173732-05'00'\", 'modDate': \"D:20240221173744-05'00'\", 'trapped': '', 'encryption': 'Standard V2 R3 128-bit RC4'}\n",
"page_content='Table of Contents\\nstrategy, planning, reporting and business development for the division. Prior to joining Microsoft, Ms. Kress spent eight years at Texas Instruments Incorporated,\\na semiconductor company, where she held a variety of finance positions. Ms. Kress holds a B.S. degree in Finance from University of Arizona and an M.B.A.\\ndegree from Southern Methodist University.\\nAjay K. Puri joined NVIDIA in 2005 as Senior Vice President, Worldwide Sales and became Executive Vice President, Worldwide Field Operations in 2009. Prior\\nto NVIDIA, he held positions in sales, marketing, and general management over a 22-year career at Sun Microsystems, Inc., a computing systems company. Mr.' metadata={'source': 'input_data/nvidia_10k.pdf', 'file_path': 'input_data/nvidia_10k.pdf', 'page': 12, 'total_pages': 96, 'format': 'PDF 1.4', 'title': '0001045810-24-000029', 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group', 'subject': 'Form 10-K filed on 2024-02-21 for the period ending 2024-01-28', 'keywords': '0001045810-24-000029; ; 10-K', 'creator': 'EDGAR Filing HTML Converter', 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', 'creationDate': \"D:20240221173732-05'00'\", 'modDate': \"D:20240221173744-05'00'\", 'trapped': '', 'encryption': 'Standard V2 R3 128-bit RC4'}\n"
]
}
],
"source": [
"for doc in retrieved_documents:\n",
" print(doc)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create a RAG Chain"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"from langchain.prompts import ChatPromptTemplate\n",
"\n",
"template = \"\"\"Answer the question based only on the following context. If you cannot answer the question with the context, please respond with 'I don't know':\n",
"\n",
"Context:\n",
"{context}\n",
"\n",
"Question:\n",
"{question}\n",
"\"\"\"\n",
"\n",
"prompt = ChatPromptTemplate.from_template(template)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"from operator import itemgetter\n",
"\n",
"from langchain_openai import ChatOpenAI\n",
"from langchain_core.output_parsers import StrOutputParser\n",
"from langchain_core.runnables import RunnablePassthrough\n",
"\n",
"primary_qa_llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0)\n",
"\n",
"retrieval_augmented_qa_chain = (\n",
" # INVOKE CHAIN WITH: {\"question\" : \"<<SOME USER QUESTION>>\"}\n",
" # \"question\" : populated by getting the value of the \"question\" key\n",
" # \"context\" : populated by getting the value of the \"question\" key and chaining it into the base_retriever\n",
" {\"context\": itemgetter(\"question\") | retriever, \"question\": itemgetter(\"question\")}\n",
" # \"context\" : is assigned to a RunnablePassthrough object (will not be called or considered in the next step)\n",
" # by getting the value of the \"context\" key from the previous step\n",
" | RunnablePassthrough.assign(context=itemgetter(\"context\"))\n",
" # \"response\" : the \"context\" and \"question\" values are used to format our prompt object and then piped\n",
" # into the LLM and stored in a key called \"response\"\n",
" # \"context\" : populated by getting the value of the \"context\" key from the previous step\n",
" | {\"response\": prompt | primary_qa_llm, \"context\": itemgetter(\"context\")}\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Mid-Term Challenge Tests"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Who is the E-VP, Operations - and how old are they?"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Debora Shoquist, 69 years old.\n"
]
}
],
"source": [
"question = \"Who is the E-VP, Operations - and how old are they?\"\n",
"\n",
"result = retrieval_augmented_qa_chain.invoke({\"question\" : question})\n",
"\n",
"print(result[\"response\"].content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### What is the gross carrying amount of Total Amortizable Intangible Assets for Jan 29, 2023?"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"$3,539 million\n"
]
}
],
"source": [
"question = \"What is the gross carrying amount of Total Amortizable Intangible Assets for Jan 29, 2023?\"\n",
"\n",
"result = retrieval_augmented_qa_chain.invoke({\"question\" : question})\n",
"\n",
"print(result[\"response\"].content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Evaluation using RAGAS"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"eval_documents = documents\n",
"\n",
"text_splitter = RecursiveCharacterTextSplitter(\n",
" chunk_size = 1500,\n",
" chunk_overlap = 400\n",
")\n",
"\n",
"eval_documents = text_splitter.split_documents(eval_documents)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"624"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(documents)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/var/folders/_1/hpp7wgls4pb3zx13lgn3cp8w0000gn/T/ipykernel_93059/735169035.py:4: DeprecationWarning: The function with_openai was deprecated in 0.1.4, and will be removed in the 0.2.0 release. Use from_langchain instead.\n",
" generator = TestsetGenerator.with_openai()\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d98b77660cf94470b304eb2909723ffb",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"embedding nodes: 0%| | 0/1248 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Filename and doc_id are the same for all nodes.\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "dc4d9a604cd747e99866b9b32c1ba98c",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Generating: 0%| | 0/10 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from ragas.testset.generator import TestsetGenerator\n",
"from ragas.testset.evolutions import simple, reasoning, multi_context\n",
"\n",
"generator = TestsetGenerator.with_openai()\n",
"\n",
"testset = generator.generate_with_langchain_docs(documents, test_size=10, distributions={simple: 0.25, reasoning: 0.25, multi_context: 0.5})"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"DataRow(question='What steps does the vendor risk assessment process involve to mitigate cybersecurity threats?', contexts=['mitigate and recover from identified and significant cybersecurity threats.\\nWe also have a vendor risk assessment process consisting of the distribution and review of supplier questionnaires designed to help us evaluate cybersecurity\\nrisks that we may encounter when working with third parties that have access to confidential and other sensitive company information. We take steps designed\\nto ensure that such vendors have implemented data privacy and security controls that help mitigate the cybersecurity risks associated with these vendors. We'], ground_truth='The vendor risk assessment process involves the distribution and review of supplier questionnaires designed to evaluate cybersecurity risks. The goal is to ensure that vendors have implemented data privacy and security controls to mitigate cybersecurity risks.', evolution_type='simple', metadata=[{'source': 'input_data/nvidia_10k.pdf', 'file_path': 'input_data/nvidia_10k.pdf', 'page': 30, 'total_pages': 96, 'format': 'PDF 1.4', 'title': '0001045810-24-000029', 'author': 'EDGAR® Online LLC, a subsidiary of OTC Markets Group', 'subject': 'Form 10-K filed on 2024-02-21 for the period ending 2024-01-28', 'keywords': '0001045810-24-000029; ; 10-K', 'creator': 'EDGAR Filing HTML Converter', 'producer': 'EDGRpdf Service w/ EO.Pdf 22.0.40.0', 'creationDate': \"D:20240221173732-05'00'\", 'modDate': \"D:20240221173744-05'00'\", 'trapped': '', 'encryption': 'Standard V2 R3 128-bit RC4'}])"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"testset.test_data[0]"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>question</th>\n",
" <th>contexts</th>\n",
" <th>ground_truth</th>\n",
" <th>evolution_type</th>\n",
" <th>metadata</th>\n",
" <th>episode_done</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>What steps does the vendor risk assessment pro...</td>\n",
" <td>[mitigate and recover from identified and sign...</td>\n",
" <td>The vendor risk assessment process involves th...</td>\n",
" <td>simple</td>\n",
" <td>[{'source': 'input_data/nvidia_10k.pdf', 'file...</td>\n",
" <td>True</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>How has NVIDIA been successful in attracting g...</td>\n",
" <td>[relating to human capital management.\\nTo be ...</td>\n",
" <td>NVIDIA has been successful in attracting globa...</td>\n",
" <td>simple</td>\n",
" <td>[{'source': 'input_data/nvidia_10k.pdf', 'file...</td>\n",
" <td>True</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>How is revenue designated based on billing loc...</td>\n",
" <td>[Table of Contents\\nAll Other operating loss -...</td>\n",
" <td>Revenue by geographic region is designated bas...</td>\n",
" <td>reasoning</td>\n",
" <td>[{'source': 'input_data/nvidia_10k.pdf', 'file...</td>\n",
" <td>True</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>How did the U.S. federal research tax credit a...</td>\n",
" <td>[The effective tax rate increased due to a dec...</td>\n",
" <td>The U.S. federal research tax credit, along wi...</td>\n",
" <td>reasoning</td>\n",
" <td>[{'source': 'input_data/nvidia_10k.pdf', 'file...</td>\n",
" <td>True</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>What is the purpose of a company's internal co...</td>\n",
" <td>[procedures as we considered necessary in the ...</td>\n",
" <td>A company's internal control over financial re...</td>\n",
" <td>multi_context</td>\n",
" <td>[{'source': 'input_data/nvidia_10k.pdf', 'file...</td>\n",
" <td>True</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" question \\\n",
"0 What steps does the vendor risk assessment pro... \n",
"1 How has NVIDIA been successful in attracting g... \n",
"2 How is revenue designated based on billing loc... \n",
"3 How did the U.S. federal research tax credit a... \n",
"4 What is the purpose of a company's internal co... \n",
"\n",
" contexts \\\n",
"0 [mitigate and recover from identified and sign... \n",
"1 [relating to human capital management.\\nTo be ... \n",
"2 [Table of Contents\\nAll Other operating loss -... \n",
"3 [The effective tax rate increased due to a dec... \n",
"4 [procedures as we considered necessary in the ... \n",
"\n",
" ground_truth evolution_type \\\n",
"0 The vendor risk assessment process involves th... simple \n",
"1 NVIDIA has been successful in attracting globa... simple \n",
"2 Revenue by geographic region is designated bas... reasoning \n",
"3 The U.S. federal research tax credit, along wi... reasoning \n",
"4 A company's internal control over financial re... multi_context \n",
"\n",
" metadata episode_done \n",
"0 [{'source': 'input_data/nvidia_10k.pdf', 'file... True \n",
"1 [{'source': 'input_data/nvidia_10k.pdf', 'file... True \n",
"2 [{'source': 'input_data/nvidia_10k.pdf', 'file... True \n",
"3 [{'source': 'input_data/nvidia_10k.pdf', 'file... True \n",
"4 [{'source': 'input_data/nvidia_10k.pdf', 'file... True "
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_df = testset.to_pandas()\n",
"test_df.head()"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"test_questions = test_df[\"question\"].values.tolist()\n",
"test_groundtruths = test_df[\"ground_truth\"].values.tolist()"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"answers = []\n",
"contexts = []\n",
"\n",
"for question in test_questions:\n",
" response = retrieval_augmented_qa_chain.invoke({\"question\" : question})\n",
" answers.append(response[\"response\"].content)\n",
" contexts.append([context.page_content for context in response[\"context\"]])"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [],
"source": [
"from datasets import Dataset\n",
"\n",
"response_dataset = Dataset.from_dict({\n",
" \"question\" : test_questions,\n",
" \"answer\" : answers,\n",
" \"contexts\" : contexts,\n",
" \"ground_truth\" : test_groundtruths\n",
"})"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'question': 'What steps does the vendor risk assessment process involve to mitigate cybersecurity threats?',\n",
" 'answer': 'The vendor risk assessment process involves the distribution and review of supplier questionnaires designed to evaluate cybersecurity risks associated with third parties.',\n",
" 'contexts': ['mitigate and recover from identified and significant cybersecurity threats.\\nWe also have a vendor risk assessment process consisting of the distribution and review of supplier questionnaires designed to help us evaluate cybersecurity\\nrisks that we may encounter when working with third parties that have access to confidential and other sensitive company information. We take steps designed\\nto ensure that such vendors have implemented data privacy and security controls that help mitigate the cybersecurity risks associated with these vendors. We',\n",
" 'routinely assess our high-risk suppliers’ conformance to industry standards (e.g., ISO 27001, ISO 28001, and C-TPAT), and we evaluate them for additional\\ninformation, product, and physical security requirements.\\nRefer to “Item 1A. Risk factors” in this annual report on Form 10-K for additional information about cybersecurity-related risks.\\nGovernance\\nInformation security matters, including managing and assessing risks from cybersecurity threats, remain under the oversight of the Company’s Board of\\nDirectors, or the Board. The Audit Committee of the Board, or the Audit Committee, also reviews the adequacy and effectiveness of the Company’s information',\n",
" 'threats. Our information security management program generally follows processes outlined in frameworks such as the ISO 27001 international standard for\\nInformation Security and we evaluate and evolve our security measures as appropriate. We consult with external parties, such as cybersecurity firms and risk\\nmanagement and governance experts, on risk management and strategy.\\nIdentifying, assessing, and managing cybersecurity risk is integrated into our overall risk management systems and processes, and we have in place\\ncybersecurity and data privacy training and policies designed to (a) respond to new requirements in global privacy laws and (b) prevent, detect, respond to,',\n",
" 'material risks from cybersecurity threats. Our Chief Security Officer’s cybersecurity expertise includes over 17 years of combined government and private sector\\nassignments.\\n31'],\n",
" 'ground_truth': 'The vendor risk assessment process involves the distribution and review of supplier questionnaires designed to evaluate cybersecurity risks. The goal is to ensure that vendors have implemented data privacy and security controls to mitigate cybersecurity risks.'}"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"response_dataset[0]"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [],
"source": [
"from ragas import evaluate\n",
"from ragas.metrics import (\n",
" faithfulness,\n",
" answer_relevancy,\n",
" answer_correctness,\n",
" context_recall,\n",
" context_precision,\n",
")\n",
"\n",
"metrics = [\n",
" faithfulness,\n",
" answer_relevancy,\n",
" context_recall,\n",
" context_precision,\n",
" answer_correctness,\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d9f291cd7c7a457a8873d8650383df87",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Evaluating: 0%| | 0/50 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"results = evaluate(response_dataset, metrics)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### RAGAS Results"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'faithfulness': 0.9500, 'answer_relevancy': 0.9488, 'context_recall': 1.0000, 'context_precision': 0.7861, 'answer_correctness': 0.7919}"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"results"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>question</th>\n",
" <th>answer</th>\n",
" <th>contexts</th>\n",
" <th>ground_truth</th>\n",
" <th>faithfulness</th>\n",
" <th>answer_relevancy</th>\n",
" <th>context_recall</th>\n",
" <th>context_precision</th>\n",
" <th>answer_correctness</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>What steps does the vendor risk assessment pro...</td>\n",
" <td>The vendor risk assessment process involves th...</td>\n",
" <td>[mitigate and recover from identified and sign...</td>\n",
" <td>The vendor risk assessment process involves th...</td>\n",
" <td>1.0</td>\n",
" <td>0.941041</td>\n",
" <td>1.0</td>\n",
" <td>0.833333</td>\n",
" <td>0.620211</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>How has NVIDIA been successful in attracting g...</td>\n",
" <td>NVIDIA has been successful in attracting globa...</td>\n",
" <td>[relating to human capital management.\\nTo be ...</td>\n",
" <td>NVIDIA has been successful in attracting globa...</td>\n",
" <td>1.0</td>\n",
" <td>0.999999</td>\n",
" <td>1.0</td>\n",
" <td>0.833333</td>\n",
" <td>1.000000</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>How is revenue designated based on billing loc...</td>\n",
" <td>Revenue is designated based on the billing loc...</td>\n",
" <td>[10 \\n(2)\\n— \\nTotal\\n$\\n(4,890)\\n$\\n(5,411)\\n...</td>\n",
" <td>Revenue by geographic region is designated bas...</td>\n",
" <td>1.0</td>\n",
" <td>0.900000</td>\n",
" <td>1.0</td>\n",
" <td>1.000000</td>\n",
" <td>0.743623</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>How did the U.S. federal research tax credit a...</td>\n",
" <td>The U.S. federal research tax credit, along wi...</td>\n",
" <td>[The effective tax rate increased due to a dec...</td>\n",
" <td>The U.S. federal research tax credit, along wi...</td>\n",
" <td>0.5</td>\n",
" <td>0.854537</td>\n",
" <td>1.0</td>\n",
" <td>0.916667</td>\n",
" <td>0.745303</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>What is the purpose of a company's internal co...</td>\n",
" <td>The purpose of a company's internal control ov...</td>\n",
" <td>[Management’s Annual Report on Internal Contro...</td>\n",
" <td>A company's internal control over financial re...</td>\n",
" <td>1.0</td>\n",
" <td>0.950108</td>\n",
" <td>1.0</td>\n",
" <td>1.000000</td>\n",
" <td>0.743341</td>\n",
" </tr>\n",
" <tr>\n",
" <th>5</th>\n",
" <td>How does NVIDIA align their principles with su...</td>\n",
" <td>NVIDIA aligns their principles with sustainabi...</td>\n",
" <td>[Sustainability and Governance\\nNVIDIA invents...</td>\n",
" <td>NVIDIA integrates sound environmental, social,...</td>\n",
" <td>1.0</td>\n",
" <td>0.965690</td>\n",
" <td>1.0</td>\n",
" <td>1.000000</td>\n",
" <td>0.838499</td>\n",
" </tr>\n",
" <tr>\n",
" <th>6</th>\n",
" <td>What technologies does NVIDIA RTX use to enhan...</td>\n",
" <td>NVIDIA RTX uses ray tracing technology and dee...</td>\n",
" <td>[television graphics.\\nThe NVIDIA RTX platform...</td>\n",
" <td>NVIDIA RTX uses ray tracing technology and dee...</td>\n",
" <td>1.0</td>\n",
" <td>0.976349</td>\n",
" <td>1.0</td>\n",
" <td>0.638889</td>\n",
" <td>0.999318</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7</th>\n",
" <td>What types of stock-based awards can be grante...</td>\n",
" <td>The types of stock-based awards that can be gr...</td>\n",
" <td>[The 2007 Plan authorizes the issuance of ince...</td>\n",
" <td>The types of stock-based awards that can be gr...</td>\n",
" <td>1.0</td>\n",
" <td>0.955835</td>\n",
" <td>1.0</td>\n",
" <td>0.805556</td>\n",
" <td>0.617505</td>\n",
" </tr>\n",
" <tr>\n",
" <th>8</th>\n",
" <td>What is the purpose of rebates for resellers a...</td>\n",
" <td>The purpose of rebates for resellers is to ser...</td>\n",
" <td>[For products sold with a right of return, we ...</td>\n",
" <td>The purpose of rebates for resellers is to ser...</td>\n",
" <td>1.0</td>\n",
" <td>0.944586</td>\n",
" <td>1.0</td>\n",
" <td>0.000000</td>\n",
" <td>0.611390</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9</th>\n",
" <td>How has NVIDIA been successful in attracting g...</td>\n",
" <td>NVIDIA has been successful in attracting globa...</td>\n",
" <td>[relating to human capital management.\\nTo be ...</td>\n",
" <td>NVIDIA has been successful in attracting globa...</td>\n",
" <td>1.0</td>\n",
" <td>1.000000</td>\n",
" <td>1.0</td>\n",
" <td>0.833333</td>\n",
" <td>1.000000</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" question \\\n",
"0 What steps does the vendor risk assessment pro... \n",
"1 How has NVIDIA been successful in attracting g... \n",
"2 How is revenue designated based on billing loc... \n",
"3 How did the U.S. federal research tax credit a... \n",
"4 What is the purpose of a company's internal co... \n",
"5 How does NVIDIA align their principles with su... \n",
"6 What technologies does NVIDIA RTX use to enhan... \n",
"7 What types of stock-based awards can be grante... \n",
"8 What is the purpose of rebates for resellers a... \n",
"9 How has NVIDIA been successful in attracting g... \n",
"\n",
" answer \\\n",
"0 The vendor risk assessment process involves th... \n",
"1 NVIDIA has been successful in attracting globa... \n",
"2 Revenue is designated based on the billing loc... \n",
"3 The U.S. federal research tax credit, along wi... \n",
"4 The purpose of a company's internal control ov... \n",
"5 NVIDIA aligns their principles with sustainabi... \n",
"6 NVIDIA RTX uses ray tracing technology and dee... \n",
"7 The types of stock-based awards that can be gr... \n",
"8 The purpose of rebates for resellers is to ser... \n",
"9 NVIDIA has been successful in attracting globa... \n",
"\n",
" contexts \\\n",
"0 [mitigate and recover from identified and sign... \n",
"1 [relating to human capital management.\\nTo be ... \n",
"2 [10 \\n(2)\\n— \\nTotal\\n$\\n(4,890)\\n$\\n(5,411)\\n... \n",
"3 [The effective tax rate increased due to a dec... \n",
"4 [Management’s Annual Report on Internal Contro... \n",
"5 [Sustainability and Governance\\nNVIDIA invents... \n",
"6 [television graphics.\\nThe NVIDIA RTX platform... \n",
"7 [The 2007 Plan authorizes the issuance of ince... \n",
"8 [For products sold with a right of return, we ... \n",
"9 [relating to human capital management.\\nTo be ... \n",
"\n",
" ground_truth faithfulness \\\n",
"0 The vendor risk assessment process involves th... 1.0 \n",
"1 NVIDIA has been successful in attracting globa... 1.0 \n",
"2 Revenue by geographic region is designated bas... 1.0 \n",
"3 The U.S. federal research tax credit, along wi... 0.5 \n",
"4 A company's internal control over financial re... 1.0 \n",
"5 NVIDIA integrates sound environmental, social,... 1.0 \n",
"6 NVIDIA RTX uses ray tracing technology and dee... 1.0 \n",
"7 The types of stock-based awards that can be gr... 1.0 \n",
"8 The purpose of rebates for resellers is to ser... 1.0 \n",
"9 NVIDIA has been successful in attracting globa... 1.0 \n",
"\n",
" answer_relevancy context_recall context_precision answer_correctness \n",
"0 0.941041 1.0 0.833333 0.620211 \n",
"1 0.999999 1.0 0.833333 1.000000 \n",
"2 0.900000 1.0 1.000000 0.743623 \n",
"3 0.854537 1.0 0.916667 0.745303 \n",
"4 0.950108 1.0 1.000000 0.743341 \n",
"5 0.965690 1.0 1.000000 0.838499 \n",
"6 0.976349 1.0 0.638889 0.999318 \n",
"7 0.955835 1.0 0.805556 0.617505 \n",
"8 0.944586 1.0 0.000000 0.611390 \n",
"9 1.000000 1.0 0.833333 1.000000 "
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"results_df = results.to_pandas()\n",
"results_df"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "py_3_11_lamma2_run",
"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.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|