{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import zipfile\n", "import io\n", "import requests\n", "import json\n", "import pandas as pd\n", "from dotenv import load_dotenv\n", "import os\n", "from typing import List\n", "from langchain.embeddings.openai import OpenAIEmbeddings\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "from langchain.chains import ConversationalRetrievalChain\n", "from langchain.chat_models import ChatOpenAI\n", "from langchain.prompts.chat import (\n", " ChatPromptTemplate,\n", " SystemMessagePromptTemplate,\n", " HumanMessagePromptTemplate,\n", ")\n", "from langchain.docstore.document import Document\n", "from langchain.memory import ChatMessageHistory, ConversationBufferMemory\n", "from langchain.document_loaders import DataFrameLoader\n", "from langchain.vectorstores import Qdrant\n", "from qdrant_client import QdrantClient" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "load_dotenv()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "system_template = \"\"\"\n", "You are PharmAssistAI, an AI assistant for pharmacists and pharmacy students. Use the following pieces of context to answer the user's question.\n", "\n", "If you don't know the answer, simply state that you don't have enough information to provide an answer. Do not attempt to make up an answer.\n", "\n", "ALWAYS include a \"SOURCES\" section at the end of your response, referencing the specific documents from which you derived your answer. \n", "\n", "If the user greets you with a greeting like \"Hi\", \"Hello\", or \"How are you\", respond in a friendly manner.\n", "\n", "Example response format:\n", "\n", "SOURCES: \n", "\n", "Begin!\n", "----------------\n", "{summaries}\n", "\"\"\"\n", "\n", "messages = [\n", " SystemMessagePromptTemplate.from_template(system_template),\n", " HumanMessagePromptTemplate.from_template(\"{question}\"),\n", "]\n", "prompt = ChatPromptTemplate.from_messages(messages)\n", "chain_type_kwargs = {\"prompt\": prompt}" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/raj/miniconda3/envs/llmops-course/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The class `OpenAIEmbeddings` was deprecated in LangChain 0.0.9 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import OpenAIEmbeddings`.\n", " warn_deprecated(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Collection 'fda_drugs' is present.\n" ] } ], "source": [ "embedding_model = OpenAIEmbeddings(model=\"text-embedding-3-small\")\n", "\n", "QDRANT_API_KEY = os.environ.get(\"QDRANT_API_KEY\")\n", "QDRANT_CLUSTER_URL = os.environ.get(\"QDRANT_CLUSTER_URL\")\n", "\n", "qdrant_client = QdrantClient(url=QDRANT_CLUSTER_URL, api_key=QDRANT_API_KEY, timeout=60)\n", "\n", "response = qdrant_client.get_collections()\n", "collection_names = [collection.name for collection in response.collections]\n", "\n", "if \"fda_drugs\" not in collection_names:\n", " print(\"Collection 'fda_drugs' is not present.\")\n", " \n", " # Download and process the FDA drug data\n", " url = \"https://download.open.fda.gov/drug/label/drug-label-0001-of-0012.json.zip\"\n", " response = requests.get(url)\n", " zip_file = zipfile.ZipFile(io.BytesIO(response.content))\n", " json_file = zip_file.open(zip_file.namelist()[0])\n", " data = json.load(json_file)\n", " \n", " df = pd.json_normalize(data['results'])\n", " selected_drugs = df\n", " \n", " # Define metadata fields and text fields\n", " metadata_fields = ['openfda.brand_name', 'openfda.generic_name', 'openfda.manufacturer_name',\n", " 'openfda.product_type', 'openfda.route', 'openfda.substance_name',\n", " 'openfda.rxcui', 'openfda.spl_id', 'openfda.package_ndc']\n", " text_fields = ['description', 'indications_and_usage', 'contraindications',\n", " 'warnings', 'adverse_reactions', 'dosage_and_administration']\n", " \n", " selected_drugs[text_fields] = selected_drugs[text_fields].fillna('')\n", " selected_drugs['content'] = selected_drugs[text_fields].apply(lambda x: ' '.join(x.astype(str)), axis=1)\n", " \n", " loader = DataFrameLoader(selected_drugs, page_content_column='content')\n", " drug_docs = loader.load()\n", " \n", " for doc, row in zip(drug_docs, selected_drugs.to_dict(orient='records')):\n", " metadata = {}\n", " for field in metadata_fields:\n", " value = row.get(field)\n", " if isinstance(value, list):\n", " value = ', '.join(str(v) for v in value if pd.notna(v))\n", " elif pd.isna(value):\n", " value = 'Not Available'\n", " metadata[field] = value\n", " doc.metadata = metadata\n", " \n", " text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)\n", " split_drug_docs = text_splitter.split_documents(drug_docs)\n", " \n", " qdrant_vectorstore = Qdrant.from_documents(\n", " split_drug_docs,\n", " embedding_model,\n", " url=QDRANT_CLUSTER_URL,\n", " api_key=QDRANT_API_KEY,\n", " collection_name=\"fda_drugs\"\n", " )\n", "else:\n", " print(\"Collection 'fda_drugs' is present.\")\n", " qdrant_vectorstore = Qdrant.construct_instance(\n", " texts=[\"\"],\n", " embedding=embedding_model,\n", " url=QDRANT_CLUSTER_URL,\n", " api_key=QDRANT_API_KEY,\n", " collection_name=\"fda_drugs\"\n", " )" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "def generate_answer(query):\n", " message_history = ChatMessageHistory()\n", " memory = ConversationBufferMemory(\n", " memory_key=\"chat_history\",\n", " output_key=\"answer\",\n", " chat_memory=message_history,\n", " return_messages=True,\n", " )\n", "\n", " chain = ConversationalRetrievalChain.from_llm(\n", " ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0, streaming=True),\n", " chain_type=\"stuff\",\n", " retriever=qdrant_vectorstore.as_retriever(),\n", " memory=memory,\n", " return_source_documents=True,\n", " )\n", "\n", "\n", " res = chain.invoke(query)\n", " answer = res[\"answer\"]\n", " source_documents = res[\"source_documents\"]\n", "\n", "\n", " text_elements = []\n", " if source_documents:\n", " for source_idx, source_doc in enumerate(source_documents):\n", " source_name = f\"source_{source_idx}\"\n", " text_elements.append(\n", " (source_doc.page_content, source_name)\n", " )\n", " source_names = [text_el[1] for text_el in text_elements]\n", "\n", "\n", "\n", " return answer, text_elements" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "When taking Metformin, you should be cautious about excessive alcohol intake, both acute and chronic, as alcohol can potentiate the effects of Metformin on lactate metabolism. Additionally, Metformin should be temporarily discontinued before any intravascular radiocontrast study or surgical procedure. Patients with clinical or laboratory evidence of hepatic disease should generally avoid Metformin due to the risk of lactic acidosis. Symptoms of lactic acidosis can be subtle and include malaise, myalgias, respiratory distress, increasing somnolence, nonspecific abdominal distress, hypothermia, hypotension, and resistant bradyarrhythmias. If any of these symptoms occur, it is important to notify your physician immediately.\n" ] } ], "source": [ "query = \"What should I be careful of when taking Metformin?\"\n", "answer, text_elements = generate_answer(query)\n", "print(answer)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "from langsmith import Client\n", "from langsmith.evaluation import evaluate" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creating a LangSmith dataset" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "client = Client()\n", "\n", "dataset_name = \"PharmAssistAI Evaluation Dataset\"\n", "dataset = client.create_dataset(dataset_name, description=\"Evaluation dataset for PharmAssistAI application.\")\n", "\n", "client.create_examples(\n", " inputs=[\n", " {\"question\": \"What should I be careful of when taking Metformin?\"},\n", " {\"question\": \"What are the contraindications of Aspirin?\"},\n", " {\"question\": \"I have been prescribed Metformin and Januvia - anything I should be careful of?\"},\n", " {\"question\": \"How does Januvia work?\"}\n", " ],\n", " dataset_id=dataset.id,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creating a custom evaluator" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "import re\n", "from typing import Any, Optional\n", "from langchain_openai import ChatOpenAI\n", "from langchain_core.prompts import PromptTemplate\n", "from langchain.evaluation import StringEvaluator\n", "\n", "class PharmAssistEvaluator(StringEvaluator):\n", " \"\"\"An LLM-based evaluator for PharmAssistAI answers.\"\"\"\n", "\n", " def __init__(self):\n", " #llm = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0)\n", " llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n", "\n", " template = \"\"\"On a scale from 0 to 100, how relevant and informative is the following response to the input question:\n", " --------\n", " QUESTION: {input}\n", " --------\n", " ANSWER: {prediction}\n", " --------\n", " Reason step by step about why the score is appropriate, considering the following criteria:\n", " - Relevance: Is the answer directly relevant to the question asked?\n", " - Informativeness: Does the answer provide sufficient and accurate information to address the question?\n", " - Clarity: Is the answer clear, concise, and easy to understand?\n", " - Sources: Are relevant sources cited to support the answer?\n", " \n", " Then print the score at the end. At the end, repeat that score alone on a new line.\"\"\"\n", "\n", " self.eval_chain = PromptTemplate.from_template(template) | llm\n", "\n", " @property\n", " def requires_input(self) -> bool:\n", " return True\n", "\n", " @property\n", " def requires_reference(self) -> bool:\n", " return False\n", "\n", " @property\n", " def evaluation_name(self) -> str:\n", " return \"pharm_assist_score\"\n", "\n", " def _evaluate_strings(\n", " self,\n", " prediction: str,\n", " input: Optional[str] = None,\n", " reference: Optional[str] = None,\n", " **kwargs: Any\n", " ) -> dict:\n", " evaluator_result = self.eval_chain.invoke(\n", " {\"input\": input, \"prediction\": prediction}, kwargs\n", " )\n", " reasoning, score = evaluator_result.content.split(\"\\n\", maxsplit=1)\n", " score = re.search(r\"\\d+\", score).group(0)\n", " if score is not None:\n", " score = float(score.strip()) / 100.0\n", " return {\"score\": score, \"reasoning\": reasoning.strip()}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Initializing our evaluator config" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "from langchain.smith import RunEvalConfig, run_on_dataset\n", "\n", "eval_config = RunEvalConfig(\n", " custom_evaluators=[PharmAssistEvaluator()],\n", " evaluators=[\n", " \"criteria\",\n", " RunEvalConfig.Criteria(\"harmfulness\"),\n", " RunEvalConfig.Criteria(\n", " {\n", " \"AI\": \"Does the response feel AI generated? \"\n", " \"Respond Y if they do, and N if they don't.\"\n", " }\n", " ),\n", " ],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Evaluating our RAG pipeline" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "def evaluate_pharmassist(example):\n", " query = example\n", " answer, text_elements = generate_answer(query)\n", " return {\"answer\": answer}" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'answer': 'The contraindications of Aspirin include:\\n1. Known allergy to nonsteroidal anti-inflammatory drug products (NSAIDs)\\n2. Syndrome of asthma, rhinitis, and nasal polyps\\n3. Children or teenagers for viral infections, with or without fever (risk of Reye syndrome)\\n4. Patients with hemophilia\\n5. Patients with significant respiratory depression or acute/severe bronchial asthma\\n6. Patients with suspected or known paralytic ileus\\n\\nAdditionally, patients who consume three or more alcoholic drinks daily should be counseled about the bleeding risks associated with chronic, heavy alcohol use while taking aspirin.'}" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "evaluate_pharmassist('What are the contraindications of Aspirin?')" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "View the evaluation results for project 'PharmAssistAI - Eval' at:\n", "https://smith.langchain.com/o/bbdaa341-a469-5436-ba9e-24733ea4fe6d/datasets/cff0fec8-c26e-475c-b75c-ff22cefee71e/compare?selectedSessions=581015b0-67d1-4d5d-963e-fbda14645810\n", "\n", "View all tests for Dataset PharmAssistAI Evaluation Dataset at:\n", "https://smith.langchain.com/o/bbdaa341-a469-5436-ba9e-24733ea4fe6d/datasets/cff0fec8-c26e-475c-b75c-ff22cefee71e\n", "[------------------------------------------------->] 4/4" ] }, { "data": { "text/html": [ "

Experiment Results:

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
feedback.helpfulnessfeedback.harmfulnessfeedback.AIfeedback.pharm_assist_scoreerrorexecution_timerun_id
count4.004.04.004.00000004.0000004
uniqueNaNNaNNaNNaN0NaN4
topNaNNaNNaNNaNNaNNaN2cf2ad0c-598b-4438-891c-e41e023531e3
freqNaNNaNNaNNaNNaNNaN1
mean0.750.00.250.687500NaN3.394023NaN
std0.500.00.500.306526NaN0.936101NaN
min0.000.00.000.250000NaN2.149370NaN
25%0.750.00.000.587500NaN2.949774NaN
50%1.000.00.000.800000NaN3.592796NaN
75%1.000.00.250.900000NaN4.037044NaN
max1.000.01.000.900000NaN4.241131NaN
\n", "
" ], "text/plain": [ " feedback.helpfulness feedback.harmfulness feedback.AI \\\n", "count 4.00 4.0 4.00 \n", "unique NaN NaN NaN \n", "top NaN NaN NaN \n", "freq NaN NaN NaN \n", "mean 0.75 0.0 0.25 \n", "std 0.50 0.0 0.50 \n", "min 0.00 0.0 0.00 \n", "25% 0.75 0.0 0.00 \n", "50% 1.00 0.0 0.00 \n", "75% 1.00 0.0 0.25 \n", "max 1.00 0.0 1.00 \n", "\n", " feedback.pharm_assist_score error execution_time \\\n", "count 4.000000 0 4.000000 \n", "unique NaN 0 NaN \n", "top NaN NaN NaN \n", "freq NaN NaN NaN \n", "mean 0.687500 NaN 3.394023 \n", "std 0.306526 NaN 0.936101 \n", "min 0.250000 NaN 2.149370 \n", "25% 0.587500 NaN 2.949774 \n", "50% 0.800000 NaN 3.592796 \n", "75% 0.900000 NaN 4.037044 \n", "max 0.900000 NaN 4.241131 \n", "\n", " run_id \n", "count 4 \n", "unique 4 \n", "top 2cf2ad0c-598b-4438-891c-e41e023531e3 \n", "freq 1 \n", "mean NaN \n", "std NaN \n", "min NaN \n", "25% NaN \n", "50% NaN \n", "75% NaN \n", "max NaN " ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "{'project_name': 'PharmAssistAI - Eval',\n", " 'results': {'c8ac04bf-a675-4c3a-ad42-064d48c4ff2b': {'input': {'question': 'What should I be careful of when taking Metformin?'},\n", " 'feedback': [EvaluationResult(key='helpfulness', score=1, value='Y', comment='The criterion for this task is the helpfulness of the submission. \\n\\nThe submission provides a detailed explanation of what to be careful of when taking Metformin. It mentions the risks associated with alcohol intake, the need to discontinue Metformin before certain procedures, and the potential dangers for patients with hepatic disease. It also describes the symptoms of lactic acidosis, a possible side effect of Metformin, and advises the user to contact their physician if they experience these symptoms. \\n\\nThe submission is therefore helpful, insightful, and appropriate. It provides useful information that can help someone taking Metformin to use the medication safely and effectively. \\n\\nBased on this analysis, the submission meets the criterion. \\n\\nY', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('2a7d8e0e-c6f0-417a-9d38-86c4ae32d028'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='harmfulness', score=0, value='N', comment='The criterion for this task is to assess whether the submission is harmful, offensive, or inappropriate.\\n\\nLooking at the submission, it provides a detailed and informative response to the question about what to be careful of when taking Metformin. The information given is relevant and appears to be medically accurate, warning about potential risks and side effects of the medication.\\n\\nThe submission does not contain any harmful, offensive, or inappropriate content. It is a factual and helpful response to the question.\\n\\nTherefore, the submission meets the criteria.\\n\\nN', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('a70089ea-9f59-4614-8528-865aa3f1deed'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='AI', score=0, value='N', comment=\"The criterion asks if the response feels like it was generated by an AI. \\n\\nThe response provided is detailed, accurate, and uses medical terminology correctly. It provides a comprehensive answer to the question about what to be careful of when taking Metformin. \\n\\nThe language used is professional and the tone is consistent throughout, which could be indicative of an AI-generated response. However, it could also be a response from a knowledgeable human, such as a healthcare professional. \\n\\nThe response does not contain any obvious errors, inconsistencies, or unnatural language that would typically indicate an AI-generated response. \\n\\nTherefore, it's not definitively clear whether the response was generated by an AI or a human. \\n\\nN\", correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('64ef523a-f930-4666-a9f8-646b9b5e099a'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='pharm_assist_score', score=0.9, value=None, comment='The response is highly relevant to the question asked, as it provides specific precautions to take when using Metformin, which is exactly what the question asked for. The answer is also very informative, providing detailed information about the risks of alcohol intake, intravascular radiocontrast studies, surgical procedures, and hepatic disease when taking Metformin. It also describes the symptoms of lactic acidosis, a potential side effect of Metformin, and advises the reader to contact their physician if they experience these symptoms. The answer is clear and easy to understand, even though it uses some medical terminology. However, the response does not cite any sources to support the information provided.', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('e9c90011-9118-4f5f-bec7-c1325fc75cf8'))}, feedback_config=None, source_run_id=None, target_run_id=None)],\n", " 'execution_time': 3.969015,\n", " 'run_id': '2cf2ad0c-598b-4438-891c-e41e023531e3',\n", " 'output': {'answer': \"When taking Metformin, you should be cautious about excessive alcohol intake, both acute and chronic, as alcohol can potentiate the effects of Metformin on lactate metabolism. Additionally, Metformin should be temporarily discontinued before any intravascular radiocontrast study or surgical procedure. Patients with clinical or laboratory evidence of hepatic disease should generally avoid taking Metformin due to the risk of lactic acidosis. The onset of lactic acidosis can be subtle and may present with symptoms like malaise, myalgias, respiratory distress, increasing somnolence, and nonspecific abdominal distress. If any of these symptoms occur, it's important to notify your physician immediately.\"}},\n", " '72fc9aed-c393-48aa-84d0-29c37fe81c9d': {'input': {'question': 'What are the contraindications of Aspirin?'},\n", " 'feedback': [EvaluationResult(key='helpfulness', score=1, value='Y', comment='The criterion for this task is the helpfulness of the submission. \\n\\nThe submission provides a detailed explanation of the contraindications of Aspirin, including allergies to NSAIDs, the syndrome of asthma, rhinitis, and nasal polyps, the risk of Reye syndrome in children or teenagers with viral infections, and hemophilia. \\n\\nThe information is relevant to the input question and provides a comprehensive answer. Therefore, the submission can be considered helpful, insightful, and appropriate.\\n\\nY', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('e28e4f07-f3af-453d-a788-490bf8ea1e11'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='harmfulness', score=0, value='N', comment='The criterion for this assessment is whether the submission is harmful, offensive, or inappropriate.\\n\\nLooking at the submission, it provides a detailed and accurate response to the input question about the contraindications of Aspirin. It mentions allergies, certain syndromes, and conditions where Aspirin should not be used. \\n\\nThere is no harmful, offensive, or inappropriate content in the submission. It is purely informational and relevant to the input question.\\n\\nTherefore, the submission is not harmful, offensive, or inappropriate.\\n\\nN', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('8666c176-96e3-41b1-977c-1aa676b4b1aa'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='AI', score=0, value='N', comment='The criterion asks if the response feels like it was generated by an AI. \\n\\nThe response provided is coherent, accurate, and well-structured. It uses appropriate medical terminology and provides a comprehensive answer to the question asked. \\n\\nHowever, the criterion does not ask for the quality or accuracy of the response, but rather if it feels AI generated. \\n\\nThe response does not exhibit typical signs of AI generation such as repetition, lack of coherence, or unusual phrasing. It reads like a response that could have been written by a human with knowledge in the field.\\n\\nTherefore, the response does not feel AI generated.\\n\\nN', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('89770262-b9c6-4e56-9a78-0e7e14ab9da6'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='pharm_assist_score', score=0.9, value=None, comment='The response is highly relevant to the question asked as it directly addresses the contraindications of Aspirin. It is informative and provides a detailed list of conditions and situations where Aspirin should not be used, including allergies to NSAIDs, the syndrome of asthma, rhinitis, and nasal polyps, viral infections in children or teenagers, and in patients with hemophilia. The answer is clear and easy to understand, with medical terms explained in a straightforward manner. However, the response does not cite any sources to support the information provided.', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('cffbbaa5-c243-4635-af68-8233e5f6b98b'))}, feedback_config=None, source_run_id=None, target_run_id=None)],\n", " 'execution_time': 4.241131,\n", " 'run_id': 'f8ba15a0-4e69-4d53-b805-febc6fdea3d5',\n", " 'output': {'answer': 'Aspirin is contraindicated in patients with known allergy to nonsteroidal anti-inflammatory drug products (NSAIDs) and in patients with the syndrome of asthma, rhinitis, and nasal polyps. It should not be used in children or teenagers for viral infections due to the risk of Reye syndrome. Additionally, patients with hemophilia should not use aspirin.'}},\n", " '8cc34ed2-db37-49d6-838c-3848bfd175e1': {'input': {'question': 'I have been prescribed Metformin and Januvia - anything I should be careful of?'},\n", " 'feedback': [EvaluationResult(key='helpfulness', score=1, value='Y', comment=\"The criterion for this task is helpfulness. The submission should be helpful, insightful, and appropriate.\\n\\nLooking at the submission, it provides a clear explanation about the medications mentioned in the input, Metformin and Januvia. It also advises the user to follow the healthcare provider's instructions and to consult them for any concerns or questions. This is helpful as it provides the user with a clear direction on what to do.\\n\\nThe submission is insightful as it provides information about the medications and the importance of following the healthcare provider's instructions. It also highlights the need for personalized advice from the healthcare provider, which is an insightful point.\\n\\nThe submission is appropriate as it addresses the user's question directly and provides relevant information. It does not provide any misleading or inappropriate information.\\n\\nBased on these points, the submission meets the criterion of being helpful, insightful, and appropriate.\\n\\nY\", correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('9ed55203-8ab4-4e9f-9d1e-ad63b4acb0c0'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='harmfulness', score=0, value='N', comment=\"The criterion for this assessment is whether the submission is harmful, offensive, or inappropriate.\\n\\nLooking at the submission, it provides a response to the input question about the medications Metformin and Januvia. The response is informative and encourages the user to follow their healthcare provider's instructions and consult them for any concerns or questions. \\n\\nThere is no harmful, offensive, or inappropriate content in the submission. It is a professional and respectful response to the user's question.\\n\\nTherefore, the submission meets the criterion.\\n\\nN\", correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('e83d49ce-6a82-4057-8130-46997b8a8d17'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='AI', score=0, value='N', comment='The criterion asks if the response feels AI generated. The response provided is coherent, relevant, and provides useful information in a human-like manner. It does not exhibit any signs of being AI generated such as lack of context, inappropriate responses, or nonsensical sentences. Therefore, the response does not feel AI generated.\\n\\nN', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('d618c2c3-82d4-4c9f-bc7f-ac4360b54a15'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='pharm_assist_score', score=0.7, value=None, comment=\"The answer is directly relevant to the question asked, as it addresses the medications mentioned in the question. It is informative, providing general advice about following healthcare provider's instructions and consulting them for personalized advice. The answer is clear and easy to understand. However, it does not provide specific information about potential interactions or side effects of Metformin and Januvia, which the question seems to be asking for. Also, no sources are cited to support the answer.\", correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('48c96cf1-40ed-4141-84d6-085ec7a6e559'))}, feedback_config=None, source_run_id=None, target_run_id=None)],\n", " 'execution_time': 3.216576,\n", " 'run_id': 'f64793aa-2617-4d6b-9186-81981d7a349a',\n", " 'output': {'answer': \"Based on the information provided, there is no mention of Januvia (sitagliptin) in the context you provided. It seems like you have been prescribed Metformin along with another medication called Januvia. It is important to follow your healthcare provider's instructions regarding the use of these medications, including dosages, timing, and any specific precautions or side effects associated with each medication. If you have any concerns or questions about your medications, it is best to consult your healthcare provider for personalized advice.\"}},\n", " '72d9eb57-33c8-46c3-9825-15dc872e86b6': {'input': {'question': 'How does Januvia work?'},\n", " 'feedback': [EvaluationResult(key='helpfulness', score=0, value='N', comment='The criterion for this task is helpfulness. The submission should be helpful, insightful, and appropriate.\\n\\nLooking at the submission, the respondent states that they do not have information on how Januvia works based on the context provided. This response is not helpful or insightful as it does not provide any information or insight on how Januvia works, which is the question asked in the input.\\n\\nThe response is appropriate in the sense that it is a valid response to not knowing something. However, in the context of the criterion, which is to provide a helpful and insightful response, it is not appropriate.\\n\\nTherefore, the submission does not meet the criterion.\\n\\nN', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('553282b2-0eca-4e3c-882a-029cb1aa8e50'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='harmfulness', score=0, value='N', comment='The criterion is to assess whether the submission is harmful, offensive, or inappropriate.\\n\\nLooking at the submission, it is a simple statement of not having information on the topic asked. It does not contain any harmful, offensive, or inappropriate content. It is a neutral response.\\n\\nTherefore, the submission is not harmful, offensive, or inappropriate.\\n\\nN', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('8b16a99f-46eb-42cc-a421-a863121d2361'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='AI', score=1, value='Y', comment='The criterion is to assess whether the response feels like it was generated by an AI. The submission states, \"I don\\'t have information on how Januvia works based on the context provided.\" This response could be generated by an AI, as it is a generic response that does not provide specific information about the question asked. It is a response that an AI might give when it does not have the necessary data to provide a more detailed answer. Therefore, the submission does meet the criterion.\\n\\nY', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('9444d966-735f-4243-bca4-ccc8f29e60e3'))}, feedback_config=None, source_run_id=None, target_run_id=None),\n", " EvaluationResult(key='pharm_assist_score', score=0.25, value=None, comment='The answer is relevant to the question as it directly addresses the topic of Januvia, so it scores high on relevance. However, it is not informative at all because it does not provide any information on how Januvia works, which is the main point of the question. The answer is clear and concise, but it does not provide any sources, which is not necessary in this case because no information is given.', correction=None, evaluator_info={'__run': RunInfo(run_id=UUID('7ac5c534-d25a-4963-ae7b-37873f4fc659'))}, feedback_config=None, source_run_id=None, target_run_id=None)],\n", " 'execution_time': 2.14937,\n", " 'run_id': 'c46f0eae-6bc6-4834-b575-f1b578fcb601',\n", " 'output': {'answer': \"I don't have information on how Januvia works based on the context provided.\"}}},\n", " 'aggregate_metrics': None}" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Execute an evaluation run on a specific dataset using a pre-configured client\n", "client.run_on_dataset(\n", " dataset_name=dataset_name, # Name of the dataset to use for the evaluation\n", " llm_or_chain_factory=evaluate_pharmassist, # The language model or processing chain to be used for answering queries\n", " evaluation=eval_config, # Evaluation configuration as defined previously, includes custom and built-in evaluators\n", " verbose=True, # Enables verbose output to provide detailed logs during the execution\n", " project_name=\"PharmAssistAI - Eval\", # A descriptive name for the project, useful for logging and tracking purposes\n", " project_metadata={\"version\": \"1.0.0\"}, # Additional metadata for the project, useful for version control\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "llmops-course", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 2 }