{ "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\": }\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 '. \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 }