Spaces:
Runtime error
Runtime error
File size: 66,720 Bytes
6ecf14b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"\n",
"# Use Watsonx to respond to natural language questions using RAG approach for Doctor AI"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"\n",
"\n",
"#### About Retrieval Augmented Generation\n",
"Retrieval Augmented Generation (RAG) is a versatile pattern that can unlock a number of use cases requiring factual recall of information, such as querying a knowledge base in natural language.\n",
"\n",
"In its simplest form, RAG requires 3 steps:\n",
"\n",
"- Index knowledge base passages (once)\n",
"- Retrieve relevant passage(s) from the knowledge base (for every user query)\n",
"- Generate a response by feeding retrieved passage into a large language model (for every user query)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"<a id=\"setup\"></a>\n",
"## Set up the environment"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Install and import dependecies"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"#!pip install chromadb==0.3.27\n",
"#!pip install sentence_transformers \n",
"#!pip install pandas \n",
"#!pip install rouge_score \n",
"#!pip install nltk\n",
"#!pip install \"ibm-watson-machine-learning>=1.0.312\" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** Please restart the notebook kernel to pick up proper version of packages installed above."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"import os, getpass\n",
"import pandas as pd\n",
"from typing import Optional, Dict, Any, Iterable, List\n",
"\n",
"try:\n",
" from sentence_transformers import SentenceTransformer\n",
"except ImportError:\n",
" raise ImportError(\"Could not import sentence_transformers: Please install sentence-transformers package.\")\n",
" \n",
"try:\n",
" import chromadb\n",
" from chromadb.api.types import EmbeddingFunction\n",
"except ImportError:\n",
" raise ImportError(\"Could not import chromdb: Please install chromadb package.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Watsonx API connection\n",
"This cell defines the credentials required to work with watsonx API for Foundation\n",
"Model inferencing.\n",
"\n",
"**Action:** Provide the IBM Cloud user API key. For details, see\n",
"[documentation](https://cloud.ibm.com/docs/account?topic=account-userapikey&interface=ui)."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# Python program to read\n",
"# json file\n",
"import json\n",
"# Opening JSON file\n",
"f = open('./credentials/api.json')\n",
"# returns JSON object as\n",
"# a dictionary\n",
"data = json.load(f)\n",
"# Ensure you have your API key set in your environment\n",
"#in ./credentials/api.json\n",
"IBM_CLOUD_API = data['IBM_CLOUD_API']\n",
"PROJECT_ID = data['PROJECT_ID']\n",
"# Closing file\n",
"f.close()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"credentials = {\n",
" \"url\": \"https://us-south.ml.cloud.ibm.com\",\n",
" \"apikey\": IBM_CLOUD_API\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Defining the project id\n",
"The API requires project id that provides the context for the call. We will obtain the id from the project in which this notebook runs. Otherwise, please provide the project id.\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"try:\n",
" project_id = os.environ[\"PROJECT_ID\"]\n",
"except KeyError:\n",
" project_id = PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"<a id=\"data\"></a>\n",
"## Train data loading"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Load train and test datasets. At first, training dataset (`train_data`) should be used to work with the models to prepare and tune prompt. Then, test dataset (`test_data`) should be used to calculate the metrics score for selected model, defined prompts and parameters."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"import numpy as np\n",
"import pandas as pd\n",
"# load data\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"filename_data = \"../2-Data/dialogues_embededd.pkl\"\n",
"data = pd.read_pickle(filename_data)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"#data = data.reset_index()\n",
"#data.rename(columns = {'index':'ids'}, inplace = True)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"train_data, test_data= train_test_split(data, test_size=0.05)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(950, 6)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_data.shape"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(50, 6)"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_data.shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"## Build up knowledge base\n",
"\n",
"The current state-of-the-art in RAG is to create dense vector representations of the knowledge base in order to calculate the semantic similarity to a given user query.\n",
"\n",
"We can generate dense vector representations using embedding models. In this notebook, we use [SentenceTransformers](https://www.google.com/search?client=safari&rls=en&q=sentencetransformers&ie=UTF-8&oe=UTF-8) [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) to embed both the knowledge base passages and user queries. `all-MiniLM-L6-v2` is a performant open-source model that is small enough to run locally.\n",
"\n",
"A vector database is optimized for dense vector indexing and retrieval. This notebook uses [Chroma](https://docs.trychroma.com), a user-friendly open-source vector database, licensed under Apache 2.0, which offers good speed and performance with all-MiniLM-L6-v2 embedding model."
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"The dataset we are using is already split into self-contained passages that can be ingested by Chroma. \n",
"\n",
"The size of each passage is limited by the embedding model's context window (which is 256 tokens for `all-MiniLM-L6-v2`)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load knowledge base documents\n",
"\n",
"Load set of documents used further to build knowledge base. "
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"data_root = \"../2-Data/\"\n",
"knowledge_base_dir = f\"{data_root}/knowledge_base\""
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'../2-Data//knowledge_base'"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"knowledge_base_dir"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"#if not os.path.exists(knowledge_base_dir):\n",
"# from zipfile import ZipFile\n",
"# with ZipFile(knowledge_base_dir + \".zip\", 'r') as zObject:\n",
"# zObject.extractall(data_root)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"#documents = pd.read_csv(f\"{knowledge_base_dir}/psgs.tsv\", sep='\\t', header=0)\n",
"#documents['indextext'] = documents['title'].astype(str) + \"\\n\" + documents['text']"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Question</th>\n",
" <th>Patient</th>\n",
" <th>Answer</th>\n",
" <th>combined</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>Q. What does abutment of the nerve root mean?</td>\n",
" <td>Hi doctor,I am just wondering what is abutting...</td>\n",
" <td>Hi. I have gone through your query with dilige...</td>\n",
" <td>Question: Q. What does abutment of the nerve r...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>Q. What should I do to reduce my weight gained...</td>\n",
" <td>Hi doctor, I am a 22-year-old female who was d...</td>\n",
" <td>Hi. You have really done well with the hypothy...</td>\n",
" <td>Question: Q. What should I do to reduce my wei...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Question \\\n",
"0 Q. What does abutment of the nerve root mean? \n",
"1 Q. What should I do to reduce my weight gained... \n",
"\n",
" Patient \\\n",
"0 Hi doctor,I am just wondering what is abutting... \n",
"1 Hi doctor, I am a 22-year-old female who was d... \n",
"\n",
" Answer \\\n",
"0 Hi. I have gone through your query with dilige... \n",
"1 Hi. You have really done well with the hypothy... \n",
"\n",
" combined \n",
"0 Question: Q. What does abutment of the nerve r... \n",
"1 Question: Q. What should I do to reduce my wei... "
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# load & inspect dataset\n",
"df = pd.read_csv(\"../2-Data/dialogues.csv\", sep = '\\t')\n",
"df = df.dropna()#.head(1000)\n",
"df.rename(columns = {'Description':'Question',\"Doctor\":\"Answer\"}, inplace = True)\n",
"#df[\"case\"] = (\" Patient: \" + df.Patient.str.strip()+ \"\\n\" + \"Question: \" + df.Question.str.strip() +)\n",
"#df[\"combined\"] = (\"Question: \" + df.Question.str.strip() + \"\\n\" +\" Patient: \" + df.Patient.str.strip()+ \"\\n\" +\" Answer: \" + df.Answer.str.strip())\n",
"\n",
"df[\"combined\"] = (\"Question: \" + df.Question.str.strip() + \"\\n\" +\" Answer: \" + df.Answer.str.strip())\n",
"\n",
"df.head(2)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(256916, 4)"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df.shape"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"df =df.drop_duplicates()"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(246538, 4)"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df.shape"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"df = df.reset_index()\n",
"df.rename(columns = {'index':'ids'}, inplace = True)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"documents=df"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(246538, 5)"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"documents.shape"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>ids</th>\n",
" <th>Question</th>\n",
" <th>Patient</th>\n",
" <th>Answer</th>\n",
" <th>combined</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>0</td>\n",
" <td>Q. What does abutment of the nerve root mean?</td>\n",
" <td>Hi doctor,I am just wondering what is abutting...</td>\n",
" <td>Hi. I have gone through your query with dilige...</td>\n",
" <td>Question: Q. What does abutment of the nerve r...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>1</td>\n",
" <td>Q. What should I do to reduce my weight gained...</td>\n",
" <td>Hi doctor, I am a 22-year-old female who was d...</td>\n",
" <td>Hi. You have really done well with the hypothy...</td>\n",
" <td>Question: Q. What should I do to reduce my wei...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>2</td>\n",
" <td>Q. I have started to get lots of acne on my fa...</td>\n",
" <td>Hi doctor! I used to have clear skin but since...</td>\n",
" <td>Hi there Acne has multifactorial etiology. Onl...</td>\n",
" <td>Question: Q. I have started to get lots of acn...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>3</td>\n",
" <td>Q. Why do I have uncomfortable feeling between...</td>\n",
" <td>Hello doctor,I am having an uncomfortable feel...</td>\n",
" <td>Hello. The popping and discomfort what you fel...</td>\n",
" <td>Question: Q. Why do I have uncomfortable feeli...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>4</td>\n",
" <td>Q. My symptoms after intercourse threatns me e...</td>\n",
" <td>Hello doctor,Before two years had sex with a c...</td>\n",
" <td>Hello. The HIV test uses a finger prick blood ...</td>\n",
" <td>Question: Q. My symptoms after intercourse thr...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>246533</th>\n",
" <td>256911</td>\n",
" <td>Why is hair fall increasing while using Bontre...</td>\n",
" <td>I am suffering from excessive hairfall. My doc...</td>\n",
" <td>Hello Dear Thanks for writing to us, we are he...</td>\n",
" <td>Question: Why is hair fall increasing while us...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>246534</th>\n",
" <td>256912</td>\n",
" <td>Why was I asked to discontinue Androanagen whi...</td>\n",
" <td>Hi Doctor, I have been having severe hair fall...</td>\n",
" <td>hello, hair4u is combination of minoxid...</td>\n",
" <td>Question: Why was I asked to discontinue Andro...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>246535</th>\n",
" <td>256913</td>\n",
" <td>Can Mintop 5% Lotion be used by women for seve...</td>\n",
" <td>Hi..i hav sever hair loss problem so consulted...</td>\n",
" <td>HI I have evaluated your query thoroughly you...</td>\n",
" <td>Question: Can Mintop 5% Lotion be used by wome...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>246536</th>\n",
" <td>256914</td>\n",
" <td>Is Minoxin 5% lotion advisable instead of Foli...</td>\n",
" <td>Hi, i am 25 year old girl, i am having massive...</td>\n",
" <td>Hello and Welcome to ‘Ask A Doctor’ service.I ...</td>\n",
" <td>Question: Is Minoxin 5% lotion advisable inste...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>246537</th>\n",
" <td>256915</td>\n",
" <td>Are Biotin supplements need to reduce severe h...</td>\n",
" <td>iam having hairfall for a decade.. but fews we...</td>\n",
" <td>you did'nt mention about thyroid problem ...us...</td>\n",
" <td>Question: Are Biotin supplements need to reduc...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>246538 rows × 5 columns</p>\n",
"</div>"
],
"text/plain": [
" ids Question \\\n",
"0 0 Q. What does abutment of the nerve root mean? \n",
"1 1 Q. What should I do to reduce my weight gained... \n",
"2 2 Q. I have started to get lots of acne on my fa... \n",
"3 3 Q. Why do I have uncomfortable feeling between... \n",
"4 4 Q. My symptoms after intercourse threatns me e... \n",
"... ... ... \n",
"246533 256911 Why is hair fall increasing while using Bontre... \n",
"246534 256912 Why was I asked to discontinue Androanagen whi... \n",
"246535 256913 Can Mintop 5% Lotion be used by women for seve... \n",
"246536 256914 Is Minoxin 5% lotion advisable instead of Foli... \n",
"246537 256915 Are Biotin supplements need to reduce severe h... \n",
"\n",
" Patient \\\n",
"0 Hi doctor,I am just wondering what is abutting... \n",
"1 Hi doctor, I am a 22-year-old female who was d... \n",
"2 Hi doctor! I used to have clear skin but since... \n",
"3 Hello doctor,I am having an uncomfortable feel... \n",
"4 Hello doctor,Before two years had sex with a c... \n",
"... ... \n",
"246533 I am suffering from excessive hairfall. My doc... \n",
"246534 Hi Doctor, I have been having severe hair fall... \n",
"246535 Hi..i hav sever hair loss problem so consulted... \n",
"246536 Hi, i am 25 year old girl, i am having massive... \n",
"246537 iam having hairfall for a decade.. but fews we... \n",
"\n",
" Answer \\\n",
"0 Hi. I have gone through your query with dilige... \n",
"1 Hi. You have really done well with the hypothy... \n",
"2 Hi there Acne has multifactorial etiology. Onl... \n",
"3 Hello. The popping and discomfort what you fel... \n",
"4 Hello. The HIV test uses a finger prick blood ... \n",
"... ... \n",
"246533 Hello Dear Thanks for writing to us, we are he... \n",
"246534 hello, hair4u is combination of minoxid... \n",
"246535 HI I have evaluated your query thoroughly you... \n",
"246536 Hello and Welcome to ‘Ask A Doctor’ service.I ... \n",
"246537 you did'nt mention about thyroid problem ...us... \n",
"\n",
" combined \n",
"0 Question: Q. What does abutment of the nerve r... \n",
"1 Question: Q. What should I do to reduce my wei... \n",
"2 Question: Q. I have started to get lots of acn... \n",
"3 Question: Q. Why do I have uncomfortable feeli... \n",
"4 Question: Q. My symptoms after intercourse thr... \n",
"... ... \n",
"246533 Question: Why is hair fall increasing while us... \n",
"246534 Question: Why was I asked to discontinue Andro... \n",
"246535 Question: Can Mintop 5% Lotion be used by wome... \n",
"246536 Question: Is Minoxin 5% lotion advisable inste... \n",
"246537 Question: Are Biotin supplements need to reduc... \n",
"\n",
"[246538 rows x 5 columns]"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"documents"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"documents=documents.head(2000)"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2000, 5)"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"documents.shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Create an embedding function\n",
"\n",
"Note that you can feed a custom embedding function to be used by chromadb. The performance of chromadb may differ depending on the embedding model used."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"class MiniLML6V2EmbeddingFunction(EmbeddingFunction):\n",
" MODEL = SentenceTransformer('all-MiniLM-L6-v2')\n",
" def __call__(self, texts):\n",
" return MiniLML6V2EmbeddingFunction.MODEL.encode(texts).tolist()\n",
"emb_func = MiniLML6V2EmbeddingFunction()"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Set up Chroma upsert\n",
"\n",
"Upserting a document means update the document even if it exists in the database. Otherwise re-inserting a document throws an error. This is useful for experimentation purpose."
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"class ChromaWithUpsert:\n",
" def __init__(\n",
" self,\n",
" name: Optional[str] = \"watsonx_rag_collection\",\n",
" persist_directory:Optional[str]=None,\n",
" embedding_function: Optional[EmbeddingFunction]=None,\n",
" collection_metadata: Optional[Dict] = None,\n",
" ):\n",
" self._client_settings = chromadb.config.Settings()\n",
" if persist_directory is not None:\n",
" self._client_settings = chromadb.config.Settings(\n",
" chroma_db_impl=\"duckdb+parquet\",\n",
" persist_directory=persist_directory,\n",
" )\n",
" self._client = chromadb.Client(self._client_settings)\n",
" self._embedding_function = embedding_function\n",
" self._persist_directory = persist_directory\n",
" self._name = name\n",
" self._collection = self._client.get_or_create_collection(\n",
" name=self._name,\n",
" embedding_function=self._embedding_function\n",
" if self._embedding_function is not None\n",
" else None,\n",
" metadata=collection_metadata,\n",
" )\n",
"\n",
" def upsert_texts(\n",
" self,\n",
" texts: Iterable[str],\n",
" metadata: Optional[List[dict]] = None,\n",
" ids: Optional[List[str]] = None,\n",
" **kwargs: Any,\n",
" ) -> List[str]:\n",
" \"\"\"Run more texts through the embeddings and add to the vectorstore.\n",
" Args:\n",
" :param texts (Iterable[str]): Texts to add to the vectorstore.\n",
" :param metadatas (Optional[List[dict]], optional): Optional list of metadatas.\n",
" :param ids (Optional[List[str]], optional): Optional list of IDs.\n",
" :param metadata: Optional[List[dict]] - optional metadata (such as title, etc.)\n",
" Returns:\n",
" List[str]: List of IDs of the added texts.\n",
" \"\"\"\n",
" # TODO: Handle the case where the user doesn't provide ids on the Collection\n",
" if ids is None:\n",
" import uuid\n",
" ids = [str(uuid.uuid1()) for _ in texts]\n",
" embeddings = None\n",
" self._collection.upsert(\n",
" metadatas=metadata, documents=texts, ids=ids\n",
" )\n",
" return ids\n",
"\n",
" def is_empty(self):\n",
" return self._collection.count()==0\n",
"\n",
" def persist(self):\n",
" self._client.persist()\n",
"\n",
" def query(self, query_texts:str, n_results:int=5):\n",
" \"\"\"\n",
" Returns the closests vector to the question vector\n",
" :param query_texts: the question\n",
" :param n_results: number of results to generate\n",
" :return: the closest result to the given question\n",
" \"\"\"\n",
" return self._collection.query(query_texts=query_texts, n_results=n_results)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: total: 93.8 ms\n",
"Wall time: 93 ms\n"
]
}
],
"source": [
"%%time\n",
"chroma = ChromaWithUpsert(\n",
" name=f\"nq910_minilm6v2\",\n",
" embedding_function=emb_func, # you can have something here using /embed endpoint\n",
" persist_directory=knowledge_base_dir,\n",
")\n",
"if chroma.is_empty():\n",
" _ = chroma.upsert_texts(\n",
" texts=documents.combined.tolist(),\n",
" # we handle tokenization, embedding, and indexing automatically. \n",
" #You can skip that and add your own embeddings as well\n",
" metadata=[{'Question': Question,\n",
" 'Patient':Patient,\n",
" 'ids': ids}\n",
" for (Question,Patient,ids) in\n",
" zip(documents.Question,documents.Patient, documents.ids)], # filter on these!\n",
" ids=[str(i) for i in documents.ids], # unique for each doc\n",
" )\n",
" chroma.persist()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Embed and index documents with Chroma\n",
"\n",
"**Note: Could take several minutes if you don't have pre-built indices**"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: total: 20.1 s\n",
"Wall time: 16.3 s\n"
]
}
],
"source": [
"%%time\n",
"chroma = ChromaWithUpsert(\n",
" name=f\"nq910_minilm6v2\",\n",
" embedding_function=emb_func, # you can have something here using /embed endpoint\n",
" persist_directory=knowledge_base_dir,\n",
")\n",
"if chroma.is_empty():\n",
" _ = chroma.upsert_texts(\n",
" texts=documents.combined.tolist(),\n",
" # we handle tokenization, embedding, and indexing automatically. \n",
" #You can skip that and add your own embeddings as well\n",
" metadata=[{'Question': Question, \n",
" 'ids': ids}\n",
" for (Question,ids) in\n",
" zip(documents.Question, documents.ids)], # filter on these!\n",
" ids=[str(i) for i in documents.ids], # unique for each doc\n",
" )\n",
" chroma.persist()"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"<a id=\"models\"></a>\n",
"## Foundation Models on Watsonx"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"You need to specify `model_id` that will be used for inferencing."
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"**Action**: Use `FLAN_UL2` model."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [],
"source": [
"from ibm_watson_machine_learning.foundation_models.utils.enums import ModelTypes"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"model_id = ModelTypes.FLAN_UL2"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"<a id=\"predict\"></a>\n",
"## Generate a retrieval-augmented response to a question"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Select questions\n",
"\n",
"Get questions from the previously loaded test dataset."
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Q. Every time I eat spicy food, I poop blood. Why?\n",
"Q. Will Kalarchikai cure multiple ovarian cysts in PCOD?\n",
"Q. Please enlighten me on non-invasive procedures to detect prostate cancer.?\n",
"Q. My sciatica is heavy after a minor herniated disc L4 or L5. Why?\n",
"Q. I feel as if the skin over my belly button is firm. Is it hernia?\n",
"Q. A white patch has been formed at the tip of the penis associated with skin tightness. Why?\n",
"Q. I masturbate only by rubbing the tip of the penis. Is it a wrong way?\n",
"Q. Every time I eat spicy food, I poop blood. Why?\n",
"Q. Please provide opinion on my complete blood count report.?\n",
"Q. My child got hurt while playing. Can we use T-Bact or Neosporin ointment?\n",
"Q. Please comment on the severity of my wife's wrist x-ray.?\n",
"Q. Why am I having extreme bloating, abdominal pain, and fatigue with scaly marks?\n",
"Q. I masturbate only by rubbing the tip of the penis. Is it a wrong way?\n",
"Q. What can be done for tender and itchy red spots on hands?\n",
"Q. Will Kalarchikai cure multiple ovarian cysts in PCOD?\n",
"Q. Does swollen lymphnode everywhere in the body mean cancer?\n",
"Q. What are the tests I have to undergo after having unprotected oral sex?\n",
"Q. Every time I eat spicy food, I poop blood. Why?\n",
"Q. Is Bimatoprost safe enough for optical nerve damage?\n",
"Q. Every time I eat spicy food, I poop blood. Why?\n",
"Q. 18 weeks pregnant woman used spray pesticide. Is it harmful for the baby?\n",
"Q. I masturbate only by rubbing the tip of the penis. Is it a wrong way?\n",
"Q. Delayed periods even after taking Gestin. What is the reason?\n",
"Q. My mother had TB meningitis and is now suspected to have tubercular spine. Help.?\n",
"Q. I masturbate only by rubbing the tip of the penis. Is it a wrong way?\n",
"Q. I masturbate only by rubbing the tip of the penis. Is it a wrong way?\n",
"Q. I had a surgery which ended up with some failures. What can I do to fix it?\n",
"Q. I am having small black spots on my toenail. Does it indicate melanoma?\n",
"Q. What is the cause for itching of face and chest after sex?\n",
"Q. My left hip is completely fused. Can we have a healthy baby?\n",
"Q. Should I continue the Olanzapine as I had a blackout episode when I was drunken?\n",
"Q. I am suffering from stomach cramps and diarrhea. What should I do?\n",
"Q. I am consuming Codeine. Will this affect conceiving?\n",
"Q. Is it normal to have cobblestone appearance at the back of throat after tonsillectomy?\n",
"Q. After lying on stomach for 20 minutes, I get most intense headache. Is this brain aneurysm?\n",
"Q. What are the chances of me to get pregnant after taking i-pill?\n",
"Q. Are my symptoms due to HIV infection? I had a high-risk exposure 15 months ago.?\n",
"Q. Will Nano-Leo give permanent solution for erection problem?\n",
"Q. I have erectile dysfunction inspite of having L-Arginine. Kindly advice.?\n",
"Q. What does abutment of the nerve root mean?\n",
"Q. Every time I eat spicy food, I poop blood. Why?\n",
"Q. Are my symptoms suggestive of schizophrenia or OCD?\n",
"Q. Every time I eat spicy food, I poop blood. Why?\n",
"Q. Why do I get wrinkles on the glans penis after using Lobate cream for pimples?\n",
"Q. Will Nano-Leo give permanent solution for erection problem?\n",
"Q. Sometimes, I get palpitations, low BP and low sugar blackouts. Please advise.?\n",
"Q. Will Nano-Leo give permanent solution for erection problem?\n",
"Q. I masturbate only by rubbing the tip of the penis. Is it a wrong way?\n",
"Q. Why is there a discomfort in my gums where the wisdom tooth is piercing them?\n",
"Q. Does side effect of the anxiety drug diminishes the memory?\n"
]
}
],
"source": [
"question_texts = [q.strip(\"?\") + \"?\" for q in test_data['Question'].tolist()]\n",
"print(\"\\n\".join(question_texts))"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Retrieve relevant context\n",
"\n",
"Fetch paragraphs similar to the question."
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"relevant_contexts = []\n",
"\n",
"for question_text in question_texts:\n",
" relevant_chunks = chroma.query(\n",
" query_texts=[question_text],\n",
" n_results=5,\n",
" )\n",
" relevant_contexts.append(relevant_chunks)"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Get the set of chunks for one of the questions."
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"=========\n",
"Paragraph index : 10\n",
"Paragraph : Question: Q. Every time I eat spicy food, I poop blood. Why?\n",
" Answer: Hello. I have gone through your information and test reports (attachment removed to protect patient identity). So, in view of that, there are a couple of things that I can opine upon: Hope that helps. For more information consult a general surgeon online -->\n",
"Distance : 0.23510286211967468\n",
"=========\n",
"Paragraph index : 2968\n",
"Paragraph : Question: Q. Why is there burning sensation after passing stools?\n",
" Answer: Hello. Intake of spicy food may cause burning sensation and irritation of anal mucosa which may lead to a burning pain during defecation. It is due to the spiciness of the food. You may try yogurt, cucumber, tender coconut water, probiotic capsules, buttermilk. Use tablet Nexium before breakfast for one week. Avoid spicy food intake. If symptoms do not improve, please consult a physician or post me a query.\n",
"Distance : 0.7934628129005432\n",
"=========\n",
"Paragraph index : 397\n",
"Paragraph : Question: Q. Can you explain the reason behind burning sensation of gums?\n",
" Answer: Hi. Hurting of gums while taking spicy food might be due to the following causes: 1. Gingivitis (swelling and inflammation of the gums) - Swollen gums may be painful and may cause burning sensation and pain while taking hot and spicy food. Gingivitis occurs due to either plaque or other debris accumulating around the teeth and gums. Also hormonal changes occurring during menstrual cycle can cause swollen and painful gums. Any medicines taken for medical issues like hypertension, epilepsy, etc., also cause gum changes and swelling. 2. Any ulcers in the mouth will get hurt while taking hot and spicy food. Ulcers might occur due to faulty tooth brushing techniques, usage of toothbrushes with hard bristles, stress, sharp tooth hurting the tissues, any dental appliances or ill-fitting dentures. 3. Any abscess related to infected tooth might also hurt while taking spicy food. But, you have mentioned that you do not have any cavities or teeth issues. Have you been examined by a dentist regarding this? 4. Any impacted tooth (teeth that remain unerupted due to inadequate space inside the mouth or remain inside the bone itself) may develop swelling of gums around it. When the opposing teeth impinges on this swollen tissue while taking spicy food it gets hurt. 5. Hypersensitivity reactions may occur to certain foods. This might cause swelling, reddening and burning sensation of the mouth. This may occur due to some food additives. 6. Habits like smoking and usage of tobacco products may also cause burning sensation while consuming spicy and hot food. 7. Dental procedures like scaling (cleaning of teeth) might cause minor tissue injuries. These hurt and cause burning sensation while taking hot and spicy food. But, this heals in 4-5 days after cleaning. In your case, this might not be the reason, as you have undergone scaling before 2-3 years. 1. Get dental scaling done, if you have any plaque or calculus deposits causing swollen gums. 2. Get your oral cavity examined by your dentist, for any ulcers, abscesses, infected teeth and impacted teeth. 3. Also get checked for any sharp teeth and any dental appliances or ill-fitting dentures. If found, sharp teeth have to be trimmed and reduced, and ill-fitting dentures and dental appliances have to be corrected immediately. 1. Kindly make a note if you develop any gum swelling, redness or bleeding gums during your periods. 2. Use toothbrushes with soft bristles for brushing your teeth. Also follow the proper brushing technique for brushing your teeth. 3. Make a note whenever your gum hurts and what foods hurt your gums. Check if any food causes the same issue repeatedly. In case, if that food contains some additive that causes hypersensitive reaction, then you may have to avoid that particular food in future. 4.Quit habits like smoking or usage of other tobacco products (in case you do). For further information consult a dentist online.--->\n",
"Distance : 0.9654074907302856\n",
"=========\n",
"Paragraph index : 2873\n",
"Paragraph : Question: Q. How can blood in stool be managed?\n",
" Answer: Hello. You may be suffering from constipation with internal hemorrhoids or fissure in ano. You have to avoid spicy food, low fiber diet. Use high fiber diet with plenty of liquids. Use Metamucil or Benefiber for stool bulk formation. Do regular exercise and yoga. If symptoms not improved you may use syrup Lactulose 30 ml after dinner for five days if necessary. If symptoms do not improve or develop an allergy to the above drug, please consult your physician. He will examine and treat you accordingly. Take care.\n",
"Distance : 0.998435914516449\n",
"=========\n",
"Paragraph index : 1547\n",
"Paragraph : Question: Q. I have a muscular thing right out of my anus. What it could be?\n",
" Answer: Hello. It is anal hemorrhoids (attachment removed to protect patient identity), and it is very painful. You may be suffering from constipation, or you must have been eating very spicy food. The treatment is sitz bath, and it means you have to sit in a tub full of warm water. It gets relieved, and you have to do this for two to three times a day. Kindly consult your doctor to discuss the suggestion and take the treatment with consent. You may apply ointment Pilex over the area. Stop eating spicy food and take syrup Duphalac (Lactulose) two spoons daily at bedtime to avoid constipation. If it is not relieved, then you have to consult a general surgeon.\n",
"Distance : 1.0564740896224976\n"
]
}
],
"source": [
"sample_chunks = relevant_contexts[0]\n",
"for i, chunk in enumerate(sample_chunks['documents'][0]):\n",
" print(\"=========\")\n",
" print(\"Paragraph index : \", sample_chunks['ids'][0][i])\n",
" print(\"Paragraph : \", chunk)\n",
" print(\"Distance : \", sample_chunks['distances'][0][i])"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Feed the context and the questions to `watsonx.ai` model."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define instructions for the model.\n",
"\n",
"**Note:** Please start with finding better prompts using small subset of training records (under `train_data` variable). Make sure to not run an inference of all of `train_data`, as it'll take a long time to get the results. To get a sample from `train_data`, you can use e.g.`train_data.head(n=10)` to get first 10 records, or `train_data.sample(n=10)` to get random 10 records. Only once you have identified the best performing prompt, update this notebook to use the prompt and compute the metrics on the test data.\n",
"\n",
"**Action:** Please edit the below cell and add your own prompt here. In the below prompt, we have the instruction (first sentence) and one example included in the prompt. If you want to change the prompt or add your own examples or more examples, please change the below prompt accordingly."
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"def make_prompt(context, question_text):\n",
" return (f\"Please answer the following.\\n\"\n",
" + f\"{context}:\\n\\n\"\n",
" + f\"{question_text}\")\n",
"\n",
"prompt_texts = []\n",
"\n",
"for relevant_context, question_text in zip(relevant_contexts, question_texts):\n",
" context = \"\\n\\n\\n\".join(relevant_context[\"documents\"][0])\n",
" prompt_text = make_prompt(context, question_text)\n",
" prompt_texts.append(prompt_text)"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Inspect prompt for sample question."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Please answer the following.\n",
"Question: Q. Every time I eat spicy food, I poop blood. Why?\n",
" Answer: Hello. I have gone through your information and test reports (attachment removed to protect patient identity). So, in view of that, there are a couple of things that I can opine upon: Hope that helps. For more information consult a general surgeon online -->\n",
"\n",
"\n",
"Question: Q. Why is there burning sensation after passing stools?\n",
" Answer: Hello. Intake of spicy food may cause burning sensation and irritation of anal mucosa which may lead to a burning pain during defecation. It is due to the spiciness of the food. You may try yogurt, cucumber, tender coconut water, probiotic capsules, buttermilk. Use tablet Nexium before breakfast for one week. Avoid spicy food intake. If symptoms do not improve, please consult a physician or post me a query.\n",
"\n",
"\n",
"Question: Q. Can you explain the reason behind burning sensation of gums?\n",
" Answer: Hi. Hurting of gums while taking spicy food might be due to the following causes: 1. Gingivitis (swelling and inflammation of the gums) - Swollen gums may be painful and may cause burning sensation and pain while taking hot and spicy food. Gingivitis occurs due to either plaque or other debris accumulating around the teeth and gums. Also hormonal changes occurring during menstrual cycle can cause swollen and painful gums. Any medicines taken for medical issues like hypertension, epilepsy, etc., also cause gum changes and swelling. 2. Any ulcers in the mouth will get hurt while taking hot and spicy food. Ulcers might occur due to faulty tooth brushing techniques, usage of toothbrushes with hard bristles, stress, sharp tooth hurting the tissues, any dental appliances or ill-fitting dentures. 3. Any abscess related to infected tooth might also hurt while taking spicy food. But, you have mentioned that you do not have any cavities or teeth issues. Have you been examined by a dentist regarding this? 4. Any impacted tooth (teeth that remain unerupted due to inadequate space inside the mouth or remain inside the bone itself) may develop swelling of gums around it. When the opposing teeth impinges on this swollen tissue while taking spicy food it gets hurt. 5. Hypersensitivity reactions may occur to certain foods. This might cause swelling, reddening and burning sensation of the mouth. This may occur due to some food additives. 6. Habits like smoking and usage of tobacco products may also cause burning sensation while consuming spicy and hot food. 7. Dental procedures like scaling (cleaning of teeth) might cause minor tissue injuries. These hurt and cause burning sensation while taking hot and spicy food. But, this heals in 4-5 days after cleaning. In your case, this might not be the reason, as you have undergone scaling before 2-3 years. 1. Get dental scaling done, if you have any plaque or calculus deposits causing swollen gums. 2. Get your oral cavity examined by your dentist, for any ulcers, abscesses, infected teeth and impacted teeth. 3. Also get checked for any sharp teeth and any dental appliances or ill-fitting dentures. If found, sharp teeth have to be trimmed and reduced, and ill-fitting dentures and dental appliances have to be corrected immediately. 1. Kindly make a note if you develop any gum swelling, redness or bleeding gums during your periods. 2. Use toothbrushes with soft bristles for brushing your teeth. Also follow the proper brushing technique for brushing your teeth. 3. Make a note whenever your gum hurts and what foods hurt your gums. Check if any food causes the same issue repeatedly. In case, if that food contains some additive that causes hypersensitive reaction, then you may have to avoid that particular food in future. 4.Quit habits like smoking or usage of other tobacco products (in case you do). For further information consult a dentist online.--->\n",
"\n",
"\n",
"Question: Q. How can blood in stool be managed?\n",
" Answer: Hello. You may be suffering from constipation with internal hemorrhoids or fissure in ano. You have to avoid spicy food, low fiber diet. Use high fiber diet with plenty of liquids. Use Metamucil or Benefiber for stool bulk formation. Do regular exercise and yoga. If symptoms not improved you may use syrup Lactulose 30 ml after dinner for five days if necessary. If symptoms do not improve or develop an allergy to the above drug, please consult your physician. He will examine and treat you accordingly. Take care.\n",
"\n",
"\n",
"Question: Q. I have a muscular thing right out of my anus. What it could be?\n",
" Answer: Hello. It is anal hemorrhoids (attachment removed to protect patient identity), and it is very painful. You may be suffering from constipation, or you must have been eating very spicy food. The treatment is sitz bath, and it means you have to sit in a tub full of warm water. It gets relieved, and you have to do this for two to three times a day. Kindly consult your doctor to discuss the suggestion and take the treatment with consent. You may apply ointment Pilex over the area. Stop eating spicy food and take syrup Duphalac (Lactulose) two spoons daily at bedtime to avoid constipation. If it is not relieved, then you have to consult a general surgeon.:\n",
"\n",
"Q. Every time I eat spicy food, I poop blood. Why?\n"
]
}
],
"source": [
"print(prompt_texts[0])"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Defining the model parameters\n",
"We need to provide a set of model parameters that will influence the result:"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames as GenParams\n",
"from ibm_watson_machine_learning.foundation_models.utils.enums import DecodingMethods\n",
"\n",
"parameters = {\n",
" GenParams.DECODING_METHOD: DecodingMethods.GREEDY,\n",
" GenParams.MIN_NEW_TOKENS: 1,\n",
" GenParams.MAX_NEW_TOKENS: 200\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Initialize the `Model` class."
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"#this cell should never fail, and will produce no output\n",
"import requests\n",
"\n",
"def getBearer(apikey):\n",
" form = {'apikey': apikey, 'grant_type': \"urn:ibm:params:oauth:grant-type:apikey\"}\n",
" print(\"About to create bearer\")\n",
"# print(form)\n",
" response = requests.post(\"https://iam.cloud.ibm.com/oidc/token\", data = form)\n",
" if response.status_code != 200:\n",
" print(\"Bad response code retrieving token\")\n",
" raise Exception(\"Failed to get token, invalid status\")\n",
" json = response.json()\n",
" if not json:\n",
" print(\"Invalid/no JSON retrieving token\")\n",
" raise Exception(\"Failed to get token, invalid response\")\n",
" print(\"Bearer retrieved\")\n",
" return json.get(\"access_token\")"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"About to create bearer\n",
"Bearer retrieved\n"
]
}
],
"source": [
"credentials[\"token\"] = getBearer(credentials[\"apikey\"])"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"from ibm_watson_machine_learning.foundation_models import Model\n",
"model = Model(\n",
" model_id=model_id,\n",
" params=parameters,\n",
" credentials=credentials,\n",
" project_id=project_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"### Generate a retrieval-augmented response"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** Execution of this cell could take several minutes."
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Please answer the following.\\nQuestion: Q. Every time I eat spicy food, I poop blood. Why?\\n Answer: Hello. I have gone through your information and test reports (attachment removed to protect patient identity). So, in view of that, there are a couple of things that I can opine upon: Hope that helps. For more information consult a general surgeon online -->\\n\\n\\nQuestion: Q. Why is there burning sensation after passing stools?\\n Answer: Hello. Intake of spicy food may cause burning sensation and irritation of anal mucosa which may lead to a burning pain during defecation. It is due to the spiciness of the food. You may try yogurt, cucumber, tender coconut water, probiotic capsules, buttermilk. Use tablet Nexium before breakfast for one week. Avoid spicy food intake. If symptoms do not improve, please consult a physician or post me a query.\\n\\n\\nQuestion: Q. Can you explain the reason behind burning sensation of gums?\\n Answer: Hi. Hurting of gums while taking spicy food might be due to the following causes: 1. Gingivitis (swelling and inflammation of the gums) - Swollen gums may be painful and may cause burning sensation and pain while taking hot and spicy food. Gingivitis occurs due to either plaque or other debris accumulating around the teeth and gums. Also hormonal changes occurring during menstrual cycle can cause swollen and painful gums. Any medicines taken for medical issues like hypertension, epilepsy, etc., also cause gum changes and swelling. 2. Any ulcers in the mouth will get hurt while taking hot and spicy food. Ulcers might occur due to faulty tooth brushing techniques, usage of toothbrushes with hard bristles, stress, sharp tooth hurting the tissues, any dental appliances or ill-fitting dentures. 3. Any abscess related to infected tooth might also hurt while taking spicy food. But, you have mentioned that you do not have any cavities or teeth issues. Have you been examined by a dentist regarding this? 4. Any impacted tooth (teeth that remain unerupted due to inadequate space inside the mouth or remain inside the bone itself) may develop swelling of gums around it. When the opposing teeth impinges on this swollen tissue while taking spicy food it gets hurt. 5. Hypersensitivity reactions may occur to certain foods. This might cause swelling, reddening and burning sensation of the mouth. This may occur due to some food additives. 6. Habits like smoking and usage of tobacco products may also cause burning sensation while consuming spicy and hot food. 7. Dental procedures like scaling (cleaning of teeth) might cause minor tissue injuries. These hurt and cause burning sensation while taking hot and spicy food. But, this heals in 4-5 days after cleaning. In your case, this might not be the reason, as you have undergone scaling before 2-3 years. 1. Get dental scaling done, if you have any plaque or calculus deposits causing swollen gums. 2. Get your oral cavity examined by your dentist, for any ulcers, abscesses, infected teeth and impacted teeth. 3. Also get checked for any sharp teeth and any dental appliances or ill-fitting dentures. If found, sharp teeth have to be trimmed and reduced, and ill-fitting dentures and dental appliances have to be corrected immediately. 1. Kindly make a note if you develop any gum swelling, redness or bleeding gums during your periods. 2. Use toothbrushes with soft bristles for brushing your teeth. Also follow the proper brushing technique for brushing your teeth. 3. Make a note whenever your gum hurts and what foods hurt your gums. Check if any food causes the same issue repeatedly. In case, if that food contains some additive that causes hypersensitive reaction, then you may have to avoid that particular food in future. 4.Quit habits like smoking or usage of other tobacco products (in case you do). For further information consult a dentist online.--->\\n\\n\\nQuestion: Q. How can blood in stool be managed?\\n Answer: Hello. You may be suffering from constipation with internal hemorrhoids or fissure in ano. You have to avoid spicy food, low fiber diet. Use high fiber diet with plenty of liquids. Use Metamucil or Benefiber for stool bulk formation. Do regular exercise and yoga. If symptoms not improved you may use syrup Lactulose 30 ml after dinner for five days if necessary. If symptoms do not improve or develop an allergy to the above drug, please consult your physician. He will examine and treat you accordingly. Take care.\\n\\n\\nQuestion: Q. I have a muscular thing right out of my anus. What it could be?\\n Answer: Hello. It is anal hemorrhoids (attachment removed to protect patient identity), and it is very painful. You may be suffering from constipation, or you must have been eating very spicy food. The treatment is sitz bath, and it means you have to sit in a tub full of warm water. It gets relieved, and you have to do this for two to three times a day. Kindly consult your doctor to discuss the suggestion and take the treatment with consent. You may apply ointment Pilex over the area. Stop eating spicy food and take syrup Duphalac (Lactulose) two spoons daily at bedtime to avoid constipation. If it is not relieved, then you have to consult a general surgeon.:\\n\\nQ. Every time I eat spicy food, I poop blood. Why?']"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prompt_texts[:1]"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(prompt_texts[:1])"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"results = []\n",
"for prompt_text in prompt_texts[:1]:\n",
" results.append(model.generate_text(prompt=prompt_text))"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
"#test_data"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Question = Q. Every time I eat spicy food, I poop blood. Why?\n",
"Answer = Hello. I have gone through your information and test reports (attachment removed to protect patient identity). So, in view of that, there are a couple of things that I can opine upon: Hope that helps. For more information consult a general surgeon online -->\n",
"Expected Answer(s) (may not be appear with exact wording in the dataset) = Hello. I have gone through your information and test reports (attachment removed to protect patient identity). So, in view of that, there are a couple of things that I can opine upon: Hope that helps. For more information consult a general surgeon online -->\n",
"\n",
"\n"
]
}
],
"source": [
"for idx, result in enumerate(results):\n",
" print(\"Question = \", test_data.iloc[idx]['Question'])\n",
" print(\"Answer = \", result)\n",
" print(\"Expected Answer(s) (may not be appear with exact wording in the dataset) = \", test_data.iloc[idx]['Answer'])\n",
" print(\"\\n\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"<a id=\"score\"></a>\n",
"## Calculate rougeL metric"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this sample notebook `rouge_score` module was used for rougeL calculation."
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"#### Rouge Metric"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"**Note:** The Rouge (Recall-Oriented Understudy for Gisting Evaluation) metric is a set of evaluation measures used in natural language processing (NLP) and specifically in text summarization and machine translation tasks. The Rouge metrics are designed to assess the quality of generated summaries or translations by comparing them to one or more reference texts.\n",
"\n",
"The main idea behind Rouge is to measure the overlap between the generated summary (or translation) and the reference text(s) in terms of n-grams or longest common subsequences. By calculating recall, precision, and F1 scores based on these overlapping units, Rouge provides a quantitative assessment of the summary's content overlap with the reference(s).\n",
"\n",
"Rouge-1 focuses on individual word overlap, Rouge-2 considers pairs of consecutive words, and Rouge-L takes into account the ordering of words and phrases. These metrics provide different perspectives on the similarity between two texts and can be used to evaluate different aspects of summarization or text generation models."
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"from rouge_score import rouge_scorer\n",
"from collections import defaultdict\n",
"import numpy as np\n",
"\n",
"def get_rouge_score(predictions, references):\n",
" scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL', 'rougeLsum'])\n",
" aggregate_score = defaultdict(list)\n",
"\n",
" for result, ref in zip(predictions, references):\n",
" for key, val in scorer.score(result, ref).items():\n",
" aggregate_score[key].append(val.fmeasure)\n",
"\n",
" scores = {}\n",
" for key in aggregate_score:\n",
" scores[key] = np.mean(aggregate_score[key])\n",
" \n",
" return scores"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'rouge1': 1.0, 'rouge2': 1.0, 'rougeL': 1.0, 'rougeLsum': 1.0}\n"
]
}
],
"source": [
"print(get_rouge_score(results, test_data.Answer))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python3 (GPT)",
"language": "python",
"name": "gpt"
},
"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.10.11"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|