File size: 44,750 Bytes
d73d493 |
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 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Your First RAQA Application\n",
"\n",
"In this notebook, we'll walk you through each of the components that are involved in a simple RAQA application. \n",
"\n",
"We won't be leveraging any fancy tools, just the OpenAI Python SDK, Numpy, and some classic Python.\n",
"\n",
"> NOTE: This was done with Python 3.11.4."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's look at a rather complicated looking visual representation of a basic RAQA application.\n",
"\n",
"<img src=\"https://i.imgur.com/LCNkd1A.png\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Imports and Utility \n",
"\n",
"We're just doing some imports and enabling `async` to work within the Jupyter environment here, nothing too crazy!"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"!pip install -q -U numpy matplotlib plotly pandas scipy scikit-learn python-dotenv chainlit==0.7.700 cohere==4.37 openai==1.3.5 tiktoken==0.5.1"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter\n",
"from aimakerspace.vectordatabase import VectorDatabase\n",
"import asyncio"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import nest_asyncio\n",
"nest_asyncio.apply()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Documents\n",
"\n",
"We'll be concerning ourselves with this part of the flow in the following section:\n",
"\n",
"<img src=\"https://i.imgur.com/wBYB2x3.png\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Loading Source Documents\n",
"\n",
"So, first things first, we need some documents to work with. \n",
"\n",
"While we could work directly with the `.txt` files (or whatever file-types you wanted to extend this to) we can instead do some batch processing of those documents at the beginning in order to store them in a more machine compatible format. \n",
"\n",
"In this case, we're going to parse our text file into a single document in memory.\n",
"\n",
"Let's look at the relevant bits of the `TextFileLoader` class:\n",
"\n",
"```python\n",
"def load_file(self):\n",
" with open(self.path, \"r\", encoding=self.encoding) as f:\n",
" self.documents.append(f.read())\n",
"```\n",
"\n",
"We're simply loading the document using the built in `open` method, and storing that output in our `self.documents` list.\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text_loader = TextFileLoader(\"data/KingLear.txt\")\n",
"documents = text_loader.load_documents()\n",
"len(documents)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ACT I\n",
"SCENE I. King Lear's palace.\n",
"Enter KENT, GLOUCESTER, and EDMUND\n",
"KENT\n",
"I thought the king had more affected the Duke of\n",
"Albany than Cornwall.\n",
"GLOUCESTER\n",
"It did always seem so to us: but now, in the\n",
"division of the kingdom, it appears not which of\n",
"the dukes he values most; for equalities are so\n",
"weighed, that curiosity in neither can make choice\n",
"of either's moiety.\n",
"KENT\n",
"Is not this your son, my lord?\n",
"GLOUCESTER\n",
"His breeding, sir, hath been at my charge: I have\n",
"so often blushed to acknowledge him, that now I am\n",
"brazed to it.\n",
"KENT\n",
"I cannot conceive you.\n",
"GLOUCESTER\n",
"Sir, this young fellow's mot\n"
]
}
],
"source": [
"print(documents[0][:600])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Splitting Text Into Chunks\n",
"\n",
"As we can see, there is one document - and it's the entire text of King Lear.\n",
"\n",
"We'll want to chunk the document into smaller parts so it's easier to pass the most relevant snippets to the LLM. \n",
"\n",
"There is no fixed way to split/chunk documents - and you'll need to rely on some intuition as well as knowing your data *very* well in order to build the most robust system.\n",
"\n",
"For this toy example, we'll just split blindly on length. \n",
"\n",
">There's an opportunity to clear up some terminology here, for this course we will be stick to the following: \n",
">\n",
">- \"source documents\" : The `.txt`, `.pdf`, `.html`, ..., files that make up the files and information we start with in its raw format\n",
">- \"document(s)\" : single (or more) text object(s)\n",
">- \"corpus\" : the combination of all of our documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's take a peek visually at what we're doing here - and why it might be useful:\n",
"\n",
"<img src=\"https://i.imgur.com/rtM6Ci6.png\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see (though it's not specifically true in this toy example) the idea of splitting documents is to break them into managable sized chunks that retain the most relevant local context."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'documents' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32mc:\\ai\\llmops3\\repos\\vsrepo\\my-first-raqa\\Python RAQA Example.ipynb Cell 14\u001b[0m line \u001b[0;36m2\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/ai/llmops3/repos/vsrepo/my-first-raqa/Python%20RAQA%20Example.ipynb#X16sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m text_splitter \u001b[39m=\u001b[39m CharacterTextSplitter()\n\u001b[1;32m----> <a href='vscode-notebook-cell:/c%3A/ai/llmops3/repos/vsrepo/my-first-raqa/Python%20RAQA%20Example.ipynb#X16sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m split_documents \u001b[39m=\u001b[39m text_splitter\u001b[39m.\u001b[39msplit_texts(documents)\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/ai/llmops3/repos/vsrepo/my-first-raqa/Python%20RAQA%20Example.ipynb#X16sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mlen\u001b[39m(split_documents)\n",
"\u001b[1;31mNameError\u001b[0m: name 'documents' is not defined"
]
}
],
"source": [
"text_splitter = CharacterTextSplitter()\n",
"split_documents = text_splitter.split_texts(documents)\n",
"len(split_documents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's take a look at some of the documents we've managed to split."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[\"\\ufeffACT I\\nSCENE I. King Lear's palace.\\nEnter KENT, GLOUCESTER, and EDMUND\\nKENT\\nI thought the king had more affected the Duke of\\nAlbany than Cornwall.\\nGLOUCESTER\\nIt did always seem so to us: but now, in the\\ndivision of the kingdom, it appears not which of\\nthe dukes he values most; for equalities are so\\nweighed, that curiosity in neither can make choice\\nof either's moiety.\\nKENT\\nIs not this your son, my lord?\\nGLOUCESTER\\nHis breeding, sir, hath been at my charge: I have\\nso often blushed to acknowledge him, that now I am\\nbrazed to it.\\nKENT\\nI cannot conceive you.\\nGLOUCESTER\\nSir, this young fellow's mother could: whereupon\\nshe grew round-wombed, and had, indeed, sir, a son\\nfor her cradle ere she had a husband for her bed.\\nDo you smell a fault?\\nKENT\\nI cannot wish the fault undone, the issue of it\\nbeing so proper.\\nGLOUCESTER\\nBut I have, sir, a son by order of law, some year\\nelder than this, who yet is no dearer in my account:\\nthough this knave came something saucily into the\\nworld before he was se\"]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"split_documents[0:1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Embeddings and Vectors\n",
"\n",
"Next, we have to convert our corpus into a \"machine readable\" format. \n",
"\n",
"Loosely, this means turning the text into numbers. \n",
"\n",
"There are plenty of resources that talk about this process in great detail - I'll leave this [blog](https://txt.cohere.com/sentence-word-embeddings/) from Cohere:AI as a resource if you want to deep dive a bit. \n",
"\n",
"Today, we're going to talk about the actual process of creating, and then storing, these embeddings, and how we can leverage that to intelligently add context to our queries."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While this is all baked into 1 call - let's look at some of the code that powers this process:\n",
"\n",
"Let's look at our `VectorDatabase().__init__()`:\n",
"\n",
"```python\n",
"def __init__(self, embedding_model: EmbeddingModel = None):\n",
" self.vectors = defaultdict(np.array)\n",
" self.embedding_model = embedding_model or EmbeddingModel()\n",
"```\n",
"\n",
"As you can see - our vectors are merely stored as a dictionary of `np.array` objects.\n",
"\n",
"Secondly, our `VectorDatabase()` has a default `EmbeddingModel()` which is a wrapper for OpenAI's `text-embedding-ada-002` model. \n",
"\n",
"> **Quick Info About `text-embedding-ada-002`**:\n",
"> - It has a context window of **8192** tokens\n",
"> - It returns vectors with dimension **1536**"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import openai\n",
"from getpass import getpass\n",
"\n",
"openai.api_key = getpass(\"OpenAI API Key: \")\n",
"os.environ[\"OPENAI_API_KEY\"] = openai.api_key"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the `async_get_embeddings` method of our `EmbeddingModel()` on a list of `str` and receive a list of `float` back!\n",
"\n",
"```python\n",
"async def async_get_embeddings(self, list_of_text: List[str]) -> List[List[float]]:\n",
" return await aget_embeddings(\n",
" list_of_text=list_of_text, engine=self.embeddings_model_name\n",
" )\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We cast those to `np.array` when we build our `VectorDatabase()`:\n",
"\n",
"```python\n",
"async def abuild_from_list(self, list_of_text: List[str]) -> \"VectorDatabase\":\n",
" embeddings = await self.embedding_model.async_get_embeddings(list_of_text)\n",
" for text, embedding in zip(list_of_text, embeddings):\n",
" self.insert(text, np.array(embedding))\n",
" return self\n",
"```\n",
"\n",
"And that's all we need to do!"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"vector_db = VectorDatabase()\n",
"vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, to review what we've done so far in natural language:\n",
"\n",
"1. We load source documents\n",
"2. We split those source documents into smaller chunks (documents)\n",
"3. We send each of those documents to the `text-embedding-ada-002` OpenAI API endpoint\n",
"4. We store each of the text representations with the vector representations as keys/values in a dictionary"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Semantic Similarity\n",
"\n",
"The next step is to be able to query our `VectorDatabase()` with a `str` and have it return to us vectors and text that is most relevant from our corpus. \n",
"\n",
"We're going to use the following process to achieve this in our toy example:\n",
"\n",
"1. We need to embed our query with the same `EmbeddingModel()` as we used to construct our `VectorDatabase()`\n",
"2. We loop through every vector in our `VectorDatabase()` and use a distance measure to compare how related they are\n",
"3. We return a list of the top `k` closest vectors, with their text representations\n",
"\n",
"There's some very heavy optimization that can be done at each of these steps - but let's just focus on the basic pattern in this notebook.\n",
"\n",
"> We are using [cosine similarity](https://www.engati.com/glossary/cosine-similarity) as a distance measure in this example - but there are many many distance measures you could use - like [these](https://flavien-vidal.medium.com/similarity-distances-for-natural-language-processing-16f63cd5ba55)\n",
"\n",
"> We are using a rather inefficient way of calculating relative distance between the query vector and all other vectors - there are more advanced approaches that are much more efficient, like [ANN](https://towardsdatascience.com/comprehensive-guide-to-approximate-nearest-neighbors-algorithms-8b94f057d6b6)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(\"ng] O my good master!\\nKING LEAR\\nPrithee, away.\\nEDGAR\\n'Tis noble Kent, your friend.\\nKING LEAR\\nA plague upon you, murderers, traitors all!\\nI might have saved her; now she's gone for ever!\\nCordelia, Cordelia! stay a little. Ha!\\nWhat is't thou say'st? Her voice was ever soft,\\nGentle, and low, an excellent thing in woman.\\nI kill'd the slave that was a-hanging thee.\\nCaptain\\n'Tis true, my lords, he did.\\nKING LEAR\\nDid I not, fellow?\\nI have seen the day, with my good biting falchion\\nI would have made them skip: I am old now,\\nAnd these same crosses spoil me. Who are you?\\nMine eyes are not o' the best: I'll tell you straight.\\nKENT\\nIf fortune brag of two she loved and hated,\\nOne of them we behold.\\nKING LEAR\\nThis is a dull sight. Are you not Kent?\\nKENT\\nThe same,\\nYour servant Kent: Where is your servant Caius?\\nKING LEAR\\nHe's a good fellow, I can tell you that;\\nHe'll strike, and quickly too: he's dead and rotten.\\nKENT\\nNo, my good lord; I am the very man,--\\nKING LEAR\\nI'll see that straight.\\nKENT\\nThat,\",\n",
" 0.8344666931475856),\n",
" (\",\\nLay comforts to your bosom; and bestow\\nYour needful counsel to our business,\\nWhich craves the instant use.\\nGLOUCESTER\\nI serve you, madam:\\nYour graces are right welcome.\\nExeunt\\n\\nSCENE II. Before Gloucester's castle.\\nEnter KENT and OSWALD, severally\\nOSWALD\\nGood dawning to thee, friend: art of this house?\\nKENT\\nAy.\\nOSWALD\\nWhere may we set our horses?\\nKENT\\nI' the mire.\\nOSWALD\\nPrithee, if thou lovest me, tell me.\\nKENT\\nI love thee not.\\nOSWALD\\nWhy, then, I care not for thee.\\nKENT\\nIf I had thee in Lipsbury pinfold, I would make thee\\ncare for me.\\nOSWALD\\nWhy dost thou use me thus? I know thee not.\\nKENT\\nFellow, I know thee.\\nOSWALD\\nWhat dost thou know me for?\\nKENT\\nA knave; a rascal; an eater of broken meats; a\\nbase, proud, shallow, beggarly, three-suited,\\nhundred-pound, filthy, worsted-stocking knave; a\\nlily-livered, action-taking knave, a whoreson,\\nglass-gazing, super-serviceable finical rogue;\\none-trunk-inheriting slave; one that wouldst be a\\nbawd, in way of good service, and art nothing but\\nth\",\n",
" 0.8218615790372598),\n",
" (\" Caius?\\nKING LEAR\\nHe's a good fellow, I can tell you that;\\nHe'll strike, and quickly too: he's dead and rotten.\\nKENT\\nNo, my good lord; I am the very man,--\\nKING LEAR\\nI'll see that straight.\\nKENT\\nThat, from your first of difference and decay,\\nHave follow'd your sad steps.\\nKING LEAR\\nYou are welcome hither.\\nKENT\\nNor no man else: all's cheerless, dark, and deadly.\\nYour eldest daughters have fordone them selves,\\nAnd desperately are dead.\\nKING LEAR\\nAy, so I think.\\nALBANY\\nHe knows not what he says: and vain it is\\nThat we present us to him.\\nEDGAR\\nVery bootless.\\nEnter a Captain\\n\\nCaptain\\nEdmund is dead, my lord.\\nALBANY\\nThat's but a trifle here.\\nYou lords and noble friends, know our intent.\\nWhat comfort to this great decay may come\\nShall be applied: for us we will resign,\\nDuring the life of this old majesty,\\nTo him our absolute power:\\nTo EDGAR and KENT\\n\\nyou, to your rights:\\nWith boot, and such addition as your honours\\nHave more than merited. All friends shall taste\\nThe wages of their virtue, and \",\n",
" 0.8212563905734079)]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vector_db.search_by_text(\"Your servant Kent. Where is your servant Caius?\", k=3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Prompts\n",
"\n",
"In the following section, we'll be looking at the role of prompts - and how they help us to guide our application in the right direction.\n",
"\n",
"In this notebook, we're going to rely on the idea of \"zero-shot in-context learning\".\n",
"\n",
"This is a lot of words to say: \"We will ask it to perform our desired task in the prompt, and provide no examples.\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### XYZRolePrompt\n",
"\n",
"Before we do that, let's stop and think a bit about how OpenAI's chat models work. \n",
"\n",
"We know they have roles - as is indicated in the following API [documentation](https://platform.openai.com/docs/api-reference/chat/create#chat/create-messages)\n",
"\n",
"There are three roles, and they function as follows (taken directly from [OpenAI](https://platform.openai.com/docs/guides/gpt/chat-completions-api)): \n",
"\n",
"- `{\"role\" : \"system\"}` : The system message helps set the behavior of the assistant. For example, you can modify the personality of the assistant or provide specific instructions about how it should behave throughout the conversation. However note that the system message is optional and the model’s behavior without a system message is likely to be similar to using a generic message such as \"You are a helpful assistant.\"\n",
"- `{\"role\" : \"user\"}` : The user messages provide requests or comments for the assistant to respond to.\n",
"- `{\"role\" : \"assistant\"}` : Assistant messages store previous assistant responses, but can also be written by you to give examples of desired behavior.\n",
"\n",
"The main idea is this: \n",
"\n",
"1. You start with a system message that outlines how the LLM should respond, what kind of behaviours you can expect from it, and more\n",
"2. Then, you can provide a few examples in the form of \"assistant\"/\"user\" pairs\n",
"3. Then, you prompt the model with the true \"user\" message.\n",
"\n",
"In this example, we'll be forgoing the 2nd step for simplicities sake."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Utility Functions\n",
"\n",
"You'll notice that we're using some utility functions from the `aimakerspace` module - let's take a peek at these and see what they're doing!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### XYZRolePrompt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we have our `system`, `user`, and `assistant` role prompts. \n",
"\n",
"Let's take a peek at what they look like:\n",
"\n",
"```python\n",
"class BasePrompt:\n",
" def __init__(self, prompt):\n",
" \"\"\"\n",
" Initializes the BasePrompt object with a prompt template.\n",
"\n",
" :param prompt: A string that can contain placeholders within curly braces\n",
" \"\"\"\n",
" self.prompt = prompt\n",
" self._pattern = re.compile(r\"\\{([^}]+)\\}\")\n",
"\n",
" def format_prompt(self, **kwargs):\n",
" \"\"\"\n",
" Formats the prompt string using the keyword arguments provided.\n",
"\n",
" :param kwargs: The values to substitute into the prompt string\n",
" :return: The formatted prompt string\n",
" \"\"\"\n",
" matches = self._pattern.findall(self.prompt)\n",
" return self.prompt.format(**{match: kwargs.get(match, \"\") for match in matches})\n",
"\n",
" def get_input_variables(self):\n",
" \"\"\"\n",
" Gets the list of input variable names from the prompt string.\n",
"\n",
" :return: List of input variable names\n",
" \"\"\"\n",
" return self._pattern.findall(self.prompt)\n",
"```\n",
"\n",
"Then we have our `RolePrompt` which laser focuses us on the role pattern found in most API endpoints for LLMs.\n",
"\n",
"```python\n",
"class RolePrompt(BasePrompt):\n",
" def __init__(self, prompt, role: str):\n",
" \"\"\"\n",
" Initializes the RolePrompt object with a prompt template and a role.\n",
"\n",
" :param prompt: A string that can contain placeholders within curly braces\n",
" :param role: The role for the message ('system', 'user', or 'assistant')\n",
" \"\"\"\n",
" super().__init__(prompt)\n",
" self.role = role\n",
"\n",
" def create_message(self, **kwargs):\n",
" \"\"\"\n",
" Creates a message dictionary with a role and a formatted message.\n",
"\n",
" :param kwargs: The values to substitute into the prompt string\n",
" :return: Dictionary containing the role and the formatted message\n",
" \"\"\"\n",
" return {\"role\": self.role, \"content\": self.format_prompt(**kwargs)}\n",
"```\n",
"\n",
"We'll look at how the `SystemRolePrompt` is constructed to get a better idea of how that extension works:\n",
"\n",
"```python\n",
"class SystemRolePrompt(RolePrompt):\n",
" def __init__(self, prompt: str):\n",
" super().__init__(prompt, \"system\")\n",
"```\n",
"\n",
"That pattern is repeated for our `UserRolePrompt` and our `AssistantRolePrompt` as well."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### ChatOpenAI"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we have our model, which is converted to a format analagous to libraries like LangChain and LlamaIndex.\n",
"\n",
"Let's take a peek at how that is constructed:\n",
"\n",
"```python\n",
"class ChatOpenAI:\n",
" def __init__(self, model_name: str = \"gpt-3.5-turbo\"):\n",
" self.model_name = model_name\n",
" self.openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n",
" if self.openai_api_key is None:\n",
" raise ValueError(\"OPENAI_API_KEY is not set\")\n",
"\n",
" def run(self, messages, text_only: bool = True):\n",
" if not isinstance(messages, list):\n",
" raise ValueError(\"messages must be a list\")\n",
"\n",
" openai.api_key = self.openai_api_key\n",
" response = openai.ChatCompletion.create(\n",
" model=self.model_name, messages=messages\n",
" )\n",
"\n",
" if text_only:\n",
" return response.choices[0].message.content\n",
"\n",
" return response\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Creating and Prompting OpenAI's `gpt-3.5-turbo`!\n",
"\n",
"Let's tie all these together and use it to prompt `gpt-3.5-turbo`!"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"from aimakerspace.openai_utils.prompts import (\n",
" UserRolePrompt,\n",
" SystemRolePrompt,\n",
" AssistantRolePrompt,\n",
")\n",
"\n",
"from aimakerspace.openai_utils.chatmodel import ChatOpenAI\n",
"\n",
"chat_openai = ChatOpenAI()\n",
"user_prompt_template = \"{content}\"\n",
"user_role_prompt = UserRolePrompt(user_prompt_template)\n",
"system_prompt_template = (\n",
" \"You are an expert in {expertise}, you always answer in a kind way.\"\n",
")\n",
"system_role_prompt = SystemRolePrompt(system_prompt_template)\n",
"\n",
"messages = [\n",
" user_role_prompt.create_message(\n",
" content=\"What is the best way to write a loop?\"\n",
" ),\n",
" system_role_prompt.create_message(expertise=\"Python\"),\n",
"]\n",
"\n",
"response = chat_openai.run(messages)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The best way to write a loop depends on the specific programming language you are using. However, I can provide some general tips for writing loops that can apply to many languages, including Python:\n",
"\n",
"1. Determine the type of loop you need: There are generally two types of loops: \"for\" loops and \"while\" loops. Use a \"for\" loop when you know the number of iterations in advance, and a \"while\" loop when the number of iterations is uncertain.\n",
"\n",
"2. Define the loop condition: In most cases, a loop should have a defined condition that determines whether the loop should continue or exit. This condition is typically checked before each iteration. Make sure the condition is appropriate for your specific scenario.\n",
"\n",
"3. Initialize loop control variables: If your loop requires variables to control its flow, make sure to initialize them before the loop starts. This ensures the loop starts with the expected initial values.\n",
"\n",
"4. Update loop control variables: When using a loop that relies on control variables, ensure that you update these variables within the loop body. Otherwise, the loop might become infinite or not produce the desired results.\n",
"\n",
"5. Include necessary code in the loop body: Within the loop body, place the code you want to execute during each iteration. This could include calculations, condition checks, or any other desired operations.\n",
"\n",
"6. Ensure proper indentation: Many programming languages, including Python, use indentation to define the scope of the loop body. Make sure to indent the code inside the loop correctly, so it is executed as part of the loop.\n",
"\n",
"7. Exit the loop when appropriate: If there is a condition based on which the loop should terminate, ensure it is properly implemented. Otherwise, an infinite loop may occur, which could lead to unexpected results or even crash your program.\n",
"\n",
"Remember, coding practices and guidelines may vary based on the programming language you are using, so it's always a good idea to consult the documentation or specific best practices for that language.\n"
]
}
],
"source": [
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Retrieval Augmented Question Answering Prompt\n",
"\n",
"Now we can create a RAQA prompt - which will help our system behave in a way that makes sense!\n",
"\n",
"There is much you could do here, many tweaks and improvements to be made!"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"RAQA_PROMPT_TEMPLATE = \"\"\"\n",
"Use the provided context to answer the user's query. \n",
"\n",
"You may not answer the user's query unless there is specific context in the following text.\n",
"\n",
"If you do not know the answer, or cannot answer, please respond with \"I don't know\".\n",
"\n",
"Context:\n",
"{context}\n",
"\"\"\"\n",
"\n",
"raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)\n",
"\n",
"USER_PROMPT_TEMPLATE = \"\"\"\n",
"User Query:\n",
"{user_query}\n",
"\"\"\"\n",
"\n",
"user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)\n",
"\n",
"class RetrievalAugmentedQAPipeline:\n",
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:\n",
" self.llm = llm\n",
" self.vector_db_retriever = vector_db_retriever\n",
"\n",
" def run_pipeline(self, user_query: str) -> str:\n",
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
" \n",
" context_prompt = \"\"\n",
" for context in context_list:\n",
" context_prompt += context[0] + \"\\n\"\n",
"\n",
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
"\n",
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
" \n",
" return self.llm.run([formatted_system_prompt, formatted_user_prompt])"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
" vector_db_retriever=vector_db,\n",
" llm=chat_openai\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'King Lear is a character in William Shakespeare\\'s play called \"King Lear.\" He is an aging king who decides to divide his kingdom among his three daughters, Goneril, Regan, and Cordelia. However, his decision leads to a series of tragic events and the unraveling of his sanity.'"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is King Lear?\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Visibility Tooling\n",
"\n",
"This is great, but what if we wanted to add some visibility to our pipeline?\n",
"\n",
"Let's use Weights and Biases as a visibility tool!\n",
"\n",
"The first thing we'll need to do is create a Weights and Biases account and get an API key. \n",
"\n",
"You can follow the process outlined [here](https://docs.wandb.ai/quickstart) to do exactly that!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can get the Weights and Biases dependency and add our key to our env. to begin!"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"!pip install -q -U wandb"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"wandb_key = getpass(\"Weights and Biases API Key: \")\n",
"os.environ[\"WANDB_API_KEY\"] = wandb_key"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[34m\u001b[1mwandb\u001b[0m: Currently logged in as: \u001b[33mgarygec8\u001b[0m (\u001b[33mdeepmediamachine\u001b[0m). Use \u001b[1m`wandb login --relogin`\u001b[0m to force relogin\n"
]
},
{
"data": {
"text/html": [
"wandb version 0.16.1 is available! To upgrade, please run:\n",
" $ pip install wandb --upgrade"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Tracking run with wandb version 0.16.0"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Run data is saved locally in <code>c:\\ai\\llmops3\\repos\\vsrepo\\my-first-raqa\\wandb\\run-20231205_135828-pd04j1u0</code>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Syncing run <strong><a href='https://wandb.ai/deepmediamachine/Visibility%20Example/runs/pd04j1u0' target=\"_blank\">northern-disco-1</a></strong> to <a href='https://wandb.ai/deepmediamachine/Visibility%20Example' target=\"_blank\">Weights & Biases</a> (<a href='https://wandb.me/run' target=\"_blank\">docs</a>)<br/>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
" View project at <a href='https://wandb.ai/deepmediamachine/Visibility%20Example' target=\"_blank\">https://wandb.ai/deepmediamachine/Visibility%20Example</a>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
" View run at <a href='https://wandb.ai/deepmediamachine/Visibility%20Example/runs/pd04j1u0' target=\"_blank\">https://wandb.ai/deepmediamachine/Visibility%20Example/runs/pd04j1u0</a>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<button onClick=\"this.nextSibling.style.display='block';this.style.display='none';\">Display W&B run</button><iframe src='https://wandb.ai/deepmediamachine/Visibility%20Example/runs/pd04j1u0?jupyter=true' style='border:none;width:100%;height:420px;display:none;'></iframe>"
],
"text/plain": [
"<wandb.sdk.wandb_run.Run at 0x1c66e162a50>"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import wandb\n",
"\n",
"os.environ[\"WANDB_NOTEBOOK_NAME\"] = \"Python RAQA Example.ipynb\"\n",
"wandb.init(project=\"Visibility Example\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can integrate Weights and Biases into our `RetrievalAugmentedQAPipeline`.\n",
"\n",
"```python\n",
"if self.wandb_project:\n",
" root_span = Trace(\n",
" name=\"root_span\",\n",
" kind=\"llm\",\n",
" status_code=status,\n",
" status_message=status_message,\n",
" start_time_ms=start_time,\n",
" end_time_ms=end_time,\n",
" metadata={\n",
" \"token_usage\" : token_usage\n",
" },\n",
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
" outputs= {\"response\" : response_text}\n",
" )\n",
"\n",
" root_span.log(name=\"openai_trace\")\n",
"```\n",
"\n",
"The main things to consider here are how to populate the various fields to make sure we're tracking useful information. \n",
"\n",
"We'll use the `text_only` flag to ensure we can get detailed information about our LLM call!\n",
"\n",
"You can check out all the parameters for Weights and Biases `Trace` [here](https://github.com/wandb/wandb/blob/653015a014281f45770aaf43627f64d9c4f04a32/wandb/sdk/data_types/trace_tree.py#L166)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"import datetime\n",
"from wandb.sdk.data_types.trace_tree import Trace\n",
"\n",
"class RetrievalAugmentedQAPipeline:\n",
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase, wandb_project = None) -> None:\n",
" self.llm = llm\n",
" self.vector_db_retriever = vector_db_retriever\n",
" self.wandb_project = wandb_project\n",
"\n",
" def run_pipeline(self, user_query: str) -> str:\n",
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
" \n",
" context_prompt = \"\"\n",
" for context in context_list:\n",
" context_prompt += context[0] + \"\\n\"\n",
"\n",
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
"\n",
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
"\n",
" \n",
" start_time = datetime.datetime.now().timestamp() * 1000\n",
"\n",
" try:\n",
" openai_response = self.llm.run([formatted_system_prompt, formatted_user_prompt], text_only=False)\n",
" end_time = datetime.datetime.now().timestamp() * 1000\n",
" status = \"success\"\n",
" status_message = (None, )\n",
" response_text = openai_response.choices[0].message.content\n",
" token_usage = dict(openai_response.usage)\n",
" model = openai_response.model\n",
"\n",
" except Exception as e:\n",
" end_time = datetime.datetime.now().timestamp() * 1000\n",
" status = \"error\"\n",
" status_message = str(e)\n",
" response_text = \"\"\n",
" token_usage = {}\n",
" model = \"\"\n",
"\n",
" if self.wandb_project:\n",
" root_span = Trace(\n",
" name=\"root_span\",\n",
" kind=\"llm\",\n",
" status_code=status,\n",
" status_message=status_message,\n",
" start_time_ms=start_time,\n",
" end_time_ms=end_time,\n",
" metadata={\n",
" \"token_usage\" : token_usage,\n",
" \"model_name\" : model\n",
" },\n",
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
" outputs= {\"response\" : response_text}\n",
" )\n",
"\n",
" root_span.log(name=\"openai_trace\")\n",
" \n",
" return response_text if response_text else \"We ran into an error. Please try again later. Full Error Message: \" + status_message"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
" vector_db_retriever=vector_db,\n",
" llm=chat_openai,\n",
" wandb_project=\"LLM Visibility Example\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"I don't know.\""
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is Batman?\")"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Cordelia dies. In the provided context, King Lear is seen holding Cordelia\\'s dead body in his arms. The text describes how he mourns her, exclaiming \"Howl, howl, howl, howl!\" and expressing his grief over her death.'"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"retrieval_augmented_qa_pipeline.run_pipeline(\"What happens to Cordelia?\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Navigate to the Weights and Biases \"run\" link to see how your LLM is performing!\n",
"\n",
"```\n",
"View run at YOUR LINK HERE\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Conclusion\n",
"\n",
"In this notebook, we've gone through the steps required to create your own simple RAQA application!\n",
"\n",
"Please feel free to extend this as much as you'd like. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Bonus Challenges\n",
"\n",
"Challenge 1: \n",
"- Implement a new distance measure\n",
"- Implement a more efficient vector search\n",
"\n",
"Challenge 2: \n",
"- Create an external VectorStore that can be run/hosted elsewhere\n",
"- Build an adapter for that VectorStore here"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'chainlit'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32mc:\\ai\\llmops3\\repos\\vsrepo\\my-first-raqa\\Python RAQA Example.ipynb Cell 53\u001b[0m line \u001b[0;36m1\n\u001b[1;32m----> <a href='vscode-notebook-cell:/c%3A/ai/llmops3/repos/vsrepo/my-first-raqa/Python%20RAQA%20Example.ipynb#Y103sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mchainlit\u001b[39;00m \u001b[39mas\u001b[39;00m \u001b[39mcl\u001b[39;00m \u001b[39m# importing chainlit for our app\u001b[39;00m\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/ai/llmops3/repos/vsrepo/my-first-raqa/Python%20RAQA%20Example.ipynb#Y103sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mchainlit\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mprompt\u001b[39;00m \u001b[39mimport\u001b[39;00m Prompt, PromptMessage \u001b[39m# importing prompt tools\u001b[39;00m\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/ai/llmops3/repos/vsrepo/my-first-raqa/Python%20RAQA%20Example.ipynb#Y103sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mchainlit\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mplayground\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mproviders\u001b[39;00m \u001b[39mimport\u001b[39;00m ChatOpenAI \u001b[39m# importing ChatOpenAI tools\u001b[39;00m\n",
"\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'chainlit'"
]
}
],
"source": [
"import chainlit as cl # importing chainlit for our app\n",
"from chainlit.prompt import Prompt, PromptMessage # importing prompt tools\n",
"from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "buildyourownlangchain",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
|