Spaces:
Runtime error
Runtime error
File size: 77,262 Bytes
644f326 | 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 | {
"cells": [
{
"cell_type": "markdown",
"id": "a782644a",
"metadata": {},
"source": [
"### Chatbot And RAG Evaluation\n",
"\n",
"Retrieval Augmented Generation (RAG) is a technique that enhances Large Language Models (LLMs) by providing them with relevant external knowledge. It has become one of the most widely used approaches for building LLM applications.\n",
"\n",
"This tutorial will show you how to evaluate your RAG applications using LangSmith. You'll learn:\n",
"\n",
"1. How to create test datasets\n",
"2. How to run your RAG application on those datasets\n",
"3. How to measure your application's performance using different evaluation metrics\n",
"\n",
"#### Overview\n",
"A typical RAG evaluation workflow consists of three main steps:\n",
"\n",
"1. Creating a dataset with questions and their expected answers\n",
"2. Running your RAG application on those questions\n",
"3. Using evaluators to measure how well your application performed, looking at factors like:\n",
" - Answer relevance\n",
" - Answer accuracy\n",
" - Retrieval quality\n",
" \n",
"For this tutorial, we'll create and evaluate a bot that answers questions about a few of Lilian Weng's insightful blog posts."
]
},
{
"cell_type": "markdown",
"id": "d0581b36",
"metadata": {},
"source": [
"### Chatbot Evaluation"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "5b4f5cf5",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"load_dotenv()\n",
"\n",
"os.environ[\"LANGSMITH_API_KEY\"]=os.getenv(\"LANGSMITH_API_KEY\")\n",
"os.environ[\"OPENAI_API_KEY\"]=os.getenv(\"OPENAI_API_KEY\")\n",
"os.environ[\"LANGSMITH_TRACING\"]=\"true\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "97a6d452",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'example_ids': ['596db3b7-bbbc-46fd-9f94-69bdc0791732',\n",
" '575b5134-ad1f-41de-8269-dbe299994e30',\n",
" '2864cc97-108b-4df9-929c-dc99dd7b82d7',\n",
" 'f642340f-a193-4c1b-8289-0962d5e1fadd',\n",
" '01a10cb2-d736-4c95-9dd6-e629b758ef2f'],\n",
" 'count': 5}"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=2e2364fd-7c7c-4294-9669-f2c8acc71c76,id=2e2364fd-7c7c-4294-9669-f2c8acc71c76\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: usage limit monthly_traces of 100 exceeded. Check LangSmith usage configuration settings\"}\\n')trace=81edeb23-956f-4a69-8d24-fb29ba1662cb,id=81edeb23-956f-4a69-8d24-fb29ba1662cb; trace=81edeb23-956f-4a69-8d24-fb29ba1662cb,id=2dc8e783-8360-4add-b218-d13c1e22c2ab\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=81edeb23-956f-4a69-8d24-fb29ba1662cb,id=2dc8e783-8360-4add-b218-d13c1e22c2ab; trace=81edeb23-956f-4a69-8d24-fb29ba1662cb,id=9b93c26e-43ce-4165-9b6a-35a819ebbd31\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=81edeb23-956f-4a69-8d24-fb29ba1662cb,id=9b93c26e-43ce-4165-9b6a-35a819ebbd31; trace=81edeb23-956f-4a69-8d24-fb29ba1662cb,id=81edeb23-956f-4a69-8d24-fb29ba1662cb\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: usage limit monthly_traces of 100 exceeded. Check LangSmith usage configuration settings\"}\\n')trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=a611a626-b5a2-4bfd-a907-4362ff71275f; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=90912e17-f045-4b1b-ae79-4a1d0855c3e9; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=235cb7a4-046d-4a4f-b1ad-7c4eb88e1676\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=235cb7a4-046d-4a4f-b1ad-7c4eb88e1676; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=2cb08cff-f5f0-4147-bdda-f0f54efc9921\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=2cb08cff-f5f0-4147-bdda-f0f54efc9921; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=90912e17-f045-4b1b-ae79-4a1d0855c3e9; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=a611a626-b5a2-4bfd-a907-4362ff71275f; trace=cfc46ed3-33a9-49e6-817a-5d600664242a,id=cfc46ed3-33a9-49e6-817a-5d600664242a; trace=cfc46ed3-33a9-49e6-817a-5d600664242a,id=ff429412-fa64-43b7-99e8-8eb7c82b3ab5; trace=cfc46ed3-33a9-49e6-817a-5d600664242a,id=898c9e11-a1f9-4c4e-85d0-5738d8a6c6b8\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=cfc46ed3-33a9-49e6-817a-5d600664242a,id=898c9e11-a1f9-4c4e-85d0-5738d8a6c6b8; trace=cfc46ed3-33a9-49e6-817a-5d600664242a,id=ff429412-fa64-43b7-99e8-8eb7c82b3ab5; trace=cfc46ed3-33a9-49e6-817a-5d600664242a,id=cfc46ed3-33a9-49e6-817a-5d600664242a; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=e4904707-0dc9-4dbd-ba9a-92e31e10b626; trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=906485ce-8498-4b41-8050-f4b9ff547b45; trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=6d3458fe-9577-44a1-a5e8-b3deee6eb0c6; trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=16df8f17-b7a0-4821-9532-cd4160bb82eb\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=16df8f17-b7a0-4821-9532-cd4160bb82eb; trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=c1faef9e-6a02-4308-a961-845138363d7f; trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=c1faef9e-6a02-4308-a961-845138363d7f; trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=6d3458fe-9577-44a1-a5e8-b3deee6eb0c6; trace=906485ce-8498-4b41-8050-f4b9ff547b45,id=906485ce-8498-4b41-8050-f4b9ff547b45; trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=b56f18b0-53ef-4cb5-b016-d3d80442f3d6; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=c39bcd8a-a79b-4745-bb30-cff2c239b5c0; trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=3540fdab-add2-4475-8264-e6753634120a; trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=be6c85cb-887b-45e4-b6f3-5047f9cf2fb8\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=be6c85cb-887b-45e4-b6f3-5047f9cf2fb8; trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=0abb4a2f-2d23-458a-95ca-d20939be6df7; trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=0abb4a2f-2d23-458a-95ca-d20939be6df7; trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=3540fdab-add2-4475-8264-e6753634120a; trace=b56f18b0-53ef-4cb5-b016-d3d80442f3d6,id=b56f18b0-53ef-4cb5-b016-d3d80442f3d6; trace=074c9224-a494-4909-9738-37405947f213,id=074c9224-a494-4909-9738-37405947f213; trace=074c9224-a494-4909-9738-37405947f213,id=18dda164-bc16-49d8-a9d2-b7392940a46a; trace=074c9224-a494-4909-9738-37405947f213,id=986cb4d0-1b77-4fdc-9b88-a7450de3b23b; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=43c14801-e85b-4e52-991a-48f3468f4d21\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=074c9224-a494-4909-9738-37405947f213,id=986cb4d0-1b77-4fdc-9b88-a7450de3b23b; trace=074c9224-a494-4909-9738-37405947f213,id=06f4c8c7-f4dc-4afe-9f24-e46624a84b8a; trace=074c9224-a494-4909-9738-37405947f213,id=06f4c8c7-f4dc-4afe-9f24-e46624a84b8a; trace=074c9224-a494-4909-9738-37405947f213,id=18dda164-bc16-49d8-a9d2-b7392940a46a; trace=074c9224-a494-4909-9738-37405947f213,id=074c9224-a494-4909-9738-37405947f213; trace=a611a626-b5a2-4bfd-a907-4362ff71275f,id=66ad7aa2-a7c2-449f-ad98-35a7784ebdce; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=6345c018-7455-48da-987a-6fdf061a15e5; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=b5e7c035-3a1f-4b39-b87d-b8dee8479b32; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=353b0be7-cc31-4d64-be03-2c5abe52ad2f; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=353b0be7-cc31-4d64-be03-2c5abe52ad2f; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=f063e967-059c-412e-a388-5820f9395aee\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=6345c018-7455-48da-987a-6fdf061a15e5,id=f063e967-059c-412e-a388-5820f9395aee; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=b5e7c035-3a1f-4b39-b87d-b8dee8479b32; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=6345c018-7455-48da-987a-6fdf061a15e5; trace=0458bac7-c944-4247-917f-9f6e2adbf3ff,id=0458bac7-c944-4247-917f-9f6e2adbf3ff; trace=0458bac7-c944-4247-917f-9f6e2adbf3ff,id=b2a5c781-a79c-47e3-a74a-ad9fd17ff3d1; trace=0458bac7-c944-4247-917f-9f6e2adbf3ff,id=894efdf5-a520-46b0-9497-5c62d6193f84; trace=0458bac7-c944-4247-917f-9f6e2adbf3ff,id=894efdf5-a520-46b0-9497-5c62d6193f84; trace=0458bac7-c944-4247-917f-9f6e2adbf3ff,id=b2a5c781-a79c-47e3-a74a-ad9fd17ff3d1; trace=0458bac7-c944-4247-917f-9f6e2adbf3ff,id=0458bac7-c944-4247-917f-9f6e2adbf3ff; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=5ebec3d5-4c3f-4a61-929e-08c961a76367; trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=ee627a18-95a9-482c-aa08-587c8c77520d; trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=1014723b-7e4c-4ba0-a196-ed1c884de250; trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=090621c2-22d2-4ba6-97b6-cdebca7477f1\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=090621c2-22d2-4ba6-97b6-cdebca7477f1; trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=ec954bff-5dfb-4ddd-a1d1-26993d993521; trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=ec954bff-5dfb-4ddd-a1d1-26993d993521; trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=1014723b-7e4c-4ba0-a196-ed1c884de250; trace=ee627a18-95a9-482c-aa08-587c8c77520d,id=ee627a18-95a9-482c-aa08-587c8c77520d; trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=4156acdd-b019-4b81-8f00-ec6020cd9e7c; trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=1dbab607-b665-47ec-8e16-ee71dda9244d; trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=65fda144-7e24-47a7-bf0f-cab8b0541c7f; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=42456b98-ffc1-44c7-9a78-443c57857513\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=65fda144-7e24-47a7-bf0f-cab8b0541c7f; trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=ff695bbb-4703-4e68-9500-11b47bb363df; trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=ff695bbb-4703-4e68-9500-11b47bb363df; trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=1dbab607-b665-47ec-8e16-ee71dda9244d; trace=4156acdd-b019-4b81-8f00-ec6020cd9e7c,id=4156acdd-b019-4b81-8f00-ec6020cd9e7c; trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=5ae2b840-db97-4437-87f0-19826503b7b5; trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=1a35aa3e-f89d-4f30-88ba-c3809a32f095; trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=85606bbd-8021-4790-a93f-23c2c107e4b2; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=ebd08729-d53c-41c5-8329-ec08340fca6c\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=85606bbd-8021-4790-a93f-23c2c107e4b2; trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=52d1647f-d96d-48c5-ab79-7e62f038a12d; trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=52d1647f-d96d-48c5-ab79-7e62f038a12d; trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=1a35aa3e-f89d-4f30-88ba-c3809a32f095; trace=5ae2b840-db97-4437-87f0-19826503b7b5,id=5ae2b840-db97-4437-87f0-19826503b7b5; trace=6345c018-7455-48da-987a-6fdf061a15e5,id=b6308865-b23b-46e9-9e3d-63927b5a9830; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=9f1c9352-c7db-44b2-a6dc-8a901af3d712; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=0cfb64fa-c7e5-4866-ac5a-9bd0e091acd8; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=c5fb0d75-f0a0-4a54-9674-daea7c1e46c0\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=c5fb0d75-f0a0-4a54-9674-daea7c1e46c0; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=8c93b20e-8474-4856-a47a-d8c7ef9086ef\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=8c93b20e-8474-4856-a47a-d8c7ef9086ef; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=0cfb64fa-c7e5-4866-ac5a-9bd0e091acd8; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=9f1c9352-c7db-44b2-a6dc-8a901af3d712; trace=d9a836cd-8ffb-4117-b1b6-b76a19ba7524,id=d9a836cd-8ffb-4117-b1b6-b76a19ba7524; trace=d9a836cd-8ffb-4117-b1b6-b76a19ba7524,id=df32d072-be42-4939-9027-f06ba007becc; trace=d9a836cd-8ffb-4117-b1b6-b76a19ba7524,id=642bc28b-79a9-4b14-9937-11e40fb62014; trace=d9a836cd-8ffb-4117-b1b6-b76a19ba7524,id=642bc28b-79a9-4b14-9937-11e40fb62014; trace=d9a836cd-8ffb-4117-b1b6-b76a19ba7524,id=df32d072-be42-4939-9027-f06ba007becc; trace=d9a836cd-8ffb-4117-b1b6-b76a19ba7524,id=d9a836cd-8ffb-4117-b1b6-b76a19ba7524; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=f6e3c42f-b26a-4f0e-9dcf-dd847f36dcc9; trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=4b4b895f-7daa-4cfd-8850-20ed87623d55; trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=89d6e43c-f996-4ce5-8e94-c6a6d96478a2; trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=7787cca7-6def-4bce-a1ae-99083c4d93c4\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=7787cca7-6def-4bce-a1ae-99083c4d93c4; trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=99b8e48c-aa12-4e84-a5dd-f339787c53b6; trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=99b8e48c-aa12-4e84-a5dd-f339787c53b6; trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=89d6e43c-f996-4ce5-8e94-c6a6d96478a2; trace=4b4b895f-7daa-4cfd-8850-20ed87623d55,id=4b4b895f-7daa-4cfd-8850-20ed87623d55; trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=c2291db7-ce0d-47d6-9884-9fa8353eacf7; trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=05a1270f-2804-4540-bb39-2a87efb523ea; trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=4054b7f7-fc08-41cd-a15d-a74cd6f9cb95; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=e63d67e1-e117-413a-8d07-38e4196d8fd2\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=4054b7f7-fc08-41cd-a15d-a74cd6f9cb95; trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=1524b27f-093f-4214-9445-9f3e7eab80e1; trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=1524b27f-093f-4214-9445-9f3e7eab80e1; trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=05a1270f-2804-4540-bb39-2a87efb523ea; trace=c2291db7-ce0d-47d6-9884-9fa8353eacf7,id=c2291db7-ce0d-47d6-9884-9fa8353eacf7; trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=7831d64e-c665-4eff-82a1-9809c7f3b4a8; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=b2096cdb-ec50-4df0-b024-b5aa06a513d5; trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=7707e8c3-3a94-4ff8-bb60-1a035c9bbf0e; trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=d3d4a78c-7e16-4e8a-9f25-fd0e5b623abf\n",
"Failed to send compressed multipart ingest: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: user-defined usage limit monthly_traces exceeded. Check LangSmith usage configuration settings\"}\\n')trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=d3d4a78c-7e16-4e8a-9f25-fd0e5b623abf; trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=4217fa1a-b5f1-49a4-966a-e251a0ba7e6c; trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=4217fa1a-b5f1-49a4-966a-e251a0ba7e6c; trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=7707e8c3-3a94-4ff8-bb60-1a035c9bbf0e; trace=7831d64e-c665-4eff-82a1-9809c7f3b4a8,id=7831d64e-c665-4eff-82a1-9809c7f3b4a8; trace=9f1c9352-c7db-44b2-a6dc-8a901af3d712,id=570ad29f-b0ae-4228-8d08-a7df907ee6f2\n"
]
}
],
"source": [
"from langsmith import Client\n",
"\n",
"client = Client()\n",
"\n",
"# Define dataset: these are your test cases\n",
"dataset_name = \"Chatbots Evaluation\"\n",
"dataset = client.create_dataset(dataset_name)\n",
"client.create_examples(\n",
" dataset_id=dataset.id,\n",
" examples=[\n",
" {\n",
" \"inputs\": {\"question\": \"What is LangChain?\"},\n",
" \"outputs\": {\"answer\": \"A framework for building LLM applications\"},\n",
" },\n",
" {\n",
" \"inputs\": {\"question\": \"What is LangSmith?\"},\n",
" \"outputs\": {\"answer\": \"A platform for observing and evaluating LLM applications\"},\n",
" },\n",
" {\n",
" \"inputs\": {\"question\": \"What is OpenAI?\"},\n",
" \"outputs\": {\"answer\": \"A company that creates Large Language Models\"},\n",
" },\n",
" {\n",
" \"inputs\": {\"question\": \"What is Google?\"},\n",
" \"outputs\": {\"answer\": \"A technology company known for search\"},\n",
" },\n",
" {\n",
" \"inputs\": {\"question\": \"What is Mistral?\"},\n",
" \"outputs\": {\"answer\": \"A company that creates Large Language Models\"},\n",
" }\n",
" ]\n",
")"
]
},
{
"cell_type": "markdown",
"id": "f20dd601",
"metadata": {},
"source": [
"### Define Metrics (LLM As A Judge)\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "12e88e52",
"metadata": {},
"outputs": [],
"source": [
"import openai\n",
"from langsmith import wrappers\n",
" \n",
"openai_client=wrappers.wrap_openai(openai.OpenAI())\n",
"\n",
"eval_instructions = \"You are an expert professor specialized in grading students' answers to questions.\"\n",
"\n",
"def correctness(inputs:dict,outputs:dict, reference_outputs:dict)->bool:\n",
" user_content = f\"\"\"You are grading the following question:\n",
" {inputs['question']}\n",
" Here is the real answer:\n",
" {reference_outputs['answer']}\n",
" You are grading the following predicted answer:\n",
" {outputs['response']}\n",
" Respond with CORRECT or INCORRECT:\n",
" Grade:\n",
" \"\"\"\n",
" response=openai_client.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" temperature=0,\n",
" messages=[\n",
" {\"role\":\"system\",\"content\":eval_instructions},\n",
" {\"role\":\"user\",\"content\":user_content}\n",
" ]\n",
" ).choices[0].message.content\n",
"\n",
" return response == \"CORRECT\""
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "e4326a96",
"metadata": {},
"outputs": [],
"source": [
"## Concisions- checks whether the actual output is less than 2x the length of the expected result.\n",
"\n",
"def concision(outputs: dict, reference_outputs: dict) -> bool:\n",
" return int(len(outputs[\"response\"]) < 2 * len(reference_outputs[\"answer\"]))"
]
},
{
"cell_type": "markdown",
"id": "e7ad76f1",
"metadata": {},
"source": [
"### Run Evaluations"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "a42fd2bd",
"metadata": {},
"outputs": [],
"source": [
"default_instructions = \"Respond to the users question in a short, concise manner (one short sentence).\"\n",
"def my_app(question: str, model: str = \"gpt-4o-mini\", instructions: str = default_instructions) -> str:\n",
" return openai_client.chat.completions.create(\n",
" model=model,\n",
" temperature=0,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": instructions},\n",
" {\"role\": \"user\", \"content\": question},\n",
" ],\n",
" ).choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "e171d6aa",
"metadata": {},
"outputs": [],
"source": [
"### Call my_app for every datapoints\n",
"def ls_target(inputs: str) -> dict:\n",
" return {\"response\": my_app(inputs[\"question\"])}"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "dc97aa85",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"View the evaluation results for experiment: 'openai-4o-mini-chatbot-ac3151d5' at:\n",
"https://smith.langchain.com/o/df51e0aa-baf3-5e22-92d8-ad1de74986e0/datasets/8ac2e6e7-257b-4355-a785-de7df185371e/compare?selectedSessions=060b20f5-52db-4eb1-95b4-c62123293cb8\n",
"\n",
"\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"e:\\RAGUdemy\\.venv\\Lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n",
"5it [00:10, 2.04s/it]\n"
]
}
],
"source": [
"## Run our evaluation\n",
"experiment_results=client.evaluate(\n",
" ls_target, ## Your AI system\n",
" data=dataset_name,\n",
" evaluators=[correctness,concision],\n",
" experiment_prefix=\"openai-4o-mini-chatbot\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "9158ae4a",
"metadata": {},
"outputs": [],
"source": [
"### Call my_app for every datapoints\n",
"def ls_target(inputs: str) -> dict:\n",
" return {\"response\": my_app(inputs[\"question\"],model=\"gpt-4-turbo\")}"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "c2e58d4f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"View the evaluation results for experiment: 'openai-4-turbo-chatbot-ae4ea2ed' at:\n",
"https://smith.langchain.com/o/df51e0aa-baf3-5e22-92d8-ad1de74986e0/datasets/8ac2e6e7-257b-4355-a785-de7df185371e/compare?selectedSessions=c4136a5d-ab63-46ec-88d4-fcfe95daaf59\n",
"\n",
"\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"5it [00:09, 1.90s/it]\n"
]
}
],
"source": [
"## Run our evaluation\n",
"experiment_results=client.evaluate(\n",
" ls_target, ## Your AI system\n",
" data=dataset_name,\n",
" evaluators=[correctness,concision],\n",
" experiment_prefix=\"openai-4-turbo-chatbot\"\n",
")"
]
},
{
"cell_type": "markdown",
"id": "1cbad8e8",
"metadata": {},
"source": [
"### Evaluation For RAG"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "17ddbc18",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"USER_AGENT environment variable not set, consider setting it to identify your requests.\n"
]
}
],
"source": [
"## RAG\n",
"from langchain_community.document_loaders import WebBaseLoader\n",
"from langchain_core.vectorstores import InMemoryVectorStore\n",
"from langchain_openai import OpenAIEmbeddings\n",
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
"\n",
"# List of URLs to load documents from\n",
"urls = [\n",
" \"https://lilianweng.github.io/posts/2023-06-23-agent/\",\n",
" \"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/\",\n",
" \"https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/\",\n",
"]\n",
"\n",
"# Load documents from the URLs\n",
"docs = [WebBaseLoader(url).load() for url in urls]\n",
"docs_list = [item for sublist in docs for item in sublist]\n",
"\n",
"# Initialize a text splitter with specified chunk size and overlap\n",
"text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n",
" chunk_size=250, chunk_overlap=0\n",
")\n",
"\n",
"# Split the documents into chunks\n",
"doc_splits = text_splitter.split_documents(docs_list)\n",
"\n",
"# Add the document chunks to the \"vector store\" using OpenAIEmbeddings\n",
"vectorstore = InMemoryVectorStore.from_documents(\n",
" documents=doc_splits,\n",
" embedding=OpenAIEmbeddings(),\n",
")\n",
"\n",
"# With langchain we can easily turn any vector store into a retrieval component:\n",
"retriever = vectorstore.as_retriever(k=6)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "d655eb26",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(id='618dc4b1-b918-4844-ae2e-86af87f25256', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content='They also discussed the risks, especially with illicit drugs and bioweapons. They developed a test set containing a list of known chemical weapon agents and asked the agent to synthesize them. 4 out of 11 requests (36%) were accepted to obtain a synthesis solution and the agent attempted to consult documentation to execute the procedure. 7 out of 11 were rejected and among these 7 rejected cases, 5 happened after a Web search while 2 were rejected based on prompt only.\\nGenerative Agents Simulation#\\nGenerative Agents (Park, et al. 2023) is super fun experiment where 25 virtual characters, each controlled by a LLM-powered agent, are living and interacting in a sandbox environment, inspired by The Sims. Generative agents create believable simulacra of human behavior for interactive applications.\\nThe design of generative agents combines LLM with memory, planning and reflection mechanisms to enable agents to behave conditioned on past experience, as well as to interact with other agents.\\n\\nMemory stream: is a long-term memory module (external database) that records a comprehensive list of agents’ experience in natural language.'),\n",
" Document(id='1fd0573b-0767-4f97-a2b2-fa715005a443', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content='Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview#\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory'),\n",
" Document(id='837abf53-55ca-46df-9928-2d56f82a6e54', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content=\"Planning is essentially in order to optimize believability at the moment vs in time.\\nPrompt template: {Intro of an agent X}. Here is X's plan today in broad strokes: 1)\\nRelationships between agents and observations of one agent by another are all taken into consideration for planning and reacting.\\nEnvironment information is present in a tree structure.\\n\\n\\n\\n\\n\\nThe generative agent architecture. (Image source: Park et al. 2023)\"),\n",
" Document(id='97716229-95e9-4af5-b2fe-02f9a7368e93', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content=\"LLM Powered Autonomous Agents | Lil'Log\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nLil'Log\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n|\\n\\n\\n\\n\\n\\n\\nPosts\\n\\n\\n\\n\\nArchive\\n\\n\\n\\n\\nSearch\\n\\n\\n\\n\\nTags\\n\\n\\n\\n\\nFAQ\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n LLM Powered Autonomous Agents\\n \\nDate: June 23, 2023 | Estimated Reading Time: 31 min | Author: Lilian Weng\\n\\n\\n \\n\\n\\nTable of Contents\\n\\n\\n\\nAgent System Overview\\n\\nComponent One: Planning\\n\\nTask Decomposition\\n\\nSelf-Reflection\\n\\n\\nComponent Two: Memory\\n\\nTypes of Memory\\n\\nMaximum Inner Product Search (MIPS)\\n\\n\\nComponent Three: Tool Use\\n\\nCase Studies\\n\\nScientific Discovery Agent\\n\\nGenerative Agents Simulation\\n\\nProof-of-Concept Examples\\n\\n\\nChallenges\\n\\nCitation\\n\\nReferences\")]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Failed to multipart ingest runs: langsmith.utils.LangSmithRateLimitError: Rate limit exceeded for https://api.smith.langchain.com/runs/multipart. HTTPError('429 Client Error: Too Many Requests for url: https://api.smith.langchain.com/runs/multipart', '{\"error\":\"Too many requests: tenant exceeded usage limits: usage limit monthly_traces of 100 exceeded. Check LangSmith usage configuration settings\"}\\n')trace=2e2364fd-7c7c-4294-9669-f2c8acc71c76,id=2e2364fd-7c7c-4294-9669-f2c8acc71c76\n"
]
}
],
"source": [
"retriever.invoke(\"what is agents\")"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "506f13c9",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"ChatOpenAI(client=<openai.resources.chat.completions.completions.Completions object at 0x000001EA28604B90>, async_client=<openai.resources.chat.completions.completions.AsyncCompletions object at 0x000001EA91879FD0>, root_client=<openai.OpenAI object at 0x000001EA28604910>, root_async_client=<openai.AsyncOpenAI object at 0x000001EA286051D0>, model_name='gpt-4o-mini', model_kwargs={}, openai_api_key=SecretStr('**********'))"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain.chat_models import init_chat_model\n",
"llm=init_chat_model(\"openai:gpt-4o-mini\")\n",
"llm"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "7e4fcdf6",
"metadata": {},
"outputs": [],
"source": [
"from langsmith import traceable\n",
"\n",
"## Add decorator\n",
"@traceable()\n",
"def rag_bot(question:str)->dict:\n",
" ## Relevant context\n",
" docs=retriever.invoke(question)\n",
" docs_string = \" \".join(doc.page_content for doc in docs)\n",
"\n",
" instructions = f\"\"\"You are a helpful assistant who is good at analyzing source information and answering questions. Use the following source documents to answer the user's questions. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\n",
"\n",
"Documents:\n",
"{docs_string}\"\"\"\n",
" \n",
" ## llm invoke\n",
"\n",
" ai_msg=llm.invoke([\n",
" {\"role\": \"system\", \"content\": instructions},\n",
" {\"role\": \"user\", \"content\": question},\n",
"\n",
" ])\n",
" return {\"answer\":ai_msg.content,\"documents\":docs}\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "93958f5d",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'answer': 'Agents refer to autonomous entities, particularly in the context of artificial intelligence, that can perceive their environment, make decisions, and take actions to achieve specific goals. In the documents, agents can be powered by large language models (LLMs) and possess features like memory, planning, and reflection to enhance their behavior and interaction. They are often designed to simulate human-like behavior or solve complex problems in various applications.',\n",
" 'documents': [Document(id='618dc4b1-b918-4844-ae2e-86af87f25256', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content='They also discussed the risks, especially with illicit drugs and bioweapons. They developed a test set containing a list of known chemical weapon agents and asked the agent to synthesize them. 4 out of 11 requests (36%) were accepted to obtain a synthesis solution and the agent attempted to consult documentation to execute the procedure. 7 out of 11 were rejected and among these 7 rejected cases, 5 happened after a Web search while 2 were rejected based on prompt only.\\nGenerative Agents Simulation#\\nGenerative Agents (Park, et al. 2023) is super fun experiment where 25 virtual characters, each controlled by a LLM-powered agent, are living and interacting in a sandbox environment, inspired by The Sims. Generative agents create believable simulacra of human behavior for interactive applications.\\nThe design of generative agents combines LLM with memory, planning and reflection mechanisms to enable agents to behave conditioned on past experience, as well as to interact with other agents.\\n\\nMemory stream: is a long-term memory module (external database) that records a comprehensive list of agents’ experience in natural language.'),\n",
" Document(id='1fd0573b-0767-4f97-a2b2-fa715005a443', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content='Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview#\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory'),\n",
" Document(id='837abf53-55ca-46df-9928-2d56f82a6e54', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content=\"Planning is essentially in order to optimize believability at the moment vs in time.\\nPrompt template: {Intro of an agent X}. Here is X's plan today in broad strokes: 1)\\nRelationships between agents and observations of one agent by another are all taken into consideration for planning and reacting.\\nEnvironment information is present in a tree structure.\\n\\n\\n\\n\\n\\nThe generative agent architecture. (Image source: Park et al. 2023)\"),\n",
" Document(id='97716229-95e9-4af5-b2fe-02f9a7368e93', metadata={'source': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'description': 'Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver.\\nAgent System Overview\\nIn a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe agent learns to call external APIs for extra information that is missing from the model weights (often hard to change after pre-training), including current information, code execution capability, access to proprietary information sources and more.\\n\\n\\n\\n\\n\\t\\n\\tOverview of a LLM-powered autonomous agent system.\\n\\nComponent One: Planning\\nA complicated task usually involves many steps. An agent needs to know what they are and plan ahead.', 'language': 'en'}, page_content=\"LLM Powered Autonomous Agents | Lil'Log\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nLil'Log\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n|\\n\\n\\n\\n\\n\\n\\nPosts\\n\\n\\n\\n\\nArchive\\n\\n\\n\\n\\nSearch\\n\\n\\n\\n\\nTags\\n\\n\\n\\n\\nFAQ\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n LLM Powered Autonomous Agents\\n \\nDate: June 23, 2023 | Estimated Reading Time: 31 min | Author: Lilian Weng\\n\\n\\n \\n\\n\\nTable of Contents\\n\\n\\n\\nAgent System Overview\\n\\nComponent One: Planning\\n\\nTask Decomposition\\n\\nSelf-Reflection\\n\\n\\nComponent Two: Memory\\n\\nTypes of Memory\\n\\nMaximum Inner Product Search (MIPS)\\n\\n\\nComponent Three: Tool Use\\n\\nCase Studies\\n\\nScientific Discovery Agent\\n\\nGenerative Agents Simulation\\n\\nProof-of-Concept Examples\\n\\n\\nChallenges\\n\\nCitation\\n\\nReferences\")]}"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"rag_bot(\"What is agents\")"
]
},
{
"cell_type": "markdown",
"id": "8f8fa531",
"metadata": {},
"source": [
"### Dataset"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "c79fc9ba",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'example_ids': ['22098524-fe71-46c2-b86f-d0c8668808e6',\n",
" '93bc3994-6e14-4bd8-b446-9a6c7eb712be',\n",
" 'd8baca57-c7a2-41a0-ae72-0d52b4cda043'],\n",
" 'count': 3}"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langsmith import Client\n",
"\n",
"client=Client()\n",
"\n",
"# Define the examples for the dataset\n",
"examples = [\n",
" {\n",
" \"inputs\": {\"question\": \"How does the ReAct agent use self-reflection? \"},\n",
" \"outputs\": {\"answer\": \"ReAct integrates reasoning and acting, performing actions - such tools like Wikipedia search API - and then observing / reasoning about the tool outputs.\"},\n",
" },\n",
" {\n",
" \"inputs\": {\"question\": \"What are the types of biases that can arise with few-shot prompting?\"},\n",
" \"outputs\": {\"answer\": \"The biases that can arise with few-shot prompting include (1) Majority label bias, (2) Recency bias, and (3) Common token bias.\"},\n",
" },\n",
" {\n",
" \"inputs\": {\"question\": \"What are five types of adversarial attacks?\"},\n",
" \"outputs\": {\"answer\": \"Five types of adversarial attacks are (1) Token manipulation, (2) Gradient based attack, (3) Jailbreak prompting, (4) Human red-teaming, (5) Model red-teaming.\"},\n",
" }\n",
"]\n",
"\n",
"### create the daatset and example in LAngsmith\n",
"dataset_name=\"RAG Test Evaluation\"\n",
"dataset = client.create_dataset(dataset_name=dataset_name)\n",
"client.create_examples(\n",
" dataset_id=dataset.id,\n",
" examples=examples\n",
")\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "7c28a1bd",
"metadata": {},
"source": [
"### Evaluators or Metrics\n",
"1. Correctness: Response vs reference answer\n",
"- Goal: Measure \"how similar/correct is the RAG chain answer, relative to a ground-truth answer\"\n",
"- Mode: Requires a ground truth (reference) answer supplied through a dataset\n",
"- Evaluator: Use LLM-as-judge to assess answer correctness."
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "67dae1ee",
"metadata": {},
"outputs": [],
"source": [
"from typing_extensions import Annotated,TypedDict\n",
"\n",
"## Correctness Output Schema\n",
"\n",
"# Grade output schema\n",
"class CorrectnessGrade(TypedDict):\n",
" # Note that the order in the fields are defined is the order in which the model will generate them.\n",
" # It is useful to put explanations before responses because it forces the model to think through\n",
" # its final response before generating it:\n",
" explanation: Annotated[str, ..., \"Explain your reasoning for the score\"]\n",
" correct: Annotated[bool, ..., \"True if the answer is correct, False otherwise.\"]\n",
"\n",
"## correctness prompt\n",
"\n",
"correctness_instructions = \"\"\"You are a teacher grading a quiz. \n",
"\n",
"You will be given a QUESTION, the GROUND TRUTH (correct) ANSWER, and the STUDENT ANSWER. \n",
"\n",
"Here is the grade criteria to follow:\n",
"(1) Grade the student answers based ONLY on their factual accuracy relative to the ground truth answer. \n",
"(2) Ensure that the student answer does not contain any conflicting statements.\n",
"(3) It is OK if the student answer contains more information than the ground truth answer, as long as it is factually accurate relative to the ground truth answer.\n",
"\n",
"Correctness:\n",
"A correctness value of True means that the student's answer meets all of the criteria.\n",
"A correctness value of False means that the student's answer does not meet all of the criteria.\n",
"\n",
"Explain your reasoning in a step-by-step manner to ensure your reasoning and conclusion are correct. \n",
"\n",
"Avoid simply stating the correct answer at the outset.\"\"\"\n",
"\n",
"from langchain_openai import ChatOpenAI\n",
"\n",
"grader_llm=ChatOpenAI(model=\"gpt-4o-mini\",temperature=0).with_structured_output(CorrectnessGrade,\n",
" method=\"json_schema\",strict=True)\n",
"## evaluator\n",
"def correctness(inputs: dict, outputs: dict, reference_outputs: dict) -> bool:\n",
" \"\"\"An evaluator for RAG answer accuracy\"\"\"\n",
" answers = f\"\"\"\\\n",
"QUESTION: {inputs['question']}\n",
"GROUND TRUTH ANSWER: {reference_outputs['answer']}\n",
"STUDENT ANSWER: {outputs['answer']}\"\"\"\n",
"\n",
" # Run evaluator\n",
" grade = grader_llm.invoke([\n",
" {\"role\": \"system\", \"content\": correctness_instructions}, \n",
" {\"role\": \"user\", \"content\": answers}\n",
" ])\n",
" return grade[\"correct\"]\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "0caee8a4",
"metadata": {},
"source": [
"### Relevance: Response vs input\n",
"The flow is similar to above, but we simply look at the inputs and outputs without needing the reference_outputs. Without a reference answer we can't grade accuracy, but can still grade relevance—as in, did the model address the user's question or not."
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "9ab9f60d",
"metadata": {},
"outputs": [],
"source": [
"# Grade output schema\n",
"class RelevanceGrade(TypedDict):\n",
" explanation: Annotated[str, ..., \"Explain your reasoning for the score\"]\n",
" relevant: Annotated[bool, ..., \"Provide the score on whether the answer addresses the question\"]\n",
"\n",
"# Grade prompt\n",
"relevance_instructions=\"\"\"You are a teacher grading a quiz. \n",
"\n",
"You will be given a QUESTION and a STUDENT ANSWER. \n",
"\n",
"Here is the grade criteria to follow:\n",
"(1) Ensure the STUDENT ANSWER is concise and relevant to the QUESTION\n",
"(2) Ensure the STUDENT ANSWER helps to answer the QUESTION\n",
"\n",
"Relevance:\n",
"A relevance value of True means that the student's answer meets all of the criteria.\n",
"A relevance value of False means that the student's answer does not meet all of the criteria.\n",
"\n",
"Explain your reasoning in a step-by-step manner to ensure your reasoning and conclusion are correct. \n",
"\n",
"Avoid simply stating the correct answer at the outset.\"\"\"\n",
"\n",
"# Grader LLM\n",
"relevance_llm = ChatOpenAI(model=\"gpt-4o\", temperature=0).with_structured_output(RelevanceGrade, method=\"json_schema\", strict=True)\n",
"\n",
"# Evaluator\n",
"def relevance(inputs: dict, outputs: dict) -> bool:\n",
" \"\"\"A simple evaluator for RAG answer helpfulness.\"\"\"\n",
" answer = f\"QUESTION: {inputs['question']}\\nSTUDENT ANSWER: {outputs['answer']}\"\n",
" grade = relevance_llm.invoke([\n",
" {\"role\": \"system\", \"content\": relevance_instructions}, \n",
" {\"role\": \"user\", \"content\": answer}\n",
" ])\n",
" return grade[\"relevant\"]"
]
},
{
"cell_type": "markdown",
"id": "f0b97886",
"metadata": {},
"source": [
"### Groundedness: Response vs retrieved docs\n",
"Another useful way to evaluate responses without needing reference answers is to check if the response is justified by (or \"grounded in\") the retrieved documents."
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "87044454",
"metadata": {},
"outputs": [],
"source": [
"# Grade output schema\n",
"class GroundedGrade(TypedDict):\n",
" explanation: Annotated[str, ..., \"Explain your reasoning for the score\"]\n",
" grounded: Annotated[bool, ..., \"Provide the score on if the answer hallucinates from the documents\"]\n",
"\n",
"# Grade prompt\n",
"grounded_instructions = \"\"\"You are a teacher grading a quiz. \n",
"\n",
"You will be given FACTS and a STUDENT ANSWER. \n",
"\n",
"Here is the grade criteria to follow:\n",
"(1) Ensure the STUDENT ANSWER is grounded in the FACTS. \n",
"(2) Ensure the STUDENT ANSWER does not contain \"hallucinated\" information outside the scope of the FACTS.\n",
"\n",
"Grounded:\n",
"A grounded value of True means that the student's answer meets all of the criteria.\n",
"A grounded value of False means that the student's answer does not meet all of the criteria.\n",
"\n",
"Explain your reasoning in a step-by-step manner to ensure your reasoning and conclusion are correct. \n",
"\n",
"Avoid simply stating the correct answer at the outset.\"\"\"\n",
"\n",
"# Grader LLM \n",
"grounded_llm = ChatOpenAI(model=\"gpt-4o\", temperature=0).with_structured_output(GroundedGrade, method=\"json_schema\", strict=True)\n",
"\n",
"# Evaluator\n",
"def groundedness(inputs: dict, outputs: dict) -> bool:\n",
" \"\"\"A simple evaluator for RAG answer groundedness.\"\"\"\n",
" doc_string = \"\\n\\n\".join(doc.page_content for doc in outputs[\"documents\"])\n",
" answer = f\"FACTS: {doc_string}\\nSTUDENT ANSWER: {outputs['answer']}\"\n",
" grade = grounded_llm.invoke([{\"role\": \"system\", \"content\": grounded_instructions}, {\"role\": \"user\", \"content\": answer}])\n",
" return grade[\"grounded\"]"
]
},
{
"cell_type": "markdown",
"id": "b5aaaa0b",
"metadata": {},
"source": [
"### Retrieval Relevance: Retrieved docs vs input"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "b36ac507",
"metadata": {},
"outputs": [],
"source": [
"# Grade output schema\n",
"class RetrievalRelevanceGrade(TypedDict):\n",
" explanation: Annotated[str, ..., \"Explain your reasoning for the score\"]\n",
" relevant: Annotated[bool, ..., \"True if the retrieved documents are relevant to the question, False otherwise\"]\n",
"\n",
"# Grade prompt\n",
"retrieval_relevance_instructions = \"\"\"You are a teacher grading a quiz. \n",
"\n",
"You will be given a QUESTION and a set of FACTS provided by the student. \n",
"\n",
"Here is the grade criteria to follow:\n",
"(1) You goal is to identify FACTS that are completely unrelated to the QUESTION\n",
"(2) If the facts contain ANY keywords or semantic meaning related to the question, consider them relevant\n",
"(3) It is OK if the facts have SOME information that is unrelated to the question as long as (2) is met\n",
"\n",
"Relevance:\n",
"A relevance value of True means that the FACTS contain ANY keywords or semantic meaning related to the QUESTION and are therefore relevant.\n",
"A relevance value of False means that the FACTS are completely unrelated to the QUESTION.\n",
"\n",
"Explain your reasoning in a step-by-step manner to ensure your reasoning and conclusion are correct. \n",
"\n",
"Avoid simply stating the correct answer at the outset.\"\"\"\n",
"\n",
"# Grader LLM\n",
"retrieval_relevance_llm = ChatOpenAI(model=\"gpt-4o\", temperature=0).with_structured_output(RetrievalRelevanceGrade, method=\"json_schema\", strict=True)\n",
"\n",
"def retrieval_relevance(inputs: dict, outputs: dict) -> bool:\n",
" \"\"\"An evaluator for document relevance\"\"\"\n",
" doc_string = \"\\n\\n\".join(doc.page_content for doc in outputs[\"documents\"])\n",
" answer = f\"FACTS: {doc_string}\\nQUESTION: {inputs['question']}\"\n",
"\n",
" # Run evaluator\n",
" grade = retrieval_relevance_llm.invoke([\n",
" {\"role\": \"system\", \"content\": retrieval_relevance_instructions}, \n",
" {\"role\": \"user\", \"content\": answer}\n",
" ])\n",
" return grade[\"relevant\"]"
]
},
{
"cell_type": "markdown",
"id": "d28f88ec",
"metadata": {},
"source": [
"### Run the evaluation"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "9bc096fb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"View the evaluation results for experiment: 'rag-doc-relevance-aea19ef6' at:\n",
"https://smith.langchain.com/o/df51e0aa-baf3-5e22-92d8-ad1de74986e0/datasets/f7dc8c23-3b36-46c2-ba44-9f7d6dc50529/compare?selectedSessions=28f937b5-5274-40e6-b777-276ac59842a6\n",
"\n",
"\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"3it [00:40, 13.64s/it]\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>inputs.question</th>\n",
" <th>outputs.answer</th>\n",
" <th>outputs.documents</th>\n",
" <th>error</th>\n",
" <th>reference.answer</th>\n",
" <th>feedback.correctness</th>\n",
" <th>feedback.groundedness</th>\n",
" <th>feedback.relevance</th>\n",
" <th>feedback.retrieval_relevance</th>\n",
" <th>execution_time</th>\n",
" <th>example_id</th>\n",
" <th>id</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>How does the ReAct agent use self-reflection?</td>\n",
" <td>The ReAct agent utilizes self-reflection by it...</td>\n",
" <td>[page_content='Self-reflection is a vital aspe...</td>\n",
" <td>None</td>\n",
" <td>ReAct integrates reasoning and acting, perform...</td>\n",
" <td>True</td>\n",
" <td>False</td>\n",
" <td>True</td>\n",
" <td>False</td>\n",
" <td>2.469538</td>\n",
" <td>22098524-fe71-46c2-b86f-d0c8668808e6</td>\n",
" <td>b6c2d547-afdd-4cdc-9691-2082d32928e7</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>What are the types of biases that can arise wi...</td>\n",
" <td>The types of biases that can arise with few-sh...</td>\n",
" <td>[page_content='Zero-shot and few-shot learning...</td>\n",
" <td>None</td>\n",
" <td>The biases that can arise with few-shot prompt...</td>\n",
" <td>True</td>\n",
" <td>True</td>\n",
" <td>True</td>\n",
" <td>True</td>\n",
" <td>3.005110</td>\n",
" <td>93bc3994-6e14-4bd8-b446-9a6c7eb712be</td>\n",
" <td>ff2bf2ae-213d-486a-a85d-e0fea4912846</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>What are five types of adversarial attacks?</td>\n",
" <td>The five types of adversarial attacks are toke...</td>\n",
" <td>[page_content='Black-box attacks assume that a...</td>\n",
" <td>None</td>\n",
" <td>Five types of adversarial attacks are (1) Toke...</td>\n",
" <td>True</td>\n",
" <td>True</td>\n",
" <td>True</td>\n",
" <td>True</td>\n",
" <td>1.783208</td>\n",
" <td>d8baca57-c7a2-41a0-ae72-0d52b4cda043</td>\n",
" <td>41383259-c822-4859-853b-ca1dd629f6cf</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" inputs.question \\\n",
"0 How does the ReAct agent use self-reflection? \n",
"1 What are the types of biases that can arise wi... \n",
"2 What are five types of adversarial attacks? \n",
"\n",
" outputs.answer \\\n",
"0 The ReAct agent utilizes self-reflection by it... \n",
"1 The types of biases that can arise with few-sh... \n",
"2 The five types of adversarial attacks are toke... \n",
"\n",
" outputs.documents error \\\n",
"0 [page_content='Self-reflection is a vital aspe... None \n",
"1 [page_content='Zero-shot and few-shot learning... None \n",
"2 [page_content='Black-box attacks assume that a... None \n",
"\n",
" reference.answer feedback.correctness \\\n",
"0 ReAct integrates reasoning and acting, perform... True \n",
"1 The biases that can arise with few-shot prompt... True \n",
"2 Five types of adversarial attacks are (1) Toke... True \n",
"\n",
" feedback.groundedness feedback.relevance feedback.retrieval_relevance \\\n",
"0 False True False \n",
"1 True True True \n",
"2 True True True \n",
"\n",
" execution_time example_id \\\n",
"0 2.469538 22098524-fe71-46c2-b86f-d0c8668808e6 \n",
"1 3.005110 93bc3994-6e14-4bd8-b446-9a6c7eb712be \n",
"2 1.783208 d8baca57-c7a2-41a0-ae72-0d52b4cda043 \n",
"\n",
" id \n",
"0 b6c2d547-afdd-4cdc-9691-2082d32928e7 \n",
"1 ff2bf2ae-213d-486a-a85d-e0fea4912846 \n",
"2 41383259-c822-4859-853b-ca1dd629f6cf "
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def target(inputs: dict) -> dict:\n",
" return rag_bot(inputs[\"question\"])\n",
"\n",
"experiment_results = client.evaluate(\n",
" target,\n",
" data=dataset_name,\n",
" evaluators=[correctness, groundedness, relevance, retrieval_relevance],\n",
" experiment_prefix=\"rag-doc-relevance\",\n",
" metadata={\"version\": \"LCEL context, gpt-4-0125-preview\"},\n",
")\n",
"# Explore results locally as a dataframe if you have pandas installed\n",
"experiment_results.to_pandas()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e7882792",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "RAGUdemy",
"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.13.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|