summaryrefslogtreecommitdiff
path: root/notebooks/kg_rag_extended.ipynb
blob: f3e6d3a9c72cdfa006cb1011580e39d17221bb69 (plain)
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c11a1651-fef4-4fc9-9eaa-cc4ca6003444",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "This notebook is a standalone script. This requires different packages which is not mentioned in the kg-rag requirements.txt file.\n",
    "This notebook serves as a proof of concept that KG-RAG can be extended to other node types to answer more versatile biomedical questions.\n",
    "'''\n",
    "\n",
    "from llama_index.core import Settings\n",
    "from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding\n",
    "\n",
    "from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings\n",
    "\n",
    "from pinecone import Pinecone\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "import os\n",
    "import json\n",
    "\n",
    "from joblib import Memory\n",
    "from tenacity import retry, stop_after_attempt, wait_random_exponential\n",
    "import requests\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import ast\n",
    "from sklearn.metrics.pairwise import cosine_similarity\n",
    "import time\n",
    "import sys\n",
    "\n",
    "from IPython.display import clear_output\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e6665db2-ded1-40df-b64a-7a247d7511eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "INDEX_NAME = 'spoke-nodes'\n",
    "EMBEDDING_MODEL = 'text-embedding-ada-002'\n",
    "CHAT_MODEL = 'gpt-35-turbo'\n",
    "SENTENCE_EMBEDDING_MODEL_FOR_CONTEXT_RETRIEVAL = 'pritamdeka/S-PubMedBert-MS-MARCO'\n",
    "\n",
    "chat_memory = Memory('cachegpt', verbose=0)\n",
    "embed_memory = Memory('cache_embedding', verbose=0)\n",
    "\n",
    "SPOKE_API_URI = 'https://spoke.rbvi.ucsf.edu'\n",
    "\n",
    "KG_RAG_PARAMS = {\n",
    "    'CONTEXT_VOLUME' : 150,\n",
    "    'QUESTION_VS_CONTEXT_SIMILARITY_PERCENTILE_THRESHOLD' : 75,\n",
    "    'QUESTION_VS_CONTEXT_MINIMUM_SIMILARITY' : 0.5,\n",
    "}\n",
    "\n",
    "DEFAULT_SPOKE_API_PARAMS = {\n",
    "    'cutoff_Compound_max_phase' : 3,\n",
    "    'cutoff_Protein_source' : ['SwissProt'],\n",
    "    'cutoff_DaG_diseases_sources' : ['knowledge', 'experiments', 'textmining'],\n",
    "    'cutoff_DaG_textmining' : 3,\n",
    "    'cutoff_CtD_phase' : 3,\n",
    "    'cutoff_PiP_confidence' : 0.7,\n",
    "    'cutoff_ACTeG_level' : ['Low', 'Medium', 'High'],\n",
    "    'depth' : 1,\n",
    "    'cutoff_DpL_average_prevalence' : 0.001\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9caecf10-0157-4220-9e95-7d8fa828bc80",
   "metadata": {},
   "outputs": [],
   "source": [
    "BIOMEDICAL_ENTITY_EXTRACTION_SYSTEM_PROMPT = '''\n",
    "  You are an expert biomedical name entity extractor from a sentence. \n",
    "  You are able to extract entities such as Diseases, Genes, Variants, Proteins, Symptoms, Side effects, Organisms, Pathways, Compounds, Reactions. \n",
    "  Report your response as a JSON in the following format:\n",
    "  {\"Entities\": <List of extracted biomedical entities from the user input>}\n",
    "  IMPORTANT : Report the names mentioned in the user input, not the criteria they belong to. \n",
    "  \n",
    "  Example 1:\n",
    "  User input : What are the proteins encoded by PINK1?\n",
    "  Response: {\"Entities\" : [\"PINK1\"]}\n",
    "  \n",
    "  Example 2:\n",
    "  User input: Other than Parkinson's disease, what diseases do SNCA connect to?\n",
    "  Response: {\"Entities\": [\"Parkinson's disease\", \"SNCA\"]}\n",
    "'''\n",
    "\n",
    "\n",
    "KG_RAG_BASED_TEXT_GENERATION_SYSTEM_PROMPT = '''\n",
    "  You are an expert biomedical researcher. \n",
    "  For answering the Question at the end with brevity, you need to first read the Context provided. \n",
    "  Then give your final answer briefly, by citing the Provenance information from the context. \n",
    "  You can find Provenance from the Context statement 'Provenance of this association is <Provenance>'. \n",
    "  Do not forget to cite the Provenance information. Note that, if Provenance is 'GWAS' report it as 'GWAS Catalog'. \n",
    "  If Provenance is 'DISEASES' report it as 'DISEASES database - https://diseases.jensenlab.org'. \n",
    "  Additionally, when providing drug or medication suggestions, give maximum information available and then advise the user to seek guidance from a healthcare professional as a precautionary measure.\n",
    "'''\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "80db095c-bd5f-4cdc-b5d2-587a471e34fb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_sentence_transformer(sentence_embedding_model):\n",
    "    return SentenceTransformerEmbeddings(model_name=sentence_embedding_model)\n",
    "    \n",
    "def biomedical_entity_extractor(text, model):\n",
    "    prompt_updated = BIOMEDICAL_ENTITY_EXTRACTION_SYSTEM_PROMPT + \"\\n\" + \"Sentence : \" + text\n",
    "    resp = get_GPT_response(text, BIOMEDICAL_ENTITY_EXTRACTION_SYSTEM_PROMPT, model, temperature=0)\n",
    "    try:\n",
    "        entity_dict = json.loads(resp)\n",
    "        return entity_dict[\"Entities\"]\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "@embed_memory.cache\n",
    "def openai_embedding(embed_model, text):\n",
    "    node_embedding = embed_model.get_text_embedding(text)\n",
    "    return node_embedding \n",
    "\n",
    "\n",
    "@chat_memory.cache\n",
    "def get_GPT_response(instruction, system_prompt, chat_model_id, temperature=0.3):\n",
    "    return fetch_GPT_response(instruction, system_prompt, chat_model_id, temperature=temperature)\n",
    "\n",
    "@retry(wait=wait_random_exponential(min=10, max=30), stop=stop_after_attempt(5))\n",
    "def fetch_GPT_response(instruction, system_prompt, chat_model_id, temperature):\n",
    "    response = client.chat.completions.create(        \n",
    "        temperature=temperature,\n",
    "        model=chat_model_id,\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": system_prompt},\n",
    "            {\"role\": \"user\", \"content\": instruction}\n",
    "        ]\n",
    "    )\n",
    "    if response.choices:\n",
    "        return response.choices[0].message.content\n",
    "    else:\n",
    "        return 'Unexpected response'\n",
    "\n",
    "def retrieve_node(query, embed_model, k=1):\n",
    "    query_embedding = embed_model.get_text_embedding(query)\n",
    "    retrieved_doc = pinecone_index.query(\n",
    "        vector=query_embedding, \n",
    "        top_k=k, \n",
    "        include_metadata=True\n",
    "    )\n",
    "    node_name = list(map(lambda x:json.loads(x['metadata']['_node_content'])['text'], retrieved_doc['matches']))\n",
    "    node_type = list(map(lambda x:x['metadata']['node_type'], retrieved_doc['matches']))\n",
    "    return node_name, node_type\n",
    "\n",
    "\n",
    "def get_spoke_api_resp(base_uri, end_point, params=None):\n",
    "    uri = base_uri + end_point\n",
    "    if params:\n",
    "        return requests.get(uri, params=params)\n",
    "    else:\n",
    "        return requests.get(uri)\n",
    "\n",
    "@retry(wait=wait_random_exponential(min=10, max=30), stop=stop_after_attempt(5))\n",
    "def get_context_using_spoke_api(node_value, node_type, search_depth):\n",
    "    type_end_point = \"/api/v1/types\"\n",
    "    result = get_spoke_api_resp(SPOKE_API_URI, type_end_point)\n",
    "    data_spoke_types = result.json()\n",
    "    node_types = list(data_spoke_types[\"nodes\"].keys())\n",
    "    edge_types = list(data_spoke_types[\"edges\"].keys())\n",
    "    node_types_to_remove = [\"DatabaseTimestamp\", \"Version\"]\n",
    "    filtered_node_types = [node_type for node_type in node_types if node_type not in node_types_to_remove]\n",
    "    api_params = {\n",
    "        'node_filters' : filtered_node_types,\n",
    "        'edge_filters': edge_types,\n",
    "        'cutoff_Compound_max_phase': DEFAULT_SPOKE_API_PARAMS['cutoff_Compound_max_phase'],\n",
    "        'cutoff_Protein_source': DEFAULT_SPOKE_API_PARAMS['cutoff_Protein_source'],\n",
    "        'cutoff_DaG_diseases_sources': DEFAULT_SPOKE_API_PARAMS['cutoff_DaG_diseases_sources'],\n",
    "        'cutoff_DaG_textmining': DEFAULT_SPOKE_API_PARAMS['cutoff_DaG_textmining'],\n",
    "        'cutoff_CtD_phase': DEFAULT_SPOKE_API_PARAMS['cutoff_CtD_phase'],\n",
    "        'cutoff_PiP_confidence': DEFAULT_SPOKE_API_PARAMS['cutoff_PiP_confidence'],\n",
    "        'cutoff_ACTeG_level': DEFAULT_SPOKE_API_PARAMS['cutoff_ACTeG_level'],\n",
    "        'cutoff_DpL_average_prevalence': DEFAULT_SPOKE_API_PARAMS['cutoff_DpL_average_prevalence'],\n",
    "        'depth' : search_depth\n",
    "    }\n",
    "    attribute = \"name\"\n",
    "    nbr_end_point = \"/api/v1/neighborhood/{}/{}/{}\".format(node_type, attribute, node_value)\n",
    "    result = get_spoke_api_resp(SPOKE_API_URI, nbr_end_point, params=api_params)\n",
    "    node_context = result.json()\n",
    "    if len(node_context) == 0: \n",
    "        return None, None\n",
    "    nbr_nodes = []\n",
    "    nbr_edges = []\n",
    "    for item in node_context:\n",
    "        if \"_\" not in item[\"data\"][\"neo4j_type\"]:\n",
    "            try:\n",
    "                if item[\"data\"][\"neo4j_type\"] == \"Protein\":\n",
    "                    nbr_nodes.append((item[\"data\"][\"neo4j_type\"], item[\"data\"][\"id\"], item[\"data\"][\"properties\"][\"description\"]))\n",
    "                else:\n",
    "                    nbr_nodes.append((item[\"data\"][\"neo4j_type\"], item[\"data\"][\"id\"], item[\"data\"][\"properties\"][\"name\"]))\n",
    "            except:\n",
    "                nbr_nodes.append((item[\"data\"][\"neo4j_type\"], item[\"data\"][\"id\"], item[\"data\"][\"properties\"][\"identifier\"]))\n",
    "        elif \"_\" in item[\"data\"][\"neo4j_type\"]:\n",
    "            try:\n",
    "                provenance = \", \".join(item[\"data\"][\"properties\"][\"sources\"])\n",
    "            except:\n",
    "                try:\n",
    "                    provenance = item[\"data\"][\"properties\"][\"source\"]\n",
    "                    if isinstance(provenance, list):\n",
    "                        provenance = \", \".join(provenance)                    \n",
    "                except:\n",
    "                    try:                    \n",
    "                        preprint_list = ast.literal_eval(item[\"data\"][\"properties\"][\"preprint_list\"])\n",
    "                        if len(preprint_list) > 0:                                                    \n",
    "                            provenance = \", \".join(preprint_list)\n",
    "                        else:\n",
    "                            pmid_list = ast.literal_eval(item[\"data\"][\"properties\"][\"pmid_list\"])\n",
    "                            pmid_list = map(lambda x:\"pubmedId:\"+x, pmid_list)\n",
    "                            if len(pmid_list) > 0:\n",
    "                                provenance = \", \".join(pmid_list)\n",
    "                            else:\n",
    "                                provenance = \"Based on data from Institute For Systems Biology (ISB)\"\n",
    "                    except:                                \n",
    "                        provenance = \"SPOKE-KG\"     \n",
    "            try:\n",
    "                evidence = item[\"data\"][\"properties\"]\n",
    "            except:\n",
    "                evidence = None\n",
    "            nbr_edges.append((item[\"data\"][\"source\"], item[\"data\"][\"neo4j_type\"], item[\"data\"][\"target\"], provenance, evidence))\n",
    "    nbr_nodes_df = pd.DataFrame(nbr_nodes, columns=[\"node_type\", \"node_id\", \"node_name\"])\n",
    "    nbr_edges_df = pd.DataFrame(nbr_edges, columns=[\"source\", \"edge_type\", \"target\", \"provenance\", \"evidence\"])\n",
    "    merge_1 = pd.merge(nbr_edges_df, nbr_nodes_df, left_on=\"source\", right_on=\"node_id\").drop(\"node_id\", axis=1)\n",
    "    merge_1.loc[:,\"node_name\"] = merge_1.node_type + \" \" + merge_1.node_name\n",
    "    merge_1.drop([\"source\", \"node_type\"], axis=1, inplace=True)\n",
    "    merge_1 = merge_1.rename(columns={\"node_name\":\"source\"})\n",
    "    merge_2 = pd.merge(merge_1, nbr_nodes_df, left_on=\"target\", right_on=\"node_id\").drop(\"node_id\", axis=1)\n",
    "    merge_2.loc[:,\"node_name\"] = merge_2.node_type + \" \" + merge_2.node_name\n",
    "    merge_2.drop([\"target\", \"node_type\"], axis=1, inplace=True)\n",
    "    merge_2 = merge_2.rename(columns={\"node_name\":\"target\"})\n",
    "    merge_2 = merge_2[[\"source\", \"edge_type\", \"target\", \"provenance\", \"evidence\"]]\n",
    "    merge_2.loc[:, \"predicate\"] = merge_2.edge_type.apply(lambda x:x.split(\"_\")[0])\n",
    "    merge_2.loc[:, \"context\"] =  merge_2.source + \" \" + merge_2.predicate.str.lower() + \" \" + merge_2.target + \" and Provenance of this association is \" + merge_2.provenance + \". \"\n",
    "    context = merge_2.context.str.cat(sep=' ')\n",
    "    # context += node_value + \" has a \" + node_context[0][\"data\"][\"properties\"][\"source\"] + \" identifier of \" + node_context[0][\"data\"][\"properties\"][\"identifier\"] + \" and Provenance of this is from \" + node_context[0][\"data\"][\"properties\"][\"source\"] + \". \"\n",
    "    return context, merge_2\n",
    "\n",
    "\n",
    "def get_pruned_context(query, entities, embed_model, search_depth, edge_evidence, context_sim_threshold, context_sim_min_threshold, context_volume):\n",
    "    if entities:\n",
    "        nodes = []\n",
    "        node_types = []\n",
    "        for entity in entities:\n",
    "            node_name_list, node_type_list = retrieve_node(entity, openai_embed_model, k=2)\n",
    "            nodes.extend(node_name_list)\n",
    "            node_types.extend(node_type_list)\n",
    "        max_number_of_high_similarity_context_per_node = int(context_volume/len(nodes))\n",
    "        # query_embedding = openai_embedding(embed_model, query)\n",
    "        query_embedding = embed_model.embed_query(query)\n",
    "        node_context_extracted = ''\n",
    "        for node_idx, node in enumerate(nodes):\n",
    "            node_context, context_table = get_context_using_spoke_api(\n",
    "                node_value=node,\n",
    "                node_type = node_types[node_idx],\n",
    "                search_depth=search_depth\n",
    "            )        \n",
    "            if not node_context:\n",
    "                node_context_extracted += f'No context related to {node} available in SPOKE'\n",
    "                continue\n",
    "            context_table.loc[:, 'context'] = context_table.context.apply(lambda x:x.strip())\n",
    "            node_context_list = node_context.split(\". \")\n",
    "            node_context_list = list(map(lambda x:x.strip(), node_context_list))\n",
    "            if len(node_context_list) < 4500000000000:\n",
    "                node_context_list = ['empty string' if item == '' else item for item in node_context_list]\n",
    "                # node_context_embeddings = [openai_embedding(embed_model, node_context) for node_context in node_context_list]            \n",
    "                node_context_embeddings = embed_model.embed_documents(node_context_list)\n",
    "                similarities = [cosine_similarity(np.array(query_embedding).reshape(1, -1), np.array(node_context_embedding).reshape(1, -1)) for node_context_embedding in node_context_embeddings]\n",
    "                similarities = sorted([(e, i) for i, e in enumerate(similarities)], reverse=True)\n",
    "                percentile_threshold = np.percentile([s[0] for s in similarities], context_sim_threshold)\n",
    "                high_similarity_indices = [s[1] for s in similarities if s[0] > percentile_threshold and s[0] > context_sim_min_threshold]\n",
    "                if len(high_similarity_indices) > max_number_of_high_similarity_context_per_node:\n",
    "                    high_similarity_indices = high_similarity_indices[:max_number_of_high_similarity_context_per_node]\n",
    "                high_similarity_context = [node_context_list[index].strip() + '.' for index in high_similarity_indices]\n",
    "                if edge_evidence:                \n",
    "                    # if len(high_similarity_context) > 1:\n",
    "                    #     high_similarity_context = list(map(lambda x:x+'.', high_similarity_context))\n",
    "                    context_table = context_table[context_table.context.isin(high_similarity_context)]\n",
    "                    context_table.loc[:, \"context\"] =  context_table.source + \" \" + context_table.predicate.str.lower() + \" \" + context_table.target + \" and Provenance of this association is \" + context_table.provenance + \" and attributes associated with this association is in the following JSON format:\\n \" + context_table.evidence.astype('str') + \"\\n\\n\"                \n",
    "                    node_context_extracted += context_table.context.str.cat(sep=' ')                      \n",
    "                else:\n",
    "                    node_context_extracted += \". \".join(high_similarity_context)\n",
    "                    node_context_extracted += \". \"\n",
    "            else:\n",
    "                if edge_evidence:\n",
    "                    context_table.loc[:, \"context\"] =  context_table.source + \" \" + context_table.predicate.str.lower() + \" \" + context_table.target + \" and Provenance of this association is \" + context_table.provenance + \" and attributes associated with this association is in the following JSON format:\\n \" + context_table.evidence.astype('str') + \"\\n\\n\"                \n",
    "                    node_context_extracted += context_table.context.str.cat(sep=' ')\n",
    "                else:\n",
    "                    node_context_extracted += \". \".join(node_context_list)                \n",
    "        return node_context_extracted\n",
    "    else:\n",
    "        return 'No biomedical entities detected in the given query.'\n",
    "\n",
    "def stream_out(output):\n",
    "    CHUNK_SIZE = int(round(len(output)/50))\n",
    "    SLEEP_TIME = 0.1\n",
    "    for i in range(0, len(output), CHUNK_SIZE):\n",
    "        print(output[i:i+CHUNK_SIZE], end='')\n",
    "        sys.stdout.flush()\n",
    "        time.sleep(SLEEP_TIME)\n",
    "    print(\"\\n\")\n",
    "\n",
    "def run(query):\n",
    "    entity = biomedical_entity_extractor(query, CHAT_MODEL)\n",
    "    kg_cntxt = get_pruned_context(\n",
    "        query, \n",
    "        entity,\n",
    "        bert_embed_model,\n",
    "        1,\n",
    "        True,\n",
    "        KG_RAG_PARAMS['QUESTION_VS_CONTEXT_SIMILARITY_PERCENTILE_THRESHOLD'],\n",
    "        KG_RAG_PARAMS['QUESTION_VS_CONTEXT_MINIMUM_SIMILARITY'],\n",
    "        KG_RAG_PARAMS['CONTEXT_VOLUME']\n",
    "    )\n",
    "    enriched_prompt = 'Context: '+ kg_cntxt + '\\n' + 'Question: ' + query \n",
    "    llm_response = get_GPT_response(\n",
    "        enriched_prompt, \n",
    "        KG_RAG_BASED_TEXT_GENERATION_SYSTEM_PROMPT, \n",
    "        'gpt-35-turbo-16k', \n",
    "        temperature=0.1\n",
    "    )\n",
    "    stream_out(llm_response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0b997ed9-9676-4a27-89ac-4425ec5bfc34",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/root/anaconda3/envs/kg_rag_interative/lib/python3.10/site-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "load_dotenv(os.path.join(os.path.expanduser('~'), '.gpt_config.env'))\n",
    "api_key = os.environ.get('API_KEY')\n",
    "azure_endpoint = os.environ.get('RESOURCE_ENDPOINT')\n",
    "api_version = os.environ.get('API_VERSION')\n",
    "\n",
    "load_dotenv(os.path.join(os.path.expanduser('~'), '.pinecone_config.env'))\n",
    "pinecone_api_key = os.environ.get('PINECONE_API_KEY')\n",
    "\n",
    "\n",
    "if os.environ.get('RESOURCE_ENDPOINT'):\n",
    "    from openai import AzureOpenAI    \n",
    "    client = AzureOpenAI(\n",
    "      api_key = os.environ.get('API_KEY'),  \n",
    "      api_version = os.environ.get('API_VERSION'),\n",
    "      azure_endpoint = os.environ.get('RESOURCE_ENDPOINT')\n",
    "    )\n",
    "else:\n",
    "    from openai import OpenAI\n",
    "    client = OpenAI(api_key = os.environ.get('API_KEY'))\n",
    "\n",
    "openai_embed_model = AzureOpenAIEmbedding(\n",
    "    model=EMBEDDING_MODEL,\n",
    "    deployment_name=EMBEDDING_MODEL,\n",
    "    api_key=api_key,\n",
    "    azure_endpoint=azure_endpoint,\n",
    "    api_version=api_version,\n",
    ")\n",
    "\n",
    "bert_embed_model = load_sentence_transformer(SENTENCE_EMBEDDING_MODEL_FOR_CONTEXT_RETRIEVAL)\n",
    "\n",
    "Settings.embed_model = openai_embed_model\n",
    "\n",
    "pc = Pinecone(api_key=pinecone_api_key)\n",
    "\n",
    "pinecone_index = pc.Index(INDEX_NAME)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "4e992a07-ef14-4737-9d41-943df6b44276",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The PAH gene encodes the protein Phenylalanine-4-hydroxylase (PAH). [Provenance: UniProt]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\n",
    "query = \"What protein does PAH gene encode?\"\n",
    "run(query)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "d0686abc-f99e-478d-8532-e09f2fc1d759",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Phenylalanine-4-hydroxylase (PAH) catalyzes the following reactions:\n",
      "1. Reaction: L-phenylalanine + tetrahydrobiopterin + oxygen <=> dihydrobiopterin + L-tyrosine + H2O\n",
      "   Provenance: KEGG database - https://www.genome.jp/kegg/\n",
      "\n",
      "2. Reaction: L-phenylalanine + tetrahydrobiopterin + oxygen <=> L-tyrosine + 4a-hydroxytetrahydrobiopterin\n",
      "   Provenance: KEGG database - https://www.genome.jp/kegg/\n",
      "\n",
      "3. Reaction: L-phenylalanine + tetrahydropteridine + oxygen <=> L-tyrosine + 4a-hydroxy-5,6,7,8-tetrahydropteridine\n",
      "   Provenance: KEGG database - https://www.genome.jp/kegg/\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\n",
    "query = \"What reactions do phenylalanine-4-hydroxylase catalyse?\"\n",
    "run(query)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "ed98da54-55dc-4e72-a2f8-d75a59884b41",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Yes, Balaglitazone downregulates several genes. The genes that are downregulated by Balaglitazone include ADI1, ACOT9, IFRD2, CCNB1, H2BC12, RPS5, DHRS7, UGDH, KDELR2, WASHC4, LYPLA1, PRPF4, GOLT1B, HSPB1, AKR7A2, BAG3, GNAS, SOX4, DUSP6, CDC25B, FAT1, PRSS23, GRN, CANT1, HOXA10, IER3, PXN, CTNND1, BNIP3, HDAC6, KDM3A, SPDEF, ARID5B, ST6GALNAC2, DUSP4, TRAPPC6A, EPB41L2, IQGAP1, ASAH1, PHGDH, RGS2, FOXO4, TIMELESS, TCEA2, CD44, CDH3, DNAJA3, CDKN1B, PIK3R3, C2CD5, GLRX, HAT1, PTPRK, H2BC5, AKR7A2, ITFG1, KIFBP, S100A6, TRIM2, SLC2A6, ALDOC, ST3GAL5, NUCB2, PPARG, PTK2, H2BC12, APPBP2, ETV1, ERBB2, BNIP3L, TUBA1A, TGFB3, HMG20B, ALDH7A1, ACAT2, NIPAL3, ZNF33B, STMN1, DYNLT3, DNMT3A, EGF, CAST. [Provenance: CMAP/LINCS compound (trt_cp)]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\n",
    "query = \"Does Balaglitazone downregulate any genes?\"\n",
    "run(query)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e51596f6-b24b-4e2a-84a1-db2210854349",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}