File size: 16,206 Bytes
1057395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -U -q langchain langchain-openai langchain_core langchain-community langchainhub openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -qU qdrant-client pymupdf pandas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-07-18 14:47:19 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:20 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:21 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:21 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:22 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:23 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:24 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:25 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:25 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:26 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:47:29 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import openai\n",
    "import getpass\n",
    "import chainlit as cl\n",
    "from langchain_community.document_loaders import PyMuPDFLoader\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_community.vectorstores import Qdrant\n",
    "from langchain.prompts import ChatPromptTemplate\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "from operator import itemgetter\n",
    "from langchain_huggingface import HuggingFaceEndpoint\n",
    "from langchain_community.document_loaders import TextLoader\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_huggingface import HuggingFaceEndpointEmbeddings\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain.schema.output_parser import StrOutputParser\n",
    "from langchain.schema.runnable import RunnablePassthrough\n",
    "from langchain.schema.runnable.config import RunnableConfig\n",
    "\n",
    "#Load environment variables\n",
    "load_dotenv()\n",
    "OPENAI_API_KEY = os.environ[\"OPENAI_API_KEY\"]\n",
    "\n",
    "\n",
    "#Load 10-K PDF and split into chunks\n",
    "loader = PyMuPDFLoader (\n",
    "    \"https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf\"\n",
    ")\n",
    "\n",
    "documents = loader.load()\n",
    "\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter(\n",
    "    chunk_size = 1000,\n",
    "    chunk_overlap = 100\n",
    ")\n",
    "\n",
    "documents = text_splitter.split_documents(documents)\n",
    "\n",
    "#Load embeddings model - we'll use OpenAI's text-embedding-3-small\n",
    "embeddings = OpenAIEmbeddings(\n",
    "    model=\"text-embedding-3-small\"\n",
    ")\n",
    "\n",
    "#Create QDrant vector store\n",
    "qdrant_vector_store = Qdrant.from_documents(\n",
    "    documents,\n",
    "    embeddings,\n",
    "    location=\":memory:\",\n",
    "    collection_name=\"WelchAllynConnex6000VSMServiceManual\",\n",
    ")\n",
    "\n",
    "#Create Retriever\n",
    "retriever = qdrant_vector_store.as_retriever()\n",
    "\n",
    "#Create Prompt Template\n",
    "template = \"\"\"Answer the question based only on the following context. If you cannot answer the question with the context, please respond with 'I don't know':\n",
    "\n",
    "Context:\n",
    "{context}\n",
    "\n",
    "Question:\n",
    "{question}\n",
    "\"\"\"\n",
    "\n",
    "prompt = ChatPromptTemplate.from_template(template)\n",
    "\n",
    "#Choose LLM - we'll use gpt-4o.\n",
    "primary_llm = ChatOpenAI(model_name=\"gpt-4o\", temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-07-18 14:50:04 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n"
     ]
    }
   ],
   "source": [
    "retrieved_documents = retriever.invoke(\"How do I specify advanced alarm settings?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "page_content='tab in the Device Status area.\n",
      "Enable NTP\n",
      "Select to use the NTP server for time\n",
      "synchronization rather than the episodic host.\n",
      "Host name or IP address\n",
      "Enter the host name, IP address, or domain name of\n",
      "the NTP server.\n",
      "Test\n",
      "Touch Test to test the connection to the NTP\n",
      "server.\n",
      "Information messages indicate that a test is in\n",
      "progress and then the result of the test (pass or fail).\n",
      "4.\n",
      "Do one of the following:\n",
      "•\n",
      "To continue in the Advanced settings, touch another tab.\n",
      "•\n",
      "To exit the Advanced settings and return to the Home tab, touch Exit.\n",
      "Specify advanced alarm settings\n",
      "1.\n",
      "Access the Advanced settings.\n",
      "a.\n",
      "Touch the Settings tab.\n",
      "b.\n",
      "Touch the Advanced tab.\n",
      "c.\n",
      "Touch Enter password.\n",
      "d.\n",
      "Enter your password and touch OK.\n",
      "The General tab appears.\n",
      "2.\n",
      "Touch the Alarms tab.\n",
      "3.\n",
      "Specify settings.\n",
      "24 Advanced settings' metadata={'source': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'file_path': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'page': 27, 'total_pages': 349, 'format': 'PDF 1.6', 'title': 'Service manual - Welch Allyn Connex Vital Signs Monitor 6000 Series™', 'author': 'Welch Allyn Inc.', 'subject': '', 'keywords': '', 'creator': 'AH Formatter V5.1 MR2 (5,1,2010,0409) for Windows', 'producer': 'Antenna House PDF Output Library 2.6.0 (Windows)', 'creationDate': \"D:20230214101552-06'00'\", 'modDate': \"D:20230214143156-05'00'\", 'trapped': '', 'encryption': 'Standard V4 R4 128-bit RC4', '_id': 'd2315a8070da40b6a7732e0886169c9a', '_collection_name': 'WelchAllynConnex6000VSMServiceManual'}\n",
      "page_content='Specify the time that an adult no breath detected\n",
      "condition must be active in an Oridion CO2\n",
      "configuration before audio and visual signals occur.\n",
      "Pediatric no breath detected alarm delay\n",
      "Specify the time that a pediatric no breath detected\n",
      "condition must be active in an Oridion CO2\n",
      "configuration before audio and visual signals occur.\n",
      "Neonate no breath detected alarm delay\n",
      "Specify the time that a neonate no breath detected\n",
      "condition must be active in an Oridion CO2\n",
      "configuration before audio and visual signals occur.\n",
      "ECG HR alarm delay\n",
      "Specifies the time that an ECG heart rate alarm\n",
      "condition must be active before audio and visual\n",
      "signals occur.\n",
      "4.\n",
      "Do one of the following:\n",
      "•\n",
      "To continue in the Advanced settings, touch another tab.\n",
      "•\n",
      "To exit the Advanced settings and return to the Home tab, touch Exit.\n",
      "Specify advanced display settings\n",
      "1.\n",
      "Access the Advanced settings.\n",
      "a.\n",
      "Touch the Settings tab.\n",
      "26 Advanced settings' metadata={'source': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'file_path': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'page': 29, 'total_pages': 349, 'format': 'PDF 1.6', 'title': 'Service manual - Welch Allyn Connex Vital Signs Monitor 6000 Series™', 'author': 'Welch Allyn Inc.', 'subject': '', 'keywords': '', 'creator': 'AH Formatter V5.1 MR2 (5,1,2010,0409) for Windows', 'producer': 'Antenna House PDF Output Library 2.6.0 (Windows)', 'creationDate': \"D:20230214101552-06'00'\", 'modDate': \"D:20230214143156-05'00'\", 'trapped': '', 'encryption': 'Standard V4 R4 128-bit RC4', '_id': '7a61d18dcf9940d48dd0becdd2473c85', '_collection_name': 'WelchAllynConnex6000VSMServiceManual'}\n",
      "page_content='Admin mode), enabling nurse administrators, biomedical engineers, and/or service engineers to\n",
      "configure specific features. The Advanced tab also presents read-only information about the\n",
      "monitor.\n",
      "The password to enter Advanced settings is configurable and can also be set to expire. See the\n",
      "\"Password\" topic at the end of this section for more details.\n",
      "NOTE You cannot enter Advanced settings if sensors or physiological alarms are\n",
      "active or if vital sign measurements are displayed.\n",
      "Access the Service tabs\n",
      "NOTE You cannot access the Service tabs if sensors or physiological alarms are\n",
      "active or if vital sign measurements are displayed.\n",
      "1.\n",
      "From the Home tab, touch the Settings tab.\n",
      "2.\n",
      "Touch the Advanced tab.\n",
      "3.\n",
      "Touch Enter password.\n",
      "48 Advanced settings' metadata={'source': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'file_path': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'page': 51, 'total_pages': 349, 'format': 'PDF 1.6', 'title': 'Service manual - Welch Allyn Connex Vital Signs Monitor 6000 Series™', 'author': 'Welch Allyn Inc.', 'subject': '', 'keywords': '', 'creator': 'AH Formatter V5.1 MR2 (5,1,2010,0409) for Windows', 'producer': 'Antenna House PDF Output Library 2.6.0 (Windows)', 'creationDate': \"D:20230214101552-06'00'\", 'modDate': \"D:20230214143156-05'00'\", 'trapped': '', 'encryption': 'Standard V4 R4 128-bit RC4', '_id': '8e4aa373a6e547deac9c12c2a02c6b21', '_collection_name': 'WelchAllynConnex6000VSMServiceManual'}\n",
      "page_content='•\n",
      "In Advanced settings, the left pane on the Network > Radio tab includes only Enable radio\n",
      "and Enable radio network alarms options (no Enable dynamic frequency option).\n",
      "1.\n",
      "Access the Advanced settings.\n",
      "a.\n",
      "Touch the Settings tab.\n",
      "b.\n",
      "Touch the Advanced tab.\n",
      "c.\n",
      "Touch Enter password.\n",
      "d.\n",
      "Enter your password and touch OK.\n",
      "The General tab appears.\n",
      "2.\n",
      "Touch the Network tab.\n",
      "3.\n",
      "Touch the Radio tab.\n",
      "4.\n",
      "Specify settings.\n",
      "Setting\n",
      "Action/Description\n",
      "Enable radio\n",
      "Enable the radio for device communications. When\n",
      "disabled, the radio is not available.\n",
      "Enable radio network alarms\n",
      "Activate radio network alarms when an alarm\n",
      "condition occurs. When disabled, radio network\n",
      "alarms are not available.\n",
      "SSID\n",
      "Touch \n",
      " and enter the service set identifier\n",
      "(SSID). SSIDs that are longer than 16 characters may\n",
      "be truncated in the user view. Enter a maximum of\n",
      "32 characters.\n",
      "Radio band\n",
      "Select the radio band.\n",
      "Authentication type\n",
      "Select an authentication scheme. Then specify any\n",
      "additional settings that appear.' metadata={'source': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'file_path': 'https://www.hillrom.com/content/dam/hillrom-aem/us/en/sap-documents/LIT/80026/80026025LITPDF.pdf', 'page': 47, 'total_pages': 349, 'format': 'PDF 1.6', 'title': 'Service manual - Welch Allyn Connex Vital Signs Monitor 6000 Series™', 'author': 'Welch Allyn Inc.', 'subject': '', 'keywords': '', 'creator': 'AH Formatter V5.1 MR2 (5,1,2010,0409) for Windows', 'producer': 'Antenna House PDF Output Library 2.6.0 (Windows)', 'creationDate': \"D:20230214101552-06'00'\", 'modDate': \"D:20230214143156-05'00'\", 'trapped': '', 'encryption': 'Standard V4 R4 128-bit RC4', '_id': '21f61f7963c84a2a8af1f35a1e02452e', '_collection_name': 'WelchAllynConnex6000VSMServiceManual'}\n"
     ]
    }
   ],
   "source": [
    "for doc in retrieved_documents:\n",
    "  print(doc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "primary_llm = ChatOpenAI(model_name=\"gpt-4o\", temperature=0)\n",
    "\n",
    "retrieval_augmented_chain = (\n",
    "        # INVOKE CHAIN WITH: {\"question\" : \"<<SOME USER QUESTION>>\"}\n",
    "        # \"question\" : populated by getting the value of the \"question\" key\n",
    "        # \"context\"  : populated by getting the value of the \"question\" key and chaining it into the base_retriever\n",
    "        {\"context\": itemgetter(\"question\") | retriever, \"question\": itemgetter(\"question\")}\n",
    "        | prompt | primary_llm\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-07-18 14:52:25 - HTTP Request: POST https://api.openai.com/v1/embeddings \"HTTP/1.1 200 OK\"\n",
      "2024-07-18 14:52:27 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n"
     ]
    }
   ],
   "source": [
    "question = \"How do I specify advanced alarm settings?\"\n",
    "\n",
    "result = retrieval_augmented_chain.invoke({\"question\" : question})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "print(result[\"response\"].content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='To specify advanced alarm settings, follow these steps:\\n\\n1. Access the Advanced settings:\\n   a. Touch the Settings tab.\\n   b. Touch the Advanced tab.\\n   c. Touch Enter password.\\n   d. Enter your password and touch OK. The General tab appears.\\n2. Touch the Alarms tab.\\n3. Specify settings.' response_metadata={'token_usage': {'completion_tokens': 68, 'prompt_tokens': 2027, 'total_tokens': 2095}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_c4e5b6fa31', 'finish_reason': 'stop', 'logprobs': None} id='run-e022a522-caec-4748-b093-24ca2b030a81-0' usage_metadata={'input_tokens': 2027, 'output_tokens': 68, 'total_tokens': 2095}\n"
     ]
    }
   ],
   "source": [
    "print(result)"
   ]
  }
 ],
 "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}