Spaces:
Running
Running
File size: 105,218 Bytes
cf7a8a2 |
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 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.6.40">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Advanced RAG – Open-Source AI Cookbook</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { display: inline-block; text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
</style>
<script src="../site_libs/quarto-nav/quarto-nav.js"></script>
<script src="../site_libs/quarto-nav/headroom.min.js"></script>
<script src="../site_libs/clipboard/clipboard.min.js"></script>
<script src="../site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="../site_libs/quarto-search/fuse.min.js"></script>
<script src="../site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="../">
<script src="../site_libs/quarto-html/quarto.js"></script>
<script src="../site_libs/quarto-html/popper.min.js"></script>
<script src="../site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="../site_libs/quarto-html/anchor.min.js"></script>
<link href="../site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="../site_libs/quarto-html/quarto-syntax-highlighting-549806ee2085284f45b00abea8c6df48.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="../site_libs/bootstrap/bootstrap.min.js"></script>
<link href="../site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="../site_libs/bootstrap/bootstrap-2be10d9e998f81ff6e49e26833438aa5.min.css" rel="stylesheet" append-hash="true" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
"location": "sidebar",
"copy-button": false,
"collapse-after": 3,
"panel-placement": "start",
"type": "textbox",
"limit": 50,
"keyboard-shortcut": [
"f",
"/",
"s"
],
"show-item-context": false,
"language": {
"search-no-results-text": "No results",
"search-matching-documents-text": "matching documents",
"search-copy-link-title": "Copy link to search",
"search-hide-matches-text": "Hide additional matches",
"search-more-match-text": "more match in this document",
"search-more-matches-text": "more matches in this document",
"search-clear-button-title": "Clear",
"search-text-placeholder": "",
"search-detached-cancel-button-title": "Cancel",
"search-submit-button-title": "Submit",
"search-label": "Search"
}
}</script>
<link rel="stylesheet" href="../styles.css">
</head>
<body class="nav-sidebar docked">
<div id="quarto-search-results"></div>
<header id="quarto-header" class="headroom fixed-top">
<nav class="quarto-secondary-nav">
<div class="container-fluid d-flex">
<button type="button" class="quarto-btn-toggle btn" data-bs-toggle="collapse" role="button" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
<i class="bi bi-layout-text-sidebar-reverse"></i>
</button>
<nav class="quarto-page-breadcrumbs" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item">Open-Source AI Cookbook</li><li class="breadcrumb-item"><a href="../notebooks/rag_zephyr_langchain.html">RAG Techniques</a></li><li class="breadcrumb-item"><a href="../notebooks/advanced_rag.html">Advanced RAG</a></li></ol></nav>
<a class="flex-grow-1" role="navigation" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
</a>
<button type="button" class="btn quarto-search-button" aria-label="Search" onclick="window.quartoOpenSearch();">
<i class="bi bi-search"></i>
</button>
</div>
</nav>
</header>
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
<nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal quarto-sidebar-collapse-item sidebar-navigation docked overflow-auto">
<div class="pt-lg-2 mt-2 text-left sidebar-header">
<div class="sidebar-title mb-0 py-0">
<a href="../">Open-Source AI Cookbook</a>
</div>
</div>
<div class="mt-2 flex-shrink-0 align-items-center">
<div class="sidebar-search">
<div id="quarto-search" class="" title="Search"></div>
</div>
</div>
<div class="sidebar-menu-container">
<ul class="list-unstyled mt-1">
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" role="navigation" aria-expanded="true">
<span class="menu-text">About</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-1" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../index.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">About Quarto</span></a>
</div>
</li>
</ul>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true">
<span class="menu-text">Open-Source AI Cookbook</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-2" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true">
<span class="menu-text">RAG Techniques</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-3" class="collapse list-unstyled sidebar-section depth2 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/rag_zephyr_langchain.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">RAG Zephyr & LangChain</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/advanced_rag.html" class="sidebar-item-text sidebar-link active">
<span class="menu-text">Advanced RAG</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/rag_evaluation.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">RAG Evaluation</span></a>
</div>
</li>
</ul>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-4" role="navigation" aria-expanded="true">
<span class="menu-text">Additional Techniques</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-4" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-4" class="collapse list-unstyled sidebar-section depth2 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/automatic_embedding.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">Automatic Embedding</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/faiss.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">FAISS for Efficient Search</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../notebooks/single_gpu.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">Single GPU Optimization</span></a>
</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div id="quarto-sidebar-glass" class="quarto-sidebar-collapse-item" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item"></div>
<!-- margin-sidebar -->
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<nav id="TOC" role="doc-toc" class="toc-active">
<h2 id="toc-title">On this page</h2>
<ul>
<li><a href="#load-your-knowledge-base" id="toc-load-your-knowledge-base" class="nav-link active" data-scroll-target="#load-your-knowledge-base">Load your knowledge base</a></li>
<li><a href="#retriever---embeddings" id="toc-retriever---embeddings" class="nav-link" data-scroll-target="#retriever---embeddings">1. Retriever - embeddings 🗂️</a>
<ul class="collapse">
<li><a href="#split-the-documents-into-chunks" id="toc-split-the-documents-into-chunks" class="nav-link" data-scroll-target="#split-the-documents-into-chunks">1.1 Split the documents into chunks</a></li>
<li><a href="#building-the-vector-database" id="toc-building-the-vector-database" class="nav-link" data-scroll-target="#building-the-vector-database">1.2 Building the vector database</a></li>
</ul></li>
<li><a href="#reader---llm" id="toc-reader---llm" class="nav-link" data-scroll-target="#reader---llm">2. Reader - LLM 💬</a>
<ul class="collapse">
<li><a href="#reader-model" id="toc-reader-model" class="nav-link" data-scroll-target="#reader-model">2.1. Reader model</a></li>
<li><a href="#prompt" id="toc-prompt" class="nav-link" data-scroll-target="#prompt">2.2. Prompt</a></li>
<li><a href="#reranking" id="toc-reranking" class="nav-link" data-scroll-target="#reranking">2.3. Reranking</a></li>
</ul></li>
<li><a href="#assembling-it-all" id="toc-assembling-it-all" class="nav-link" data-scroll-target="#assembling-it-all">3. Assembling it all!</a></li>
<li><a href="#to-go-further" id="toc-to-go-further" class="nav-link" data-scroll-target="#to-go-further">To go further 🗺️</a>
<ul class="collapse">
<li><a href="#setting-up-an-evaluation-pipeline" id="toc-setting-up-an-evaluation-pipeline" class="nav-link" data-scroll-target="#setting-up-an-evaluation-pipeline">Setting up an evaluation pipeline</a></li>
<li><a href="#improving-the-retriever" id="toc-improving-the-retriever" class="nav-link" data-scroll-target="#improving-the-retriever">Improving the retriever</a></li>
<li><a href="#improving-the-reader" id="toc-improving-the-reader" class="nav-link" data-scroll-target="#improving-the-reader">Improving the reader</a></li>
</ul></li>
</ul>
</nav>
</div>
<!-- main -->
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default"><nav class="quarto-page-breadcrumbs quarto-title-breadcrumbs d-none d-lg-block" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item">Open-Source AI Cookbook</li><li class="breadcrumb-item"><a href="../notebooks/rag_zephyr_langchain.html">RAG Techniques</a></li><li class="breadcrumb-item"><a href="../notebooks/advanced_rag.html">Advanced RAG</a></li></ol></nav>
<div class="quarto-title">
<h1 class="title">Advanced RAG</h1>
</div>
<div class="quarto-title-meta">
</div>
</header>
<p>This notebook demonstrates how you can build an advanced RAG (Retrieval Augmented Generation) for answering a user’s question about a specific knowledge base (here, the HuggingFace documentation), using LangChain.</p>
<p>For an introduction to RAG, you can check <a href="../notebooks/rag_zephyr_langchain.html">this other cookbook</a>!</p>
<p>RAG systems are complex, with many moving parts: here a RAG diagram, where we noted in blue all possibilities for system enhancement:</p>
<p><img src="https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/RAG_workflow.png" height="700"></p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>💡 As you can see, there are many steps to tune in this architecture: tuning the system properly will yield significant performance gains.</p>
</div>
</div>
<p>In this notebook, we will take a look into many of these blue notes to see how to tune your RAG system and get the best performance.</p>
<p><strong>Let’s dig into the model building!</strong> First, we install the required model dependancies.</p>
<div id="7d75abe1" class="cell" data-execution_count="1">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="op">!</span>pip install <span class="op">-</span>q torch transformers transformers accelerate bitsandbytes langchain sentence<span class="op">-</span>transformers faiss<span class="op">-</span>gpu openpyxl pacmap</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="2a33957c" class="cell" data-execution_count="2">
<div class="sourceCode cell-code" id="cb2"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="op">%</span>reload_ext dotenv</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="op">%</span>dotenv</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="d3507708" class="cell" data-execution_count="3">
<div class="sourceCode cell-code" id="annotated-cell-3"><pre class="sourceCode python code-annotation-code code-with-copy code-annotated"><code class="sourceCode python"><span id="annotated-cell-3-1"><a href="#annotated-cell-3-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tqdm.notebook <span class="im">import</span> tqdm</span>
<span id="annotated-cell-3-2"><a href="#annotated-cell-3-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> pandas <span class="im">as</span> pd</span>
<span id="annotated-cell-3-3"><a href="#annotated-cell-3-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> typing <span class="im">import</span> Optional, List, Tuple</span>
<span id="annotated-cell-3-4"><a href="#annotated-cell-3-4" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> datasets <span class="im">import</span> Dataset</span>
<span id="annotated-cell-3-5"><a href="#annotated-cell-3-5" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt</span>
<span id="annotated-cell-3-6"><a href="#annotated-cell-3-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="annotated-cell-3-7"><a href="#annotated-cell-3-7" aria-hidden="true" tabindex="-1"></a>pd.set_option(</span>
<button class="code-annotation-anchor" data-target-cell="annotated-cell-3" data-target-annotation="1">1</button><span id="annotated-cell-3-8" class="code-annotation-target"><a href="#annotated-cell-3-8" aria-hidden="true" tabindex="-1"></a> <span class="st">"display.max_colwidth"</span>, <span class="va">None</span></span>
<span id="annotated-cell-3-9"><a href="#annotated-cell-3-9" aria-hidden="true" tabindex="-1"></a>) </span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-annotation">
<dl class="code-annotation-container-hidden code-annotation-container-grid">
<dt data-target-cell="annotated-cell-3" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-3" data-code-lines="8" data-code-annotation="1">This will be helpful when visualizing retriever outputs</span>
</dd>
</dl>
</div>
</div>
<section id="load-your-knowledge-base" class="level3">
<h3 class="anchored" data-anchor-id="load-your-knowledge-base">Load your knowledge base</h3>
<div id="acfee5b8" class="cell" data-execution_count="4">
<div class="sourceCode cell-code" id="cb3"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> datasets</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>ds <span class="op">=</span> datasets.load_dataset(<span class="st">"m-ric/huggingface_doc"</span>, split<span class="op">=</span><span class="st">"train"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="40339fbc" class="cell" data-execution_count="5">
<div class="sourceCode cell-code" id="cb4"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> langchain.docstore.document <span class="im">import</span> Document <span class="im">as</span> LangchainDocument</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>RAW_KNOWLEDGE_BASE <span class="op">=</span> [</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a> LangchainDocument(page_content<span class="op">=</span>doc[<span class="st">"text"</span>], metadata<span class="op">=</span>{<span class="st">"source"</span>: doc[<span class="st">"source"</span>]})</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> doc <span class="kw">in</span> tqdm(ds)</span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a>]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="retriever---embeddings" class="level1">
<h1>1. Retriever - embeddings 🗂️</h1>
<p>The <strong>retriever acts like an internal search engine</strong>: given the user query, it returns a few relevant snippets from your knowledge base.</p>
<p>These snippets will then be fed to the Reader Model to help it generate its answer.</p>
<p>So <strong>our objective here is, given a user question, to find the most snippets from our knowledge base to answer that question.</strong></p>
<p>This is a wide objective, it leaves open some questions. How many snippets should we retrieve? This parameter will be named <code>top_k</code>.</p>
<p>How long should these snippets be? This is called the <code>chunk size</code>. There’s no one-size-fits-all answers, but here are a few elements: - 🔀 Your <code>chunk size</code> is allowed to vary from one snippet to the other. - Since there will always be some noise in your retrieval, increasing the <code>top_k</code> increases the chance to get relevant elements in your retrieved snippets. 🎯 Shooting more arrows increases your probability to hit your target. - Meanwhile, the summed length of your retrieved documents should not be too high: for instance, for most current models 16k tokens will probably drown your Reader model in information due to <a href="https://huggingface.co/papers/2307.03172">Lost-in-the-middle phenomenon</a>. 🎯 Give your reader model only the most relevant insights, not a huge pile of books!</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>In this notebook, we use Langchain library since <strong>it offers a huge variety of options for vector databases and allows us to keep document metadata throughout the processing</strong>.</p>
</div>
</div>
<section id="split-the-documents-into-chunks" class="level3">
<h3 class="anchored" data-anchor-id="split-the-documents-into-chunks">1.1 Split the documents into chunks</h3>
<ul>
<li>In this part, <strong>we split the documents from our knowledge base into smaller chunks</strong> which will be the snippets on which the reader LLM will base its answer.</li>
<li>The goal is to prepare a collection of <strong>semantically relevant snippets</strong>. So their size should be adapted to precise ideas: too small will truncate ideas, too large will dilute them.</li>
</ul>
<div class="callout callout-style-default callout-tip callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Tip
</div>
</div>
<div class="callout-body-container callout-body">
<p>💡 Many options exist for text splitting: splitting on words, on sentence boundaries, recursive chunking that processes documents in a tree-like way to preserve structure information… To learn more about chunking, I recommend you read <a href="https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/5_Levels_Of_Text_Splitting.ipynb">this great notebook</a> by Greg Kamradt.</p>
</div>
</div>
<ul>
<li><strong>Recursive chunking</strong> breaks down the text into smaller parts step by step using a given list of separators sorted from the most important to the least important separator. If the first split doesn’t give the right size or shape chunks, the method repeats itself on the new chunks using a different separator. For instance with the list of separators <code>["\n\n", "\n", ".", ""]</code>:
<ul>
<li>The method will first break down the document wherever there is a double line break <code>"\n\n"</code>.</li>
<li>Resulting documents will be split again on simple line breaks <code>"\n"</code>, then on sentence ends <code>"."</code>.</li>
<li>And finally, if some chunks are still too big, they will be split whenever they overflow the maximum size.</li>
</ul></li>
<li>With this method, the global structure is well preserved, at the expense of getting slight variations in chunk size.</li>
</ul>
<blockquote class="blockquote">
<p><a href="https://huggingface.co/spaces/A-Roucher/chunk_visualizer">This space</a> lets you visualize how different splitting options affect the chunks you get.</p>
</blockquote>
<p>🔬 Let’s experiment a bit with chunk sizes, beginning with an arbitrary size, and see how splits work. We use Langchain’s implementation of recursive chunking with <code>RecursiveCharacterTextSplitter</code>. - Parameter <code>chunk_size</code> controls the length of individual chunks: this length is counted by default as the number of characters in the chunk. - Parameter <code>chunk_overlap</code> lets adjacent chunks get a bit of overlap on each other. This reduces the probability that an idea could be cut in half by the split between two adjacent chunks. We ~arbitrarily set this to 1/10th of the chunk size, you could try different values!</p>
<div id="7a7ac95d" class="cell" data-execution_count="6">
<div class="sourceCode cell-code" id="annotated-cell-6"><pre class="sourceCode python code-annotation-code code-with-copy code-annotated"><code class="sourceCode python"><span id="annotated-cell-6-1"><a href="#annotated-cell-6-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> langchain.text_splitter <span class="im">import</span> RecursiveCharacterTextSplitter</span>
<span id="annotated-cell-6-2"><a href="#annotated-cell-6-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="annotated-cell-6-3"><a href="#annotated-cell-6-3" aria-hidden="true" tabindex="-1"></a><span class="co"># We use a hierarchical list of separators specifically tailored for splitting Markdown documents</span></span>
<span id="annotated-cell-6-4"><a href="#annotated-cell-6-4" aria-hidden="true" tabindex="-1"></a><span class="co"># This list is taken from LangChain's MarkdownTextSplitter class.</span></span>
<span id="annotated-cell-6-5"><a href="#annotated-cell-6-5" aria-hidden="true" tabindex="-1"></a>MARKDOWN_SEPARATORS <span class="op">=</span> [</span>
<span id="annotated-cell-6-6"><a href="#annotated-cell-6-6" aria-hidden="true" tabindex="-1"></a> <span class="st">"</span><span class="ch">\n</span><span class="st">#{1,6} "</span>,</span>
<span id="annotated-cell-6-7"><a href="#annotated-cell-6-7" aria-hidden="true" tabindex="-1"></a> <span class="st">"```</span><span class="ch">\n</span><span class="st">"</span>,</span>
<span id="annotated-cell-6-8"><a href="#annotated-cell-6-8" aria-hidden="true" tabindex="-1"></a> <span class="st">"</span><span class="ch">\n\\</span><span class="st">*</span><span class="ch">\\</span><span class="st">*</span><span class="ch">\\</span><span class="st">*+</span><span class="ch">\n</span><span class="st">"</span>,</span>
<span id="annotated-cell-6-9"><a href="#annotated-cell-6-9" aria-hidden="true" tabindex="-1"></a> <span class="st">"</span><span class="ch">\n</span><span class="st">---+</span><span class="ch">\n</span><span class="st">"</span>,</span>
<span id="annotated-cell-6-10"><a href="#annotated-cell-6-10" aria-hidden="true" tabindex="-1"></a> <span class="st">"</span><span class="ch">\n</span><span class="st">___+</span><span class="ch">\n</span><span class="st">"</span>,</span>
<span id="annotated-cell-6-11"><a href="#annotated-cell-6-11" aria-hidden="true" tabindex="-1"></a> <span class="st">"</span><span class="ch">\n\n</span><span class="st">"</span>,</span>
<span id="annotated-cell-6-12"><a href="#annotated-cell-6-12" aria-hidden="true" tabindex="-1"></a> <span class="st">"</span><span class="ch">\n</span><span class="st">"</span>,</span>
<span id="annotated-cell-6-13"><a href="#annotated-cell-6-13" aria-hidden="true" tabindex="-1"></a> <span class="st">" "</span>,</span>
<span id="annotated-cell-6-14"><a href="#annotated-cell-6-14" aria-hidden="true" tabindex="-1"></a> <span class="st">""</span>,</span>
<span id="annotated-cell-6-15"><a href="#annotated-cell-6-15" aria-hidden="true" tabindex="-1"></a>]</span>
<span id="annotated-cell-6-16"><a href="#annotated-cell-6-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="annotated-cell-6-17"><a href="#annotated-cell-6-17" aria-hidden="true" tabindex="-1"></a>text_splitter <span class="op">=</span> RecursiveCharacterTextSplitter(</span>
<button class="code-annotation-anchor" data-target-cell="annotated-cell-6" data-target-annotation="1">1</button><span id="annotated-cell-6-18" class="code-annotation-target"><a href="#annotated-cell-6-18" aria-hidden="true" tabindex="-1"></a> chunk_size<span class="op">=</span><span class="dv">1000</span>,</span>
<button class="code-annotation-anchor" data-target-cell="annotated-cell-6" data-target-annotation="2">2</button><span id="annotated-cell-6-19" class="code-annotation-target"><a href="#annotated-cell-6-19" aria-hidden="true" tabindex="-1"></a> chunk_overlap<span class="op">=</span><span class="dv">100</span>,</span>
<button class="code-annotation-anchor" data-target-cell="annotated-cell-6" data-target-annotation="3">3</button><span id="annotated-cell-6-20" class="code-annotation-target"><a href="#annotated-cell-6-20" aria-hidden="true" tabindex="-1"></a> add_start_index<span class="op">=</span><span class="va">True</span>,</span>
<button class="code-annotation-anchor" data-target-cell="annotated-cell-6" data-target-annotation="4">4</button><span id="annotated-cell-6-21" class="code-annotation-target"><a href="#annotated-cell-6-21" aria-hidden="true" tabindex="-1"></a> strip_whitespace<span class="op">=</span><span class="va">True</span>,</span>
<span id="annotated-cell-6-22"><a href="#annotated-cell-6-22" aria-hidden="true" tabindex="-1"></a> separators<span class="op">=</span>MARKDOWN_SEPARATORS,</span>
<span id="annotated-cell-6-23"><a href="#annotated-cell-6-23" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="annotated-cell-6-24"><a href="#annotated-cell-6-24" aria-hidden="true" tabindex="-1"></a></span>
<span id="annotated-cell-6-25"><a href="#annotated-cell-6-25" aria-hidden="true" tabindex="-1"></a>docs_processed <span class="op">=</span> []</span>
<span id="annotated-cell-6-26"><a href="#annotated-cell-6-26" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> doc <span class="kw">in</span> RAW_KNOWLEDGE_BASE:</span>
<span id="annotated-cell-6-27"><a href="#annotated-cell-6-27" aria-hidden="true" tabindex="-1"></a> docs_processed <span class="op">+=</span> text_splitter.split_documents([doc])</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-annotation">
<dl class="code-annotation-container-hidden code-annotation-container-grid">
<dt data-target-cell="annotated-cell-6" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-6" data-code-lines="18" data-code-annotation="1">The maximum number of characters in a chunk: we selected this value arbitrally</span>
</dd>
<dt data-target-cell="annotated-cell-6" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-6" data-code-lines="19" data-code-annotation="2">The number of characters to overlap between chunks</span>
</dd>
<dt data-target-cell="annotated-cell-6" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-6" data-code-lines="20" data-code-annotation="3">If <code>True</code>, includes chunk’s start index in metadata</span>
</dd>
<dt data-target-cell="annotated-cell-6" data-target-annotation="4">4</dt>
<dd>
<span data-code-cell="annotated-cell-6" data-code-lines="21" data-code-annotation="4">If <code>True</code>, strips whitespace from the start and end of every document</span>
</dd>
</dl>
</div>
</div>
<p>We also have to keep in mind that when embedding documents, we will use an embedding model that has accepts a certain maximum sequence length <code>max_seq_length</code>.</p>
<p>So we should make sure that our chunk sizes are below this limit, because any longer chunk will be truncated before processing, thus losing relevancy.</p>
<div id="174a0a05" class="cell" data-execution_count="7">
<div class="sourceCode cell-code" id="cb5"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sentence_transformers <span class="im">import</span> SentenceTransformer</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="co"># To get the value of the max sequence_length, we will query the underlying `SentenceTransformer` object used in the RecursiveCharacterTextSplitter.</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(</span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a> <span class="ss">f"Model's maximum sequence length: </span><span class="sc">{</span>SentenceTransformer(<span class="st">'thenlper/gte-small'</span>)<span class="sc">.</span>max_seq_length<span class="sc">}</span><span class="ss">"</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> transformers <span class="im">import</span> AutoTokenizer</span>
<span id="cb5-9"><a href="#cb5-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-10"><a href="#cb5-10" aria-hidden="true" tabindex="-1"></a>tokenizer <span class="op">=</span> AutoTokenizer.from_pretrained(<span class="st">"thenlper/gte-small"</span>)</span>
<span id="cb5-11"><a href="#cb5-11" aria-hidden="true" tabindex="-1"></a>lengths <span class="op">=</span> [<span class="bu">len</span>(tokenizer.encode(doc.page_content)) <span class="cf">for</span> doc <span class="kw">in</span> tqdm(docs_processed)]</span>
<span id="cb5-12"><a href="#cb5-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb5-13"><a href="#cb5-13" aria-hidden="true" tabindex="-1"></a><span class="co"># Plot the distrubution of document lengths, counted as the number of tokens</span></span>
<span id="cb5-14"><a href="#cb5-14" aria-hidden="true" tabindex="-1"></a>fig <span class="op">=</span> pd.Series(lengths).hist()</span>
<span id="cb5-15"><a href="#cb5-15" aria-hidden="true" tabindex="-1"></a>plt.title(<span class="st">"Distribution of document lengths in the knowledge base (in count of tokens)"</span>)</span>
<span id="cb5-16"><a href="#cb5-16" aria-hidden="true" tabindex="-1"></a>plt.show()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>👀 As you can see, <strong>the chunk lengths are not aligned with our limit of 512 tokens</strong>, and some documents are above the limit, thus some part of them will be lost in truncation! - So we should change the <code>RecursiveCharacterTextSplitter</code> class to count length in number of tokens instead of number of characters. - Then we can choose a specific chunk size, here we would choose a lower threshold than 512: - smaller documents could allow the split to focus more on specific ideas. - But too small chunks would split sentences in half, thus losing meaning again: the proper tuning is a matter of balance.</p>
<div id="2fa8715e" class="cell" data-execution_count="8">
<div class="sourceCode cell-code" id="cb6"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> langchain.text_splitter <span class="im">import</span> RecursiveCharacterTextSplitter</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> transformers <span class="im">import</span> AutoTokenizer</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a>EMBEDDING_MODEL_NAME <span class="op">=</span> <span class="st">"thenlper/gte-small"</span></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> split_documents(</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a> chunk_size: <span class="bu">int</span>,</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a> knowledge_base: List[LangchainDocument],</span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a> tokenizer_name: Optional[<span class="bu">str</span>] <span class="op">=</span> EMBEDDING_MODEL_NAME,</span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a>) <span class="op">-></span> List[LangchainDocument]:</span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a> <span class="co">"""</span></span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a><span class="co"> Split documents into chunks of maximum size `chunk_size` tokens and return a list of documents.</span></span>
<span id="cb6-14"><a href="#cb6-14" aria-hidden="true" tabindex="-1"></a><span class="co"> """</span></span>
<span id="cb6-15"><a href="#cb6-15" aria-hidden="true" tabindex="-1"></a> text_splitter <span class="op">=</span> RecursiveCharacterTextSplitter.from_huggingface_tokenizer(</span>
<span id="cb6-16"><a href="#cb6-16" aria-hidden="true" tabindex="-1"></a> AutoTokenizer.from_pretrained(tokenizer_name),</span>
<span id="cb6-17"><a href="#cb6-17" aria-hidden="true" tabindex="-1"></a> chunk_size<span class="op">=</span>chunk_size,</span>
<span id="cb6-18"><a href="#cb6-18" aria-hidden="true" tabindex="-1"></a> chunk_overlap<span class="op">=</span><span class="bu">int</span>(chunk_size <span class="op">/</span> <span class="dv">10</span>),</span>
<span id="cb6-19"><a href="#cb6-19" aria-hidden="true" tabindex="-1"></a> add_start_index<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb6-20"><a href="#cb6-20" aria-hidden="true" tabindex="-1"></a> strip_whitespace<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb6-21"><a href="#cb6-21" aria-hidden="true" tabindex="-1"></a> separators<span class="op">=</span>MARKDOWN_SEPARATORS,</span>
<span id="cb6-22"><a href="#cb6-22" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb6-23"><a href="#cb6-23" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-24"><a href="#cb6-24" aria-hidden="true" tabindex="-1"></a> docs_processed <span class="op">=</span> []</span>
<span id="cb6-25"><a href="#cb6-25" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> doc <span class="kw">in</span> knowledge_base:</span>
<span id="cb6-26"><a href="#cb6-26" aria-hidden="true" tabindex="-1"></a> docs_processed <span class="op">+=</span> text_splitter.split_documents([doc])</span>
<span id="cb6-27"><a href="#cb6-27" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-28"><a href="#cb6-28" aria-hidden="true" tabindex="-1"></a> <span class="co"># Remove duplicates</span></span>
<span id="cb6-29"><a href="#cb6-29" aria-hidden="true" tabindex="-1"></a> unique_texts <span class="op">=</span> {}</span>
<span id="cb6-30"><a href="#cb6-30" aria-hidden="true" tabindex="-1"></a> docs_processed_unique <span class="op">=</span> []</span>
<span id="cb6-31"><a href="#cb6-31" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> doc <span class="kw">in</span> docs_processed:</span>
<span id="cb6-32"><a href="#cb6-32" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> doc.page_content <span class="kw">not</span> <span class="kw">in</span> unique_texts:</span>
<span id="cb6-33"><a href="#cb6-33" aria-hidden="true" tabindex="-1"></a> unique_texts[doc.page_content] <span class="op">=</span> <span class="va">True</span></span>
<span id="cb6-34"><a href="#cb6-34" aria-hidden="true" tabindex="-1"></a> docs_processed_unique.append(doc)</span>
<span id="cb6-35"><a href="#cb6-35" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-36"><a href="#cb6-36" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> docs_processed_unique</span>
<span id="cb6-37"><a href="#cb6-37" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-38"><a href="#cb6-38" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-39"><a href="#cb6-39" aria-hidden="true" tabindex="-1"></a>docs_processed <span class="op">=</span> split_documents(</span>
<span id="cb6-40"><a href="#cb6-40" aria-hidden="true" tabindex="-1"></a> <span class="dv">512</span>, <span class="co"># We choose a chunk size adapted to our model</span></span>
<span id="cb6-41"><a href="#cb6-41" aria-hidden="true" tabindex="-1"></a> RAW_KNOWLEDGE_BASE,</span>
<span id="cb6-42"><a href="#cb6-42" aria-hidden="true" tabindex="-1"></a> tokenizer_name<span class="op">=</span>EMBEDDING_MODEL_NAME,</span>
<span id="cb6-43"><a href="#cb6-43" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb6-44"><a href="#cb6-44" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-45"><a href="#cb6-45" aria-hidden="true" tabindex="-1"></a><span class="co"># Let's visualize the chunk sizes we would have in tokens from a common model</span></span>
<span id="cb6-46"><a href="#cb6-46" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> transformers <span class="im">import</span> AutoTokenizer</span>
<span id="cb6-47"><a href="#cb6-47" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-48"><a href="#cb6-48" aria-hidden="true" tabindex="-1"></a>tokenizer <span class="op">=</span> AutoTokenizer.from_pretrained(EMBEDDING_MODEL_NAME)</span>
<span id="cb6-49"><a href="#cb6-49" aria-hidden="true" tabindex="-1"></a>lengths <span class="op">=</span> [<span class="bu">len</span>(tokenizer.encode(doc.page_content)) <span class="cf">for</span> doc <span class="kw">in</span> tqdm(docs_processed)]</span>
<span id="cb6-50"><a href="#cb6-50" aria-hidden="true" tabindex="-1"></a>fig <span class="op">=</span> pd.Series(lengths).hist()</span>
<span id="cb6-51"><a href="#cb6-51" aria-hidden="true" tabindex="-1"></a>plt.title(<span class="st">"Distribution of document lengths in the knowledge base (in count of tokens)"</span>)</span>
<span id="cb6-52"><a href="#cb6-52" aria-hidden="true" tabindex="-1"></a>plt.show()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>➡️ Now the chunk length distribution looks better!</p>
</section>
<section id="building-the-vector-database" class="level3">
<h3 class="anchored" data-anchor-id="building-the-vector-database">1.2 Building the vector database</h3>
<p>We want to compute the embeddings for all the chunks of our knowledge base: to learn more on sentence embeddings, we recommend reading <a href="https://osanseviero.github.io/hackerllama/blog/posts/sentence_embeddings/">this guide</a>.</p>
<section id="how-does-retrieval-work" class="level4">
<h4 class="anchored" data-anchor-id="how-does-retrieval-work">How does retrieval work ?</h4>
<p>Once the chunks are all embedded, we store them into a vector database. When the user types in a query, it gets embedded by the same model previously used, and a similarity search returns the closest documents from the vector database.</p>
<p>The technical challenge is thus, given a query vector, to quickly find the nearest neighbours of this vector in the vector database. To do this, we need to choose two things: a distance, and a search algorithm to find the nearest neighbors quickly within a database of thousands of records.</p>
<section id="nearest-neighbor-search-algorithm" class="level5">
<h5 class="anchored" data-anchor-id="nearest-neighbor-search-algorithm">Nearest Neighbor search algorithm</h5>
<p>There are plentiful choices for the nearest neighbor search algorithm: we go with Facebook’s <a href="https://github.com/facebookresearch/faiss">FAISS</a>, since FAISS is performant enough for most use cases, and it is well known thus widely implemented.</p>
</section>
<section id="distances" class="level5">
<h5 class="anchored" data-anchor-id="distances">Distances</h5>
<p>Regarding distances, you can find a good guide <a href="https://osanseviero.github.io/hackerllama/blog/posts/sentence_embeddings/#distance-between-embeddings">here</a>. In short:</p>
<ul>
<li><strong>Cosine similarity</strong> computes similarity between two vectors as the cosinus of their relative angle: it allows us to compare vector directions are regardless of their magnitude. Using it requires to normalize all vectors, to rescale them into unit norm.</li>
<li><strong>Dot product</strong> takes into account magnitude, with the sometimes undesirable effect that increasing a vector’s length will make it more similar to all others.</li>
<li><strong>Euclidean distance</strong> is the distance between the ends of vectors.</li>
</ul>
<p>You can try <a href="https://developers.google.com/machine-learning/clustering/similarity/check-your-understanding">this small exercise</a> to check your understanding of these concepts. But once vectors are normalized, <a href="https://platform.openai.com/docs/guides/embeddings/which-distance-function-should-i-use">the choice of a specific distance does not matter much</a>.</p>
<p>Our particular model works well with cosine similarity, so choose this distance, and we set it up both in the Embedding model, and in the <code>distance_strategy</code> argument of our FAISS index. With cosine similarity, we have to normalize our embeddings.</p>
<div class="callout callout-style-default callout-warning callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Warning
</div>
</div>
<div class="callout-body-container callout-body">
<p>🚨👇 The cell below takes a few minutes to run on A10G!</p>
</div>
</div>
<div id="938830be" class="cell" data-execution_count="9">
<div class="sourceCode cell-code" id="cb7"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> langchain.vectorstores <span class="im">import</span> FAISS</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> langchain_community.embeddings <span class="im">import</span> HuggingFaceEmbeddings</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> langchain_community.vectorstores.utils <span class="im">import</span> DistanceStrategy</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a>embedding_model <span class="op">=</span> HuggingFaceEmbeddings(</span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a> model_name<span class="op">=</span>EMBEDDING_MODEL_NAME,</span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a> multi_process<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a> model_kwargs<span class="op">=</span>{<span class="st">"device"</span>: <span class="st">"cuda"</span>},</span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a> encode_kwargs<span class="op">=</span>{<span class="st">"normalize_embeddings"</span>: <span class="va">True</span>}, <span class="co"># set True for cosine similarity</span></span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a>KNOWLEDGE_VECTOR_DATABASE <span class="op">=</span> FAISS.from_documents(</span>
<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a> docs_processed, embedding_model, distance_strategy<span class="op">=</span>DistanceStrategy.COSINE</span>
<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>👀 To visualize the search for the closest documents, let’s project our embeddings from 384 dimensions down to 2 dimensions using PaCMAP.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>💡 We chose PaCMAP rather than other techniques such as t-SNE or UMAP, since <a href="https://www.nature.com/articles/s42003-022-03628-x#Abs1">it is efficient (preserves local and global structure), robust to initialization parameters and fast</a>.</p>
</div>
</div>
<div id="5ed5a830" class="cell" data-execution_count="10">
<div class="sourceCode cell-code" id="cb8"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="co"># embed a user query in the same space</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a>user_query <span class="op">=</span> <span class="st">"How to create a pipeline object?"</span></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>query_vector <span class="op">=</span> embedding_model.embed_query(user_query)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="206f15a0" class="cell" data-execution_count="11">
<div class="sourceCode cell-code" id="cb9"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> pacmap</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> numpy <span class="im">as</span> np</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> plotly.express <span class="im">as</span> px</span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>embedding_projector <span class="op">=</span> pacmap.PaCMAP(</span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a> n_components<span class="op">=</span><span class="dv">2</span>, n_neighbors<span class="op">=</span><span class="va">None</span>, MN_ratio<span class="op">=</span><span class="fl">0.5</span>, FP_ratio<span class="op">=</span><span class="fl">2.0</span>, random_state<span class="op">=</span><span class="dv">1</span></span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a>embeddings_2d <span class="op">=</span> [</span>
<span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a> <span class="bu">list</span>(KNOWLEDGE_VECTOR_DATABASE.index.reconstruct_n(idx, <span class="dv">1</span>)[<span class="dv">0</span>])</span>
<span id="cb9-11"><a href="#cb9-11" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> idx <span class="kw">in</span> <span class="bu">range</span>(<span class="bu">len</span>(docs_processed))</span>
<span id="cb9-12"><a href="#cb9-12" aria-hidden="true" tabindex="-1"></a>] <span class="op">+</span> [query_vector]</span>
<span id="cb9-13"><a href="#cb9-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-14"><a href="#cb9-14" aria-hidden="true" tabindex="-1"></a><span class="co"># fit the data (The index of transformed data corresponds to the index of the original data)</span></span>
<span id="cb9-15"><a href="#cb9-15" aria-hidden="true" tabindex="-1"></a>documents_projected <span class="op">=</span> embedding_projector.fit_transform(np.array(embeddings_2d), init<span class="op">=</span><span class="st">"pca"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="249c7a6b" class="cell" data-execution_count="12">
<div class="sourceCode cell-code" id="cb10"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>df <span class="op">=</span> pd.DataFrame.from_dict(</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a> [</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a> <span class="st">"x"</span>: documents_projected[i, <span class="dv">0</span>],</span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a> <span class="st">"y"</span>: documents_projected[i, <span class="dv">1</span>],</span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a> <span class="st">"source"</span>: docs_processed[i].metadata[<span class="st">"source"</span>].split(<span class="st">"/"</span>)[<span class="dv">1</span>],</span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a> <span class="st">"extract"</span>: docs_processed[i].page_content[:<span class="dv">100</span>] <span class="op">+</span> <span class="st">"..."</span>,</span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a> <span class="st">"symbol"</span>: <span class="st">"circle"</span>,</span>
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a> <span class="st">"size_col"</span>: <span class="dv">4</span>,</span>
<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span> i <span class="kw">in</span> <span class="bu">range</span>(<span class="bu">len</span>(docs_processed))</span>
<span id="cb10-12"><a href="#cb10-12" aria-hidden="true" tabindex="-1"></a> ]</span>
<span id="cb10-13"><a href="#cb10-13" aria-hidden="true" tabindex="-1"></a> <span class="op">+</span> [</span>
<span id="cb10-14"><a href="#cb10-14" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb10-15"><a href="#cb10-15" aria-hidden="true" tabindex="-1"></a> <span class="st">"x"</span>: documents_projected[<span class="op">-</span><span class="dv">1</span>, <span class="dv">0</span>],</span>
<span id="cb10-16"><a href="#cb10-16" aria-hidden="true" tabindex="-1"></a> <span class="st">"y"</span>: documents_projected[<span class="op">-</span><span class="dv">1</span>, <span class="dv">1</span>],</span>
<span id="cb10-17"><a href="#cb10-17" aria-hidden="true" tabindex="-1"></a> <span class="st">"source"</span>: <span class="st">"User query"</span>,</span>
<span id="cb10-18"><a href="#cb10-18" aria-hidden="true" tabindex="-1"></a> <span class="st">"extract"</span>: user_query,</span>
<span id="cb10-19"><a href="#cb10-19" aria-hidden="true" tabindex="-1"></a> <span class="st">"size_col"</span>: <span class="dv">100</span>,</span>
<span id="cb10-20"><a href="#cb10-20" aria-hidden="true" tabindex="-1"></a> <span class="st">"symbol"</span>: <span class="st">"star"</span>,</span>
<span id="cb10-21"><a href="#cb10-21" aria-hidden="true" tabindex="-1"></a> }</span>
<span id="cb10-22"><a href="#cb10-22" aria-hidden="true" tabindex="-1"></a> ]</span>
<span id="cb10-23"><a href="#cb10-23" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb10-24"><a href="#cb10-24" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-25"><a href="#cb10-25" aria-hidden="true" tabindex="-1"></a><span class="co"># visualize the embedding</span></span>
<span id="cb10-26"><a href="#cb10-26" aria-hidden="true" tabindex="-1"></a>fig <span class="op">=</span> px.scatter(</span>
<span id="cb10-27"><a href="#cb10-27" aria-hidden="true" tabindex="-1"></a> df,</span>
<span id="cb10-28"><a href="#cb10-28" aria-hidden="true" tabindex="-1"></a> x<span class="op">=</span><span class="st">"x"</span>,</span>
<span id="cb10-29"><a href="#cb10-29" aria-hidden="true" tabindex="-1"></a> y<span class="op">=</span><span class="st">"y"</span>,</span>
<span id="cb10-30"><a href="#cb10-30" aria-hidden="true" tabindex="-1"></a> color<span class="op">=</span><span class="st">"source"</span>,</span>
<span id="cb10-31"><a href="#cb10-31" aria-hidden="true" tabindex="-1"></a> hover_data<span class="op">=</span><span class="st">"extract"</span>,</span>
<span id="cb10-32"><a href="#cb10-32" aria-hidden="true" tabindex="-1"></a> size<span class="op">=</span><span class="st">"size_col"</span>,</span>
<span id="cb10-33"><a href="#cb10-33" aria-hidden="true" tabindex="-1"></a> symbol<span class="op">=</span><span class="st">"symbol"</span>,</span>
<span id="cb10-34"><a href="#cb10-34" aria-hidden="true" tabindex="-1"></a> color_discrete_map<span class="op">=</span>{<span class="st">"User query"</span>: <span class="st">"black"</span>},</span>
<span id="cb10-35"><a href="#cb10-35" aria-hidden="true" tabindex="-1"></a> width<span class="op">=</span><span class="dv">1000</span>,</span>
<span id="cb10-36"><a href="#cb10-36" aria-hidden="true" tabindex="-1"></a> height<span class="op">=</span><span class="dv">700</span>,</span>
<span id="cb10-37"><a href="#cb10-37" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb10-38"><a href="#cb10-38" aria-hidden="true" tabindex="-1"></a>fig.update_traces(</span>
<span id="cb10-39"><a href="#cb10-39" aria-hidden="true" tabindex="-1"></a> marker<span class="op">=</span><span class="bu">dict</span>(opacity<span class="op">=</span><span class="dv">1</span>, line<span class="op">=</span><span class="bu">dict</span>(width<span class="op">=</span><span class="dv">0</span>, color<span class="op">=</span><span class="st">"DarkSlateGrey"</span>)), selector<span class="op">=</span><span class="bu">dict</span>(mode<span class="op">=</span><span class="st">"markers"</span>)</span>
<span id="cb10-40"><a href="#cb10-40" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb10-41"><a href="#cb10-41" aria-hidden="true" tabindex="-1"></a>fig.update_layout(</span>
<span id="cb10-42"><a href="#cb10-42" aria-hidden="true" tabindex="-1"></a> legend_title_text<span class="op">=</span><span class="st">"<b>Chunk source</b>"</span>,</span>
<span id="cb10-43"><a href="#cb10-43" aria-hidden="true" tabindex="-1"></a> title<span class="op">=</span><span class="st">"<b>2D Projection of Chunk Embeddings via PaCMAP</b>"</span>,</span>
<span id="cb10-44"><a href="#cb10-44" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb10-45"><a href="#cb10-45" aria-hidden="true" tabindex="-1"></a>fig.show()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p><img src="https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/PaCMAP_embeddings.png" height="700"></p>
<p>➡️ On the graph above, you can see a spatial representation of the kowledge base documents. As the vector embeddings represent the document’s meaning, their closeness in meaning should be reflected in their embedding’s closeness.</p>
<p>The user query’s embedding is also shown : we want to find the <code>k</code> document that have the closest meaning, thus we pick the <code>k</code> closest vectors.</p>
<p>In the LangChain vector database implementation, this search operation is performed by the method <code>vector_database.similarity_search(query)</code>.</p>
<p>Here is the result:</p>
<div id="47319e72" class="cell" data-execution_count="13">
<div class="sourceCode cell-code" id="cb11"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"</span><span class="ch">\n</span><span class="ss">Starting retrieval for </span><span class="sc">{</span>user_query<span class="op">=</span><span class="sc">}</span><span class="ss">..."</span>)</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>retrieved_docs <span class="op">=</span> KNOWLEDGE_VECTOR_DATABASE.similarity_search(query<span class="op">=</span>user_query, k<span class="op">=</span><span class="dv">5</span>)</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">"</span><span class="ch">\n</span><span class="st">==================================Top document=================================="</span>)</span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(retrieved_docs[<span class="dv">0</span>].page_content)</span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">"==================================Metadata=================================="</span>)</span>
<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(retrieved_docs[<span class="dv">0</span>].metadata)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
</section>
</section>
</section>
<section id="reader---llm" class="level1">
<h1>2. Reader - LLM 💬</h1>
<p>In this part, the <strong>LLM Reader reads the retrieved context to formulate its answer.</strong></p>
<p>There are actually substeps that can all be tuned: 1. The content of the retrieved documents is aggregated together into the “context”, with many processing options like <em>prompt compression</em>. 2. The context and the user query are aggregated into a prompt then given to the LLM to generate its answer.</p>
<section id="reader-model" class="level3">
<h3 class="anchored" data-anchor-id="reader-model">2.1. Reader model</h3>
<p>The choice of a reader model is important on a few aspects: - the reader model’s <code>max_seq_length</code> must accomodate our prompt, which includes the context output by the retriever call: the context consists in 5 documents of 512 tokens each, so we aim for a context length of 4k tokens at least. - the reader model</p>
<p>For this example, we chose <a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-beta"><code>HuggingFaceH4/zephyr-7b-beta</code></a>, a small but powerful model.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>With many models being released every week, you may want to substitute this model to the latest and greatest. The best way to keep track of open source LLMs is to check the <a href="https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard">Open-source LLM leaderboard</a>.</p>
</div>
</div>
<p>To make inference faster, we will load the quantized version of the model:</p>
<div id="eaf2beef" class="cell" data-execution_count="14">
<div class="sourceCode cell-code" id="cb12"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> transformers <span class="im">import</span> pipeline</span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> torch</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> transformers <span class="im">import</span> AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a>READER_MODEL_NAME <span class="op">=</span> <span class="st">"HuggingFaceH4/zephyr-7b-beta"</span></span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>bnb_config <span class="op">=</span> BitsAndBytesConfig(</span>
<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a> load_in_4bit<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a> bnb_4bit_use_double_quant<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb12-10"><a href="#cb12-10" aria-hidden="true" tabindex="-1"></a> bnb_4bit_quant_type<span class="op">=</span><span class="st">"nf4"</span>,</span>
<span id="cb12-11"><a href="#cb12-11" aria-hidden="true" tabindex="-1"></a> bnb_4bit_compute_dtype<span class="op">=</span>torch.bfloat16,</span>
<span id="cb12-12"><a href="#cb12-12" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb12-13"><a href="#cb12-13" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> AutoModelForCausalLM.from_pretrained(READER_MODEL_NAME, quantization_config<span class="op">=</span>bnb_config)</span>
<span id="cb12-14"><a href="#cb12-14" aria-hidden="true" tabindex="-1"></a>tokenizer <span class="op">=</span> AutoTokenizer.from_pretrained(READER_MODEL_NAME)</span>
<span id="cb12-15"><a href="#cb12-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-16"><a href="#cb12-16" aria-hidden="true" tabindex="-1"></a>READER_LLM <span class="op">=</span> pipeline(</span>
<span id="cb12-17"><a href="#cb12-17" aria-hidden="true" tabindex="-1"></a> model<span class="op">=</span>model,</span>
<span id="cb12-18"><a href="#cb12-18" aria-hidden="true" tabindex="-1"></a> tokenizer<span class="op">=</span>tokenizer,</span>
<span id="cb12-19"><a href="#cb12-19" aria-hidden="true" tabindex="-1"></a> task<span class="op">=</span><span class="st">"text-generation"</span>,</span>
<span id="cb12-20"><a href="#cb12-20" aria-hidden="true" tabindex="-1"></a> do_sample<span class="op">=</span><span class="va">True</span>,</span>
<span id="cb12-21"><a href="#cb12-21" aria-hidden="true" tabindex="-1"></a> temperature<span class="op">=</span><span class="fl">0.2</span>,</span>
<span id="cb12-22"><a href="#cb12-22" aria-hidden="true" tabindex="-1"></a> repetition_penalty<span class="op">=</span><span class="fl">1.1</span>,</span>
<span id="cb12-23"><a href="#cb12-23" aria-hidden="true" tabindex="-1"></a> return_full_text<span class="op">=</span><span class="va">False</span>,</span>
<span id="cb12-24"><a href="#cb12-24" aria-hidden="true" tabindex="-1"></a> max_new_tokens<span class="op">=</span><span class="dv">500</span>,</span>
<span id="cb12-25"><a href="#cb12-25" aria-hidden="true" tabindex="-1"></a>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="f6f72fd3" class="cell" data-execution_count="15">
<div class="sourceCode cell-code" id="cb13"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>READER_LLM(<span class="st">"What is 4+4? Answer:"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="prompt" class="level3">
<h3 class="anchored" data-anchor-id="prompt">2.2. Prompt</h3>
<p>The RAG prompt template below is what we will feed to the Reader LLM: it is important to have it formatted in the Reader LLM’s chat template.</p>
<p>We give it our context and the user’s question.</p>
<div id="e28bd1d6" class="cell" data-execution_count="16">
<div class="sourceCode cell-code" id="cb14"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a>prompt_in_chat_format <span class="op">=</span> [</span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true" tabindex="-1"></a> <span class="st">"role"</span>: <span class="st">"system"</span>,</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true" tabindex="-1"></a> <span class="st">"content"</span>: <span class="st">"""Using the information contained in the context,</span></span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true" tabindex="-1"></a><span class="st">give a comprehensive answer to the question.</span></span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true" tabindex="-1"></a><span class="st">Respond only to the question asked, response should be concise and relevant to the question.</span></span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true" tabindex="-1"></a><span class="st">Provide the number of the source document when relevant.</span></span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true" tabindex="-1"></a><span class="st">If the answer cannot be deduced from the context, do not give an answer."""</span>,</span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true" tabindex="-1"></a> },</span>
<span id="cb14-10"><a href="#cb14-10" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb14-11"><a href="#cb14-11" aria-hidden="true" tabindex="-1"></a> <span class="st">"role"</span>: <span class="st">"user"</span>,</span>
<span id="cb14-12"><a href="#cb14-12" aria-hidden="true" tabindex="-1"></a> <span class="st">"content"</span>: <span class="st">"""Context:</span></span>
<span id="cb14-13"><a href="#cb14-13" aria-hidden="true" tabindex="-1"></a><span class="sc">{context}</span></span>
<span id="cb14-14"><a href="#cb14-14" aria-hidden="true" tabindex="-1"></a><span class="st">---</span></span>
<span id="cb14-15"><a href="#cb14-15" aria-hidden="true" tabindex="-1"></a><span class="st">Now here is the question you need to answer.</span></span>
<span id="cb14-16"><a href="#cb14-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb14-17"><a href="#cb14-17" aria-hidden="true" tabindex="-1"></a><span class="st">Question: </span><span class="sc">{question}</span><span class="st">"""</span>,</span>
<span id="cb14-18"><a href="#cb14-18" aria-hidden="true" tabindex="-1"></a> },</span>
<span id="cb14-19"><a href="#cb14-19" aria-hidden="true" tabindex="-1"></a>]</span>
<span id="cb14-20"><a href="#cb14-20" aria-hidden="true" tabindex="-1"></a>RAG_PROMPT_TEMPLATE <span class="op">=</span> tokenizer.apply_chat_template(</span>
<span id="cb14-21"><a href="#cb14-21" aria-hidden="true" tabindex="-1"></a> prompt_in_chat_format, tokenize<span class="op">=</span><span class="va">False</span>, add_generation_prompt<span class="op">=</span><span class="va">True</span></span>
<span id="cb14-22"><a href="#cb14-22" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb14-23"><a href="#cb14-23" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(RAG_PROMPT_TEMPLATE)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Let’s test our Reader on our previously retrieved documents!</p>
<div id="96c062d3" class="cell" data-execution_count="17">
<div class="sourceCode cell-code" id="cb15"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a>retrieved_docs_text <span class="op">=</span> [</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a> doc.page_content <span class="cf">for</span> doc <span class="kw">in</span> retrieved_docs</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>] <span class="co"># we only need the text of the documents</span></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>context <span class="op">=</span> <span class="st">"</span><span class="ch">\n</span><span class="st">Extracted documents:</span><span class="ch">\n</span><span class="st">"</span></span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a>context <span class="op">+=</span> <span class="st">""</span>.join([<span class="ss">f"Document </span><span class="sc">{</span><span class="bu">str</span>(i)<span class="sc">}</span><span class="ss">:::</span><span class="ch">\n</span><span class="ss">"</span> <span class="op">+</span> doc <span class="cf">for</span> i, doc <span class="kw">in</span> <span class="bu">enumerate</span>(retrieved_docs_text)])</span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a>final_prompt <span class="op">=</span> RAG_PROMPT_TEMPLATE.<span class="bu">format</span>(</span>
<span id="cb15-8"><a href="#cb15-8" aria-hidden="true" tabindex="-1"></a> question<span class="op">=</span><span class="st">"How to create a pipeline object?"</span>, context<span class="op">=</span>context</span>
<span id="cb15-9"><a href="#cb15-9" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb15-10"><a href="#cb15-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-11"><a href="#cb15-11" aria-hidden="true" tabindex="-1"></a><span class="co"># Redact an answer</span></span>
<span id="cb15-12"><a href="#cb15-12" aria-hidden="true" tabindex="-1"></a>answer <span class="op">=</span> READER_LLM(final_prompt)[<span class="dv">0</span>][<span class="st">"generated_text"</span>]</span>
<span id="cb15-13"><a href="#cb15-13" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(answer)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="reranking" class="level3">
<h3 class="anchored" data-anchor-id="reranking">2.3. Reranking</h3>
<p>A good option for RAG is to retrieve more documents than you want in the end, then rerank the results with a more powerful retrieval model before keeping only the <code>top_k</code>.</p>
<p>For this, <a href="https://arxiv.org/abs/2112.01488">Colbertv2</a> is a great choice: instead of a bi-encoder like our classical embedding models, it is a cross-encoder that computes more fine-grained interactions between the query tokens and each document’s tokens.</p>
<p>It is easily usable thanks to <a href="https://github.com/bclavie/RAGatouille">the RAGatouille library</a>.</p>
<div id="c0298337" class="cell" data-execution_count="18">
<div class="sourceCode cell-code" id="cb16"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> ragatouille <span class="im">import</span> RAGPretrainedModel</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>RERANKER <span class="op">=</span> RAGPretrainedModel.from_pretrained(<span class="st">"colbert-ir/colbertv2.0"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
</section>
<section id="assembling-it-all" class="level1">
<h1>3. Assembling it all!</h1>
<div id="f7d2b29a" class="cell" data-execution_count="19">
<div class="sourceCode cell-code" id="cb17"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> transformers <span class="im">import</span> Pipeline</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> answer_with_rag(</span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true" tabindex="-1"></a> question: <span class="bu">str</span>,</span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true" tabindex="-1"></a> llm: Pipeline,</span>
<span id="cb17-7"><a href="#cb17-7" aria-hidden="true" tabindex="-1"></a> knowledge_index: FAISS,</span>
<span id="cb17-8"><a href="#cb17-8" aria-hidden="true" tabindex="-1"></a> reranker: Optional[RAGPretrainedModel] <span class="op">=</span> <span class="va">None</span>,</span>
<span id="cb17-9"><a href="#cb17-9" aria-hidden="true" tabindex="-1"></a> num_retrieved_docs: <span class="bu">int</span> <span class="op">=</span> <span class="dv">30</span>,</span>
<span id="cb17-10"><a href="#cb17-10" aria-hidden="true" tabindex="-1"></a> num_docs_final: <span class="bu">int</span> <span class="op">=</span> <span class="dv">5</span>,</span>
<span id="cb17-11"><a href="#cb17-11" aria-hidden="true" tabindex="-1"></a>) <span class="op">-></span> Tuple[<span class="bu">str</span>, List[LangchainDocument]]:</span>
<span id="cb17-12"><a href="#cb17-12" aria-hidden="true" tabindex="-1"></a> <span class="co"># Gather documents with retriever</span></span>
<span id="cb17-13"><a href="#cb17-13" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">"=> Retrieving documents..."</span>)</span>
<span id="cb17-14"><a href="#cb17-14" aria-hidden="true" tabindex="-1"></a> relevant_docs <span class="op">=</span> knowledge_index.similarity_search(query<span class="op">=</span>question, k<span class="op">=</span>num_retrieved_docs)</span>
<span id="cb17-15"><a href="#cb17-15" aria-hidden="true" tabindex="-1"></a> relevant_docs <span class="op">=</span> [doc.page_content <span class="cf">for</span> doc <span class="kw">in</span> relevant_docs] <span class="co"># keep only the text</span></span>
<span id="cb17-16"><a href="#cb17-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-17"><a href="#cb17-17" aria-hidden="true" tabindex="-1"></a> <span class="co"># Optionally rerank results</span></span>
<span id="cb17-18"><a href="#cb17-18" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> reranker:</span>
<span id="cb17-19"><a href="#cb17-19" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">"=> Reranking documents..."</span>)</span>
<span id="cb17-20"><a href="#cb17-20" aria-hidden="true" tabindex="-1"></a> relevant_docs <span class="op">=</span> reranker.rerank(question, relevant_docs, k<span class="op">=</span>num_docs_final)</span>
<span id="cb17-21"><a href="#cb17-21" aria-hidden="true" tabindex="-1"></a> relevant_docs <span class="op">=</span> [doc[<span class="st">"content"</span>] <span class="cf">for</span> doc <span class="kw">in</span> relevant_docs]</span>
<span id="cb17-22"><a href="#cb17-22" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-23"><a href="#cb17-23" aria-hidden="true" tabindex="-1"></a> relevant_docs <span class="op">=</span> relevant_docs[:num_docs_final]</span>
<span id="cb17-24"><a href="#cb17-24" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-25"><a href="#cb17-25" aria-hidden="true" tabindex="-1"></a> <span class="co"># Build the final prompt</span></span>
<span id="cb17-26"><a href="#cb17-26" aria-hidden="true" tabindex="-1"></a> context <span class="op">=</span> <span class="st">"</span><span class="ch">\n</span><span class="st">Extracted documents:</span><span class="ch">\n</span><span class="st">"</span></span>
<span id="cb17-27"><a href="#cb17-27" aria-hidden="true" tabindex="-1"></a> context <span class="op">+=</span> <span class="st">""</span>.join([<span class="ss">f"Document </span><span class="sc">{</span><span class="bu">str</span>(i)<span class="sc">}</span><span class="ss">:::</span><span class="ch">\n</span><span class="ss">"</span> <span class="op">+</span> doc <span class="cf">for</span> i, doc <span class="kw">in</span> <span class="bu">enumerate</span>(relevant_docs)])</span>
<span id="cb17-28"><a href="#cb17-28" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-29"><a href="#cb17-29" aria-hidden="true" tabindex="-1"></a> final_prompt <span class="op">=</span> RAG_PROMPT_TEMPLATE.<span class="bu">format</span>(question<span class="op">=</span>question, context<span class="op">=</span>context)</span>
<span id="cb17-30"><a href="#cb17-30" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-31"><a href="#cb17-31" aria-hidden="true" tabindex="-1"></a> <span class="co"># Redact an answer</span></span>
<span id="cb17-32"><a href="#cb17-32" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">"=> Generating answer..."</span>)</span>
<span id="cb17-33"><a href="#cb17-33" aria-hidden="true" tabindex="-1"></a> answer <span class="op">=</span> llm(final_prompt)[<span class="dv">0</span>][<span class="st">"generated_text"</span>]</span>
<span id="cb17-34"><a href="#cb17-34" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb17-35"><a href="#cb17-35" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> answer, relevant_docs</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Let’s see how our RAG pipeline answers a user query.</p>
<div id="06ccd294" class="cell" data-execution_count="20">
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>question <span class="op">=</span> <span class="st">"how to create a pipeline object?"</span></span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>answer, relevant_docs <span class="op">=</span> answer_with_rag(</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a> question, READER_LLM, KNOWLEDGE_VECTOR_DATABASE, reranker<span class="op">=</span>RERANKER</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="f6ece0d2" class="cell" data-execution_count="21">
<div class="sourceCode cell-code" id="cb19"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">"==================================Answer=================================="</span>)</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"</span><span class="sc">{</span>answer<span class="sc">}</span><span class="ss">"</span>)</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">"==================================Source docs=================================="</span>)</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> i, doc <span class="kw">in</span> <span class="bu">enumerate</span>(relevant_docs):</span>
<span id="cb19-5"><a href="#cb19-5" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f"Document </span><span class="sc">{</span>i<span class="sc">}</span><span class="ss">------------------------------------------------------------"</span>)</span>
<span id="cb19-6"><a href="#cb19-6" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(doc)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>✅ We now have a fully functional, performant RAG sytem. That’s it for today! Congratulations for making it to the end 🥳</p>
</section>
<section id="to-go-further" class="level1">
<h1>To go further 🗺️</h1>
<p>This is not the end of the journey! You can try many steps to improve your RAG system. We recommend doing so in an iterative way: bring small changes to the system and see what improves performance.</p>
<section id="setting-up-an-evaluation-pipeline" class="level3">
<h3 class="anchored" data-anchor-id="setting-up-an-evaluation-pipeline">Setting up an evaluation pipeline</h3>
<ul>
<li>💬 “You cannot improve the model performance that you do not measure”, said Gandhi… or at least Llama2 told me he said it. Anyway, you should absolutely start by measuring performance: this means building a small evaluation dataset, then monitor the performance of your RAG system on this evaluation dataset.</li>
</ul>
</section>
<section id="improving-the-retriever" class="level3">
<h3 class="anchored" data-anchor-id="improving-the-retriever">Improving the retriever</h3>
<p>🛠️ <strong>You can use these options to tune the results:</strong></p>
<ul>
<li>Tune the chunking method:
<ul>
<li>Size of the chunks</li>
<li>Method: split on different separators, use <a href="https://python.langchain.com/docs/modules/data_connection/document_transformers/semantic-chunker">semantic chunking</a>…</li>
</ul></li>
<li>Change the embedding model</li>
</ul>
<p>👷♀️ <strong>More could be considered:</strong> - Try another chunking method, like semantic chunking - Change the index used (here, FAISS) - Query expansion: reformulate the user query in slightly different ways to retrieve more documents.</p>
</section>
<section id="improving-the-reader" class="level3">
<h3 class="anchored" data-anchor-id="improving-the-reader">Improving the reader</h3>
<p>🛠️ <strong>Here you can try the following options to improve results:</strong> - Tune the prompt - Switch reranking on/off - Choose a more powerful reader model</p>
<p>💡 <strong>Many options could be considered here to further improve the results:</strong> - Compress the retrieved context to keep only the most relevant parts to answer the query. - Extend the RAG system to make it more user-friendly: - cite source - make conversational</p>
</section>
</section>
</main> <!-- /main -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
const annoteTargets = window.document.querySelectorAll('.code-annotation-anchor');
for (let i=0; i<annoteTargets.length; i++) {
const annoteTarget = annoteTargets[i];
const targetCell = annoteTarget.getAttribute("data-target-cell");
const targetAnnotation = annoteTarget.getAttribute("data-target-annotation");
const contentFn = () => {
const content = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
if (content) {
const tipContent = content.cloneNode(true);
tipContent.classList.add("code-annotation-tip-content");
return tipContent.outerHTML;
}
}
const config = {
allowHTML: true,
content: contentFn,
onShow: (instance) => {
selectCodeLines(instance.reference);
instance.reference.classList.add('code-annotation-active');
window.tippy.hideAll();
},
onHide: (instance) => {
unselectCodeLines();
instance.reference.classList.remove('code-annotation-active');
},
maxWidth: 300,
delay: [50, 0],
duration: [200, 0],
offset: [5, 10],
arrow: true,
appendTo: function(el) {
return el.parentElement.parentElement.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'right',
popperOptions: {
modifiers: [
{
name: 'flip',
options: {
flipVariations: false, // true by default
allowedAutoPlacements: ['right'],
fallbackPlacements: ['right', 'top', 'top-start', 'top-end', 'bottom', 'bottom-start', 'bottom-end', 'left'],
},
},
{
name: 'preventOverflow',
options: {
mainAxis: false,
altAxis: false
}
}
]
}
};
window.tippy(annoteTarget, config);
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
</div> <!-- /content -->
</body></html> |