{ "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": [ "\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": [ "\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": [ "
\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", "
QuestionPatientAnswercombined
0Q. What does abutment of the nerve root mean?Hi doctor,I am just wondering what is abutting...Hi. I have gone through your query with dilige...Question: Q. What does abutment of the nerve r...
1Q. What should I do to reduce my weight gained...Hi doctor, I am a 22-year-old female who was d...Hi. You have really done well with the hypothy...Question: Q. What should I do to reduce my wei...
\n", "
" ], "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": [ "
\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", " \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", " \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", "
idsQuestionPatientAnswercombined
00Q. What does abutment of the nerve root mean?Hi doctor,I am just wondering what is abutting...Hi. I have gone through your query with dilige...Question: Q. What does abutment of the nerve r...
11Q. What should I do to reduce my weight gained...Hi doctor, I am a 22-year-old female who was d...Hi. You have really done well with the hypothy...Question: Q. What should I do to reduce my wei...
22Q. I have started to get lots of acne on my fa...Hi doctor! I used to have clear skin but since...Hi there Acne has multifactorial etiology. Onl...Question: Q. I have started to get lots of acn...
33Q. Why do I have uncomfortable feeling between...Hello doctor,I am having an uncomfortable feel...Hello. The popping and discomfort what you fel...Question: Q. Why do I have uncomfortable feeli...
44Q. My symptoms after intercourse threatns me e...Hello doctor,Before two years had sex with a c...Hello. The HIV test uses a finger prick blood ...Question: Q. My symptoms after intercourse thr...
..................
246533256911Why is hair fall increasing while using Bontre...I am suffering from excessive hairfall. My doc...Hello Dear Thanks for writing to us, we are he...Question: Why is hair fall increasing while us...
246534256912Why was I asked to discontinue Androanagen whi...Hi Doctor, I have been having severe hair fall...hello, hair4u is combination of minoxid...Question: Why was I asked to discontinue Andro...
246535256913Can Mintop 5% Lotion be used by women for seve...Hi..i hav sever hair loss problem so consulted...HI I have evaluated your query thoroughly you...Question: Can Mintop 5% Lotion be used by wome...
246536256914Is Minoxin 5% lotion advisable instead of Foli...Hi, i am 25 year old girl, i am having massive...Hello and Welcome to ‘Ask A Doctor’ service.I ...Question: Is Minoxin 5% lotion advisable inste...
246537256915Are Biotin supplements need to reduce severe h...iam having hairfall for a decade.. but fews we...you did'nt mention about thyroid problem ...us...Question: Are Biotin supplements need to reduc...
\n", "

246538 rows × 5 columns

\n", "
" ], "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": [ "\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": [ "\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": [ "\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 }