Yew Chong commited on
Commit
4199b87
1 Parent(s): 07e97dd

notebook for patient

Browse files
Files changed (2) hide show
  1. .gitignore +4 -1
  2. LLM for Patient (test).ipynb +271 -0
.gitignore CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # env
2
  .env*
3
  healthhack-store-firebase-adminsdk-sq7ne-32400d49de.json
@@ -18,4 +20,5 @@ indexes/
18
  .firebase
19
 
20
  # others
21
- *.log
 
 
1
+ __pycache__/
2
+
3
  # env
4
  .env*
5
  healthhack-store-firebase-adminsdk-sq7ne-32400d49de.json
 
20
  .firebase
21
 
22
  # others
23
+ *.log
24
+ test*.py
LLM for Patient (test).ipynb ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 15,
6
+ "id": "e0a3cde9",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "data": {
11
+ "text/plain": [
12
+ "True"
13
+ ]
14
+ },
15
+ "execution_count": 15,
16
+ "metadata": {},
17
+ "output_type": "execute_result"
18
+ }
19
+ ],
20
+ "source": [
21
+ "import openai\n",
22
+ "from langchain_openai import ChatOpenAI, OpenAIEmbeddings\n",
23
+ "import tiktoken\n",
24
+ "from langchain.prompts.few_shot import FewShotPromptTemplate\n",
25
+ "from langchain.prompts.prompt import PromptTemplate\n",
26
+ "from operator import itemgetter\n",
27
+ "from langchain.schema import StrOutputParser\n",
28
+ "from langchain_core.output_parsers import StrOutputParser\n",
29
+ "from langchain_core.runnables import RunnablePassthrough\n",
30
+ "\n",
31
+ "import langchain_community.embeddings.huggingface\n",
32
+ "# help(langchain_community.embeddings.huggingface)\n",
33
+ "from langchain_community.embeddings.huggingface import HuggingFaceBgeEmbeddings\n",
34
+ "from langchain_community.vectorstores import FAISS\n",
35
+ "\n",
36
+ "from langchain.chains import LLMChain\n",
37
+ "from langchain.chains.conversation.memory import ConversationBufferMemory, ConversationBufferWindowMemory, ConversationSummaryMemory, ConversationSummaryBufferMemory\n",
38
+ "\n",
39
+ "import os, dotenv\n",
40
+ "from dotenv import load_dotenv\n",
41
+ "load_dotenv()"
42
+ ]
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "execution_count": 3,
47
+ "id": "bf5aac26",
48
+ "metadata": {},
49
+ "outputs": [],
50
+ "source": [
51
+ "# embeddings = OpenAIEmbeddings(deployment=\"textembedding\", chunk_size = 16, api_key = os.environ[\"OPENAI_API_KEY\"])\n",
52
+ "# index_name = \"SCLC\"\n",
53
+ "\n",
54
+ "model_name = \"bge-large-en-v1.5\"\n",
55
+ "model_kwargs = {\"device\": \"cpu\"}\n",
56
+ "# model_kwargs = {\"device\": \"cuda\"}\n",
57
+ "encode_kwargs = {\"normalize_embeddings\": True}\n",
58
+ "embeddings = HuggingFaceBgeEmbeddings(\n",
59
+ " # model_name=model_name, \n",
60
+ " model_kwargs = model_kwargs,\n",
61
+ " encode_kwargs = encode_kwargs)\n",
62
+ "\n",
63
+ "index_name = \"indexes/ChestPainQA\"\n",
64
+ "\n",
65
+ "# store = FAISS.load_local(index_name, embeddings)\n",
66
+ "import db_firestore as db\n",
67
+ "store = db.get_store(index_name, embeddings=embeddings)\n"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": 42,
73
+ "id": "2d75b44a",
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "TEMPLATE = \"\"\"You are a patient undergoing a medical check-up. You will be given the following:\n",
78
+ "1. A context to answer the doctor, for your possible symptoms.\n",
79
+ "2. A question about your current symptoms.\n",
80
+ "\n",
81
+ "Your task is to answer the doctor's questions as simple as possible, acting like a patient.\n",
82
+ "Do not include other symptoms that are not included in the context, which provides your symptoms.\n",
83
+ "\n",
84
+ "Answer the question to the point, without any elaboration if you're not prodded with it.\n",
85
+ "\n",
86
+ "As you are a patient, you do not know any medical jargon or lingo. Do not include specific medical terms in your reply.\n",
87
+ "You only know colloquial words for medical terms. \n",
88
+ "For example, you should not reply with \"dysarthria\", but instead with \"cannot speak properly\". \n",
89
+ "For example, you should not reply with \"syncope\", but instead with \"fainting\". \n",
90
+ "\n",
91
+ "Here is the context:\n",
92
+ "{context}\n",
93
+ "\n",
94
+ "----------------------------------------------------------------\n",
95
+ "You are to reply the doctor's following question, with reference to the above context.\n",
96
+ "Question:\n",
97
+ "{question}\n",
98
+ "----------------------------------------------------------------\n",
99
+ "Remember, answer in a short and sweet manner, don't talk too much.\n",
100
+ "Your reply:\n",
101
+ "\"\"\"\n",
102
+ "\n",
103
+ "prompt = PromptTemplate(\n",
104
+ " input_variables = [\"question\", \"context\"],\n",
105
+ " template = TEMPLATE\n",
106
+ ")\n",
107
+ "retriever = store.as_retriever(search_type=\"similarity\", search_kwargs={\"k\":2})\n",
108
+ "def format_docs(docs):\n",
109
+ " return \"\\n--------------------\\n\".join(doc.page_content for doc in docs)\n",
110
+ "\n",
111
+ "\n",
112
+ "llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0)\n",
113
+ "\n"
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "execution_count": 45,
119
+ "id": "e6e21890",
120
+ "metadata": {},
121
+ "outputs": [],
122
+ "source": [
123
+ "## RESET MEMORY\n",
124
+ "## To reset the memory (if it screws up), rerun this cell\n",
125
+ "memory = ConversationSummaryBufferMemory(llm=llm, memory_key=\"chat_history\", input_key=\"question\" )\n",
126
+ "\n",
127
+ "chain = (\n",
128
+ " {\n",
129
+ " \"context\": retriever | format_docs, \n",
130
+ " \"question\": RunnablePassthrough()\n",
131
+ " } | \n",
132
+ " # prompt | \n",
133
+ " LLMChain(llm=llm, prompt=prompt, memory=memory, verbose=True) #| \n",
134
+ " # StrOutputParser()\n",
135
+ ")"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "execution_count": 47,
141
+ "id": "f443e8c7",
142
+ "metadata": {},
143
+ "outputs": [
144
+ {
145
+ "name": "stdout",
146
+ "output_type": "stream",
147
+ "text": [
148
+ "\n",
149
+ "\n",
150
+ "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
151
+ "Prompt after formatting:\n",
152
+ "\u001b[32;1m\u001b[1;3mYou are a patient undergoing a medical check-up. You will be given the following:\n",
153
+ "1. A context to answer the doctor, for your possible symptoms.\n",
154
+ "2. A question about your current symptoms.\n",
155
+ "\n",
156
+ "Your task is to answer the doctor's questions as simple as possible, acting like a patient.\n",
157
+ "Do not include other symptoms that are not included in the context, which provides your symptoms.\n",
158
+ "\n",
159
+ "Answer the question to the point, without any elaboration if you're not prodded with it.\n",
160
+ "\n",
161
+ "As you are a patient, you do not know any medical jargon or lingo. Do not include specific medical terms in your reply.\n",
162
+ "You only know colloquial words for medical terms. \n",
163
+ "For example, you should not reply with \"dysarthria\", but instead with \"cannot speak properly\". \n",
164
+ "For example, you should not reply with \"syncope\", but instead with \"fainting\". \n",
165
+ "\n",
166
+ "Here is the context:\n",
167
+ "o Mother: Some collagen tissue disorder, not sure what it was \n",
168
+ "o Both parents have HTN and HLD, well controlled \n",
169
+ "● Social history * \n",
170
+ "o Smoker, 10 sticks a day for the past 30 years \n",
171
+ "o Drinker, can of beer every dinner and weekend binge drinking with friends \n",
172
+ "o Diet, normally likes eating char kuay teow or fried carrot cake, doesn’t take much fruits or \n",
173
+ "vegetables \n",
174
+ "o Occupation: Retired, former taxi driver \n",
175
+ "o NIL exercise \n",
176
+ "o Sexual hx unremarkable \n",
177
+ "o NIL recent travel \n",
178
+ "● Ideas, Concerns and Expectations \n",
179
+ "o Worried if he is having a heart attack, scared because his father had one \n",
180
+ "o Wants the pain to stop \n",
181
+ "----------------------------------------------------------------------------------------------------------------------------- ---------\n",
182
+ "--------------------\n",
183
+ "● Neuro : \n",
184
+ "o Syncope (one episode), dysarthria \n",
185
+ "o NIL headaches or vision changes \n",
186
+ "o NIL weakness or numbness \n",
187
+ "o NIL head trauma/falls (did not sustain injury during syncopal episode) \n",
188
+ "● Gastro : \n",
189
+ "o NIL nausea or vomiting \n",
190
+ "o NIL abdo pain \n",
191
+ "o NIL changes to bowel habit or blood in stool, constipation or diarrhoea \n",
192
+ "● Respi : \n",
193
+ "o Some breathlessness, not excessive \n",
194
+ "o NIL cough or haemoptysis \n",
195
+ "● Renal/Uro : \n",
196
+ "o NIL urinary Sx - dysuria, haematuria \n",
197
+ "● MSK/Derm \n",
198
+ "o NIL joint or muscle pains \n",
199
+ "o NIL rash or skin changes \n",
200
+ "● Constitutional : NIL fever, weight loss, loss of appetite, night sweats \n",
201
+ " \n",
202
+ "----------------------------------------------------------------------------------------------------------------------------- --------- \n",
203
+ " \n",
204
+ "History taking: Others \n",
205
+ "● PMHx/Shx * \n",
206
+ "o HTN, HLD, T2DM, diagnosed 7 years ago, poorly compliant with meds \n",
207
+ "o History of biliary colic and gallstones, diagnosed 2 years ago \n",
208
+ "o Recent hospitalisation and procedure done\n",
209
+ "\n",
210
+ "----------------------------------------------------------------\n",
211
+ "You are to reply the doctor's following question, with reference to the above context.\n",
212
+ "Question:\n",
213
+ "Are you okay?\n",
214
+ "----------------------------------------------------------------\n",
215
+ "Remember, answer in a short and sweet manner, don't talk too much.\n",
216
+ "Your reply:\n",
217
+ "\u001b[0m\n",
218
+ "\n",
219
+ "\u001b[1m> Finished chain.\u001b[0m\n"
220
+ ]
221
+ },
222
+ {
223
+ "data": {
224
+ "text/plain": [
225
+ "{'context': 'o Mother: Some collagen tissue disorder, not sure what it was \\no Both parents have HTN and HLD, well controlled \\n● Social history * \\no Smoker, 10 sticks a day for the past 30 years \\no Drinker, can of beer every dinner and weekend binge drinking with friends \\no Diet, normally likes eating char kuay teow or fried carrot cake, doesn’t take much fruits or \\nvegetables \\no Occupation: Retired, former taxi driver \\no NIL exercise \\no Sexual hx unremarkable \\no NIL recent travel \\n● Ideas, Concerns and Expectations \\no Worried if he is having a heart attack, scared because his father had one \\no Wants the pain to stop \\n----------------------------------------------------------------------------------------------------------------------------- ---------\\n--------------------\\n● Neuro : \\no Syncope (one episode), dysarthria \\no NIL headaches or vision changes \\no NIL weakness or numbness \\no NIL head trauma/falls (did not sustain injury during syncopal episode) \\n● Gastro : \\no NIL nausea or vomiting \\no NIL abdo pain \\no NIL changes to bowel habit or blood in stool, constipation or diarrhoea \\n● Respi : \\no Some breathlessness, not excessive \\no NIL cough or haemoptysis \\n● Renal/Uro : \\no NIL urinary Sx - dysuria, haematuria \\n● MSK/Derm \\no NIL joint or muscle pains \\no NIL rash or skin changes \\n● Constitutional : NIL fever, weight loss, loss of appetite, night sweats \\n \\n----------------------------------------------------------------------------------------------------------------------------- --------- \\n \\nHistory taking: Others \\n● PMHx/Shx * \\no HTN, HLD, T2DM, diagnosed 7 years ago, poorly compliant with meds \\no History of biliary colic and gallstones, diagnosed 2 years ago \\no Recent hospitalisation and procedure done',\n",
226
+ " 'question': 'Are you okay?',\n",
227
+ " 'chat_history': 'Human: What did I ask?\\nAI: You asked if I had any chest pain.',\n",
228
+ " 'text': \"No, I'm not okay.\"}"
229
+ ]
230
+ },
231
+ "execution_count": 47,
232
+ "metadata": {},
233
+ "output_type": "execute_result"
234
+ }
235
+ ],
236
+ "source": [
237
+ "results = chain.invoke(\"Are you okay?\")\n",
238
+ "print(results.get(\"text\"))"
239
+ ]
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "execution_count": null,
244
+ "id": "68a5d4c4",
245
+ "metadata": {},
246
+ "outputs": [],
247
+ "source": []
248
+ }
249
+ ],
250
+ "metadata": {
251
+ "kernelspec": {
252
+ "display_name": "Python 3 (ipykernel)",
253
+ "language": "python",
254
+ "name": "python3"
255
+ },
256
+ "language_info": {
257
+ "codemirror_mode": {
258
+ "name": "ipython",
259
+ "version": 3
260
+ },
261
+ "file_extension": ".py",
262
+ "mimetype": "text/x-python",
263
+ "name": "python",
264
+ "nbconvert_exporter": "python",
265
+ "pygments_lexer": "ipython3",
266
+ "version": "3.8.5"
267
+ }
268
+ },
269
+ "nbformat": 4,
270
+ "nbformat_minor": 5
271
+ }