File size: 41,544 Bytes
5d80c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "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",
    "<answer>\n",
    "SOURCES: <document_references>\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": [
       "<h3>Experiment Results:</h3>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "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>feedback.helpfulness</th>\n",
       "      <th>feedback.harmfulness</th>\n",
       "      <th>feedback.AI</th>\n",
       "      <th>feedback.pharm_assist_score</th>\n",
       "      <th>error</th>\n",
       "      <th>execution_time</th>\n",
       "      <th>run_id</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>4.00</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.00</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>0</td>\n",
       "      <td>4.000000</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>unique</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>top</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2cf2ad0c-598b-4438-891c-e41e023531e3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>freq</th>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>0.75</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.25</td>\n",
       "      <td>0.687500</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.394023</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.50</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.50</td>\n",
       "      <td>0.306526</td>\n",
       "      <td>NaN</td>\n",
       "      <td>0.936101</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>0.00</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.250000</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.149370</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>0.75</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.587500</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.949774</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>1.00</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.592796</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>1.00</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.25</td>\n",
       "      <td>0.900000</td>\n",
       "      <td>NaN</td>\n",
       "      <td>4.037044</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>1.00</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.00</td>\n",
       "      <td>0.900000</td>\n",
       "      <td>NaN</td>\n",
       "      <td>4.241131</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "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
}