{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -qU langchain_openai langchain_huggingface langchain_core==0.2.38 langchain langchain_community langchain-text-splitters langgraph arxiv duckduckgo_search==5.3.1b1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -qU qdrant-client pymupdf pandas faiss-cpu unstructured==0.15.7 python-pptx==1.0.2 nltk==3.9.1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -qU sentence_transformers datasets pyarrow==14.0.1 biopytho" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/opt/anaconda3/envs/aie4-demo/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "from langchain_core.messages import SystemMessage, HumanMessage\n", "from langchain.tools import StructuredTool\n", "from langchain.agents import initialize_agent, Tool, AgentType\n", "from langchain_openai import ChatOpenAI\n", "from langgraph.graph.message import add_messages\n", "from langgraph.graph import StateGraph, END\n", "from pydantic import BaseModel\n", "from typing import List, TypedDict, Annotated\n", "import xml.etree.ElementTree as ET\n", "import uuid\n", "import re\n", "from langgraph.prebuilt import ToolNode\n", "from Bio import Entrez\n", "from langchain_qdrant import QdrantVectorStore\n", "from qdrant_client import QdrantClient\n", "from qdrant_client.http.models import Distance, VectorParams\n", "from qdrant_client.http.models import Filter, FieldCondition, MatchValue\n", "from langchain_huggingface import HuggingFaceEmbeddings\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "from langchain.chains import (\n", " ConversationalRetrievalChain,\n", ")\n", "from langchain.docstore.document import Document\n", "from langchain.memory import ChatMessageHistory, ConversationBufferMemory\n", "from transformers import GPT2Tokenizer\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import getpass\n", "\n", "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from Bio import Entrez\n", "import xml.etree.ElementTree as ET\n", "# Set your Entrez email\n", "Entrez.email = \"yinong313@gmail.com\"" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "from IPython.display import display, Markdown\n", "\n", "def pretty_print(message: str) -> None:\n", " display(Markdown(f\"```markdown\\n{message}\\n```\"))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/opt/anaconda3/envs/aie4-demo/lib/python3.11/site-packages/transformers/tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n", " warnings.warn(\n" ] } ], "source": [ "from sentence_transformers import SentenceTransformer, util\n", "\n", "# Load the pre-trained model for embeddings (you can choose a different model if preferred)\n", "semantic_model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "\n", "embedding_model = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n", "corpus = {}\n", "consolidated_results={}\n", "pmids = ['39416351','39411615','39410730','39392845']\n", "os.makedirs('./data/downloaded_paper', exist_ok=True)\n", "\n", "# Fetch records from PubMed Central (PMC)\n", "handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n", "records = Entrez.read(handle)\n", "handle.close()\n", "\n", "full_articles = []\n", "for record in records['PubmedArticle']:\n", " try:\n", " title = record['MedlineCitation']['Article']['ArticleTitle']\n", " pmid = record['MedlineCitation']['PMID']\n", " pmc_id = 'nan'\n", " pmc_id_temp = record['PubmedData']['ArticleIdList']\n", " \n", " # Extract PMC ID if available\n", " for ele in pmc_id_temp:\n", " if ele.attributes['IdType'] == 'pmc':\n", " pmc_id = ele.replace('PMC', '')\n", " break\n", "\n", " # Fetch full article from PMC\n", " if pmc_id != 'nan':\n", " handle = Entrez.efetch(db=\"pmc\", id=pmc_id, rettype=\"full\", retmode=\"xml\")\n", " full_article = handle.read()\n", " handle.close()\n", "\n", " # Split the full article into chunks\n", " cleaned_full_article = extract_text_from_pmc_xml(full_article)\n", " full_articles.append({\n", " \"PMID\": pmid,\n", " \"Title\": title,\n", " \"FullText\": cleaned_full_article # Add chunked text\n", " })\n", " output_nm = 'PMID:' + pmid + ' ' + \" \".join(title.split(' ')[0:3]) + '.txt'\n", " output_dir = os.path.join('./data/downloaded_paper', output_nm)\n", " with open(output_dir, \"w\") as file:\n", " # Write the text to the file\n", " file.write(cleaned_full_article)\n", " else:\n", " full_articles.append({\"PMID\": pmid, \"Title\": title, \"FullText\": \"cannot fetch\"})\n", " except KeyError:\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### MVP2: More function added (pull full-text and do simple RAG)\n", "- Note right now it can only pull free articles which contains something like \"StringElement('PMC11276461', attributes={'IdType': 'pmc'})\" - see below example.\n", "- Then it will use '11276461' from 'PMC11276461' to pull full artile." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[StringElement('39063396', attributes={'IdType': 'pubmed'}), StringElement('PMC11276461', attributes={'IdType': 'pmc'}), StringElement('10.3390/ijerph21070819', attributes={'IdType': 'doi'}), StringElement('ijerph21070819', attributes={'IdType': 'pii'})]\n" ] } ], "source": [ "\"\"\"Fetch full text from PubMed Central for given PMIDs.\"\"\"\n", "handle = Entrez.efetch(db=\"pubmed\", id=\"39063396\", retmode=\"xml\")\n", "records = Entrez.read(handle)\n", "handle.close()\n", "for record in records['PubmedArticle']:\n", " pmc_id_temp = record['PubmedData']['ArticleIdList']\n", " print(pmc_id_temp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### MVP2: Whole Flow\n", "- Agent with 3 tools\n", " - pubmed_tool,\n", " - semantic_screening_tool,\n", " - rag_tool" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_t7Rybf2ucTJRAnwgqU37wgwQ', 'function': {'arguments': '{\"query\":\"(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))\"}', 'name': 'PubMed_Search_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 59, 'prompt_tokens': 496, 'total_tokens': 555, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-157fed54-d117-486f-af4a-b4310c0b6854-0', tool_calls=[{'name': 'PubMed_Search_Tool', 'args': {'query': '(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))'}, 'id': 'call_t7Rybf2ucTJRAnwgqU37wgwQ', 'type': 'tool_call'}], usage_metadata={'input_tokens': 496, 'output_tokens': 59, 'total_tokens': 555})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'action'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[ToolMessage(content='[{\"PMID\": \"39291999\", \"Title\": \"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\", \"Abstract\": \"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"}, {\"PMID\": \"39063396\", \"Title\": \"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\", \"Abstract\": \"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all p < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both p < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"}, {\"PMID\": \"39051414\", \"Title\": \"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\", \"Abstract\": \"Background: This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. Methods: A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. Results: Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (p = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, p = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, p = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (p < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (p = 0.005). Conclusions: The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"}]', name='PubMed_Search_Tool', tool_call_id='call_t7Rybf2ucTJRAnwgqU37wgwQ')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_hTrHb9Av7Uxriu6Z7woR2bMi', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\"}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 30, 'prompt_tokens': 1469, 'total_tokens': 1499, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-8715af33-7c99-47b8-858d-950654c6f8e2-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic'}, 'id': 'call_hTrHb9Av7Uxriu6Z7woR2bMi', 'type': 'tool_call'}], usage_metadata={'input_tokens': 1469, 'output_tokens': 30, 'total_tokens': 1499})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'action'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[ToolMessage(content=\"Error: 1 validation error for AbstractScreeningInput\\nabstracts\\n Field required [type=missing, input_value={'criteria': 'comparison ...ter the COVID pandemic'}, input_type=dict]\\n For further information visit https://errors.pydantic.dev/2.9/v/missing\\n Please fix your mistakes.\", name='Semantic_Abstract_Screening_Tool', tool_call_id='call_hTrHb9Av7Uxriu6Z7woR2bMi')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_wXc1b5bfjTfc94c8GcyrlELu', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\",\"abstracts\":[{\"PMID\":\"39291999\",\"Title\":\"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\",\"Abstract\":\"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"},{\"PMID\":\"39063396\",\"Title\":\"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\",\"Abstract\":\"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all p < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both p < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"},{\"PMID\":\"39051414\",\"Title\":\"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\",\"Abstract\":\"Background: This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. Methods: A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. Results: Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (p = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, p = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, p = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (p < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (p = 0.005). Conclusions: The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"}]}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 920, 'prompt_tokens': 1577, 'total_tokens': 2497, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-a03c1cc7-0fb3-4299-8bae-89409e0713b9-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic', 'abstracts': [{'PMID': '39291999', 'Title': 'Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.', 'Abstract': 'Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.'}, {'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'Abstract': 'During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all p < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both p < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.'}, {'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'Abstract': 'Background: This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. Methods: A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. Results: Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (p = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, p = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, p = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (p < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (p = 0.005). Conclusions: The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.'}]}, 'id': 'call_wXc1b5bfjTfc94c8GcyrlELu', 'type': 'tool_call'}], usage_metadata={'input_tokens': 1577, 'output_tokens': 920, 'total_tokens': 2497})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'action'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[ToolMessage(content='[{\"PMID\": \"39291999\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.31 < threshold 0.4\"}, {\"PMID\": \"39063396\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.53 >= threshold 0.4\"}, {\"PMID\": \"39051414\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.45 >= threshold 0.4\"}]', name='Semantic_Abstract_Screening_Tool', tool_call_id='call_wXc1b5bfjTfc94c8GcyrlELu')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_KMTLEk1pHVymBlm4S9Geeig1', 'function': {'arguments': '{\"pmids\":[\"39063396\",\"39051414\"],\"query\":\"data source information used in each paper (especially medical records)\"}', 'name': 'Fetch_Extract_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 40, 'prompt_tokens': 2608, 'total_tokens': 2648, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_2f406b9113', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-ea57b535-c3c0-437a-969e-7b1b69c3a8be-0', tool_calls=[{'name': 'Fetch_Extract_Tool', 'args': {'pmids': ['39063396', '39051414'], 'query': 'data source information used in each paper (especially medical records)'}, 'id': 'call_KMTLEk1pHVymBlm4S9Geeig1', 'type': 'tool_call'}], usage_metadata={'input_tokens': 2608, 'output_tokens': 40, 'total_tokens': 2648})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n", " warnings.warn(\n", "C:\\Users\\YLiang\\AppData\\Local\\Temp\\ipykernel_35360\\1582393269.py:272: LangChainDeprecationWarning: The method `Chain.__call__` was deprecated in langchain 0.1.0 and will be removed in 1.0. Use invoke instead.\n", " result = qa_chain({\"question\": query})\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Receiving update from node: 'action'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[ToolMessage(content='{\\'39063396\\': {\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'Generated Answer\\': \"The data source used in the study was the UMMC enterprise data warehouse, which contained medical records. The medical records were extracted from this data warehouse to examine sociodemographic characteristics, healthcare resource utilization (HCRU), and medical expenditures between telemedicine (TMH) and non-telemedicine cohorts. The sociodemographic characteristics considered in the study included age, sex, race, primary insurance, rurality, and household income. It\\'s important to note that due to the presence of protected health information (PHI) and in accordance with IRB regulations, the dataset cannot be made publicly available.\", \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'54fd6497-fa85-47af-9cb6-2bf2ff99457d\\', \\'_id\\': \\'4bfc2c9803084a908b9224c458e30dfa\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Institutional Review Board Statement\\\\n\\\\nThis study was approved by the Institutional Review Board (IRB) of the University of Mississippi Medical Center (ID: UMMC-IRB-2022-458; date of approval: 12 April 2023).\\\\n\\\\nInformed Consent Statement\\\\n\\\\nPatient consent was waived following Federal Regulations set forth by 45 CFR 46.116(f).\\\\n\\\\nData Availability Statement\\\\n\\\\nDue to the presence of protected health information (PHI) and in accordance with IRB regulations, the dataset cannot be made publicly available.\\\\n\\\\nConflicts of Interest\\\\n\\\\nLSL was an employee of ConcertAI during the conduct of this study. Other authors have no conflicts of interest to declare.\\\\n\\\\nReferences\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM.\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM of subjects residing in rural areas.\\\\n\\\\nSociodemographic characteristics of all study subjects and using TMH.\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'794d626e-8bd7-4426-abdf-ae96f1079c9d\\', \\'_id\\': \\'d9173cc20922455eabcc06e47bed7d7a\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Medical records were extracted from the UMMC enterprise data warehouse to examine sociodemographic characteristics, HCRU, and medical expenditures between TMH and non-TMH cohorts. Sociodemographic characteristics considered in this study include age, sex, race, primary insurance, rurality, and household income. Age was categorized into four groups: 18 to 34 years, 35 to 49 years, 50 to 64 years, and 65 years or older. Race was categorized into three groups: White/Caucasian, Black/African American, and other. The other race group included subjects identifying as American Indian, Alaska Native, Native Hawaiian, other Pacific Islander, Mississippi Band Choctaw Indian, Asian, Hispanic, Multiracial, and others. Subjects of unknown race or those who refused to provide this information were considered missing. Primary insurance was defined as the insurance most frequently used for mental and behavioral health visits during the study period and was categorized into four groups: commercial\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'c34872ae-f47d-418b-a4a8-d69f86e50aca\\', \\'_id\\': \\'dfbd789180d74bce8c6a1e711db54c1e\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'were included, future studies should consider multiple academic centers or healthcare entities to validate the robustness of findings across different geographic regions and patient populations. Additionally, there is potential for missing data since patients may seek care at multiple institutions. This limitation was mitigated by limiting the study sample to patients who had evidence of regular care visits at UMMC and had evidence of insurance coverage for at least one visit. However, as the study sample consisted of insured patients who regularly seek healthcare from UMMC, it may not represent the entire population of Mississippi, such as those without any healthcare access, thereby limiting generalizability to uninsured populations. Future research should identify and address barriers faced by uninsured populations to provide a more comprehensive understanding of TMH utilization and its impact on HCRU and medical expenditures.\\')]}, \\'39051414\\': {\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'Generated Answer\\': \\'The data source used in the study described is the 2020 National Inpatient Sample (NIS) dataset. This dataset covers hospitalizations in the United States from 1 January 2020 to 31 December 2020 and is derived from the State Inpatient Databases (SIDs). The NIS dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ). It is a de-identified, publicly available inpatient database that represents an estimated 98% of the U.S. population. The dataset employs a 20% stratified discharge sample, which is then weighted to ensure national representativeness.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'731882ce-e143-49ba-8a9f-06eaa42adb10\\', \\'_id\\': \\'41646d28fb6b43bb89ab12bc8e54a654\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'3. Materials and Methods\\\\n\\\\n\\\\n\\\\n3.1. Study Design and Database Description\\\\n\\\\nUtilizing the 2020 National Inpatient Sample (NIS) dataset, we conducted a retrospective cohort analysis of adult patients admitted with a primary diagnosis of sickle cell crisis in the United States. The NIS 2020 dataset specifically covers hospitalizations within the period from 1 January 2020 to 31 December 2020. It derives from the State Inpatient Databases (SIDs) that cover an estimated 98% of the U.S. population. As part of the Healthcare Cost and Utilization Project sponsored by Agency for Healthcare Research and Quality (AHRQ), the NIS is the most extensive, de-identified, publicly available inpatient database in the U.S. This database employs a 20% stratified discharge sample, which is then weighted relative to the total discharges to ensure national representativeness.\\\\n\\\\n\\\\n\\\\n3.2. Study Patients\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'de21c6f4-c463-4566-afcb-2ba1bfbf407d\\', \\'_id\\': \\'fd742ac79e9348dd8736601f0b7de762\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Our study has some limitations. Because it was retrospective, we could not fully randomize exposure. However, by employing multivariate regression models that took into account various patient and hospital traits, as well as co-morbidities, we made an effort to reduce confounding. Still, even with these measures, there is a slight chance that residual confounding occurred. To identify patients with sickle cell crisis and COVID-19, we opted for ICD-10 codes rather than clinical measures. This might have resulted in diagnosis misclassification. Yet, the legitimacy of using ICD-10 codes for this purpose is backed by earlier studies that utilized HCUP data [\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'f37a502c-2cce-40d1-a44f-c932d4b85d31\\', \\'_id\\': \\'a365b4cd3a8c418bb17b5d324bea35ab\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Supplementary Materials\\\\n\\\\nThe following supporting information can be downloaded at:\\\\n\\\\nAuthor Contributions\\\\n\\\\nConceptualization, Z.H.B. and M.H.; methodology, Z.H.B.; formal analysis, Z.H.B.; investigation and analysis, Z.H.B.; writing—original draft preparation, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; writing—review and editing, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; visualization, Y.B. and C.L.B.; supervision, Y.B. and C.L.B. All authors have read and agreed to the published version of the manuscript.\\\\n\\\\nInstitutional Review Board Statement\\\\n\\\\nEthical review and approval were waived for this study as it does not involve research with human subjects and the dataset used is de-identified.\\\\n\\\\nInformed Consent Statement\\\\n\\\\nIt is a retrospective study using publicly available de-identified data and consent is not required.\\\\n\\\\nData Availability Statement\\')]}}', name='Fetch_Extract_Tool', tool_call_id='call_KMTLEk1pHVymBlm4S9Geeig1')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='### Summary of the Process and Findings:\\n\\n1. **Search Query Execution:**\\n - I used the PubMed search tool with the query focused on the impact of COVID-19 on healthcare resource utilization. The search returned three relevant papers.\\n\\n2. **Abstract Screening:**\\n - The abstracts were screened based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic.\\n - **Paper 1 (PMID: 39291999):** Excluded due to a low similarity score (0.31), indicating it did not meet the criteria.\\n - **Paper 2 (PMID: 39063396):** Included with a similarity score of 0.53, indicating it met the criteria.\\n - **Paper 3 (PMID: 39051414):** Included with a similarity score of 0.45, indicating it met the criteria.\\n\\n3. **Full-Text Retrieval and Information Extraction:**\\n - For the included papers, I fetched the full-text articles and extracted information regarding the data sources used, especially focusing on medical records.\\n\\n - **Paper 2 (PMID: 39063396):**\\n - **Title:** Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\n - **Data Source:** The study used medical records extracted from the UMMC enterprise data warehouse. This data was used to analyze sociodemographic characteristics, healthcare resource utilization, and medical expenditures between telemedicine and non-telemedicine cohorts. The dataset was not publicly available due to protected health information (PHI) regulations.\\n\\n - **Paper 3 (PMID: 39051414):**\\n - **Title:** Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\n - **Data Source:** The study utilized the 2020 National Inpatient Sample (NIS) dataset, which is a de-identified, publicly available inpatient database representing hospitalizations in the U.S. The dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ).\\n\\n### Conclusion:\\nThe process involved searching for relevant literature, screening abstracts based on specific criteria, and extracting detailed data source information from the full-text articles. The included studies provided insights into the impact of COVID-19 on healthcare resource utilization, using robust data sources like institutional data warehouses and national inpatient samples.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 519, 'prompt_tokens': 4823, 'total_tokens': 5342, 'prompt_tokens_details': {'cached_tokens': 1408}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'stop', 'logprobs': None}, id='run-b2a9db6e-f642-44ac-8c7d-dba2345c8ee7-0', usage_metadata={'input_tokens': 4823, 'output_tokens': 519, 'total_tokens': 5342})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Final message content from the last chunk:\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "### Summary of the Process and Findings:\n", "\n", "1. **Search Query Execution:**\n", " - I used the PubMed search tool with the query focused on the impact of COVID-19 on healthcare resource utilization. The search returned three relevant papers.\n", "\n", "2. **Abstract Screening:**\n", " - The abstracts were screened based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic.\n", " - **Paper 1 (PMID: 39291999):** Excluded due to a low similarity score (0.31), indicating it did not meet the criteria.\n", " - **Paper 2 (PMID: 39063396):** Included with a similarity score of 0.53, indicating it met the criteria.\n", " - **Paper 3 (PMID: 39051414):** Included with a similarity score of 0.45, indicating it met the criteria.\n", "\n", "3. **Full-Text Retrieval and Information Extraction:**\n", " - For the included papers, I fetched the full-text articles and extracted information regarding the data sources used, especially focusing on medical records.\n", "\n", " - **Paper 2 (PMID: 39063396):**\n", " - **Title:** Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\n", " - **Data Source:** The study used medical records extracted from the UMMC enterprise data warehouse. This data was used to analyze sociodemographic characteristics, healthcare resource utilization, and medical expenditures between telemedicine and non-telemedicine cohorts. The dataset was not publicly available due to protected health information (PHI) regulations.\n", "\n", " - **Paper 3 (PMID: 39051414):**\n", " - **Title:** Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\n", " - **Data Source:** The study utilized the 2020 National Inpatient Sample (NIS) dataset, which is a de-identified, publicly available inpatient database representing hospitalizations in the U.S. The dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ).\n", "\n", "### Conclusion:\n", "The process involved searching for relevant literature, screening abstracts based on specific criteria, and extracting detailed data source information from the full-text articles. The included studies provided insights into the impact of COVID-19 on healthcare resource utilization, using robust data sources like institutional data warehouses and national inpatient samples.\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from langchain_core.messages import SystemMessage, HumanMessage\n", "from langchain.tools import StructuredTool\n", "from langchain.agents import initialize_agent, Tool, AgentType\n", "from langchain_openai import ChatOpenAI\n", "from langgraph.graph.message import add_messages\n", "from langgraph.graph import StateGraph, END\n", "from pydantic import BaseModel\n", "from typing import List, TypedDict, Annotated\n", "import xml.etree.ElementTree as ET\n", "import uuid\n", "import re\n", "from langgraph.prebuilt import ToolNode\n", "from Bio import Entrez\n", "from langchain_qdrant import QdrantVectorStore\n", "from qdrant_client import QdrantClient\n", "from qdrant_client.http.models import Distance, VectorParams\n", "from qdrant_client.http.models import Filter, FieldCondition, MatchValue\n", "from langchain_huggingface import HuggingFaceEmbeddings\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "from langchain.chains import (\n", " ConversationalRetrievalChain,\n", ")\n", "from langchain.docstore.document import Document\n", "from langchain.memory import ChatMessageHistory, ConversationBufferMemory\n", "\n", "# 1. Define PubMed Search Tool\n", "class PubMedSearchInput(BaseModel):\n", " query: str\n", " #max_results: int = 5\n", "\n", "# PubMed search tool using Entrez (now with structured inputs)\n", "def pubmed_search(query: str, max_results: int = 3):\n", " \"\"\"Search PubMed using Entrez API and return abstracts.\"\"\"\n", " handle = Entrez.esearch(db=\"pubmed\", term=query, retmax=max_results)\n", " record = Entrez.read(handle)\n", " handle.close()\n", " pmids = record[\"IdList\"]\n", " \n", " # Fetch abstracts\n", " handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n", " records = Entrez.read(handle)\n", " handle.close()\n", "\n", " abstracts = []\n", " for record in records['PubmedArticle']:\n", " try:\n", " title = record['MedlineCitation']['Article']['ArticleTitle']\n", " abstract = record['MedlineCitation']['Article']['Abstract']['AbstractText'][0]\n", " pmid = record['MedlineCitation']['PMID']\n", " abstracts.append({\"PMID\": pmid, \"Title\": title, \"Abstract\": abstract})\n", " except KeyError:\n", " pass\n", " return abstracts\n", "\n", "# Define the AbstractScreeningInput using Pydantic BaseModel\n", "class AbstractScreeningInput(BaseModel):\n", " abstracts: List[dict]\n", " criteria: str\n", "\n", "def screen_abstracts_semantic(abstracts: List[dict], criteria: str, similarity_threshold: float = 0.4):\n", " \"\"\"Screen abstracts based on semantic similarity to the criteria.\"\"\"\n", " \n", " # Compute the embedding of the criteria\n", " criteria_embedding = semantic_model.encode(criteria, convert_to_tensor=True)\n", " \n", " screened = []\n", " for paper in abstracts:\n", " abstract_text = paper['Abstract']\n", " \n", " # Compute the embedding of the abstract\n", " abstract_embedding = semantic_model.encode(abstract_text, convert_to_tensor=True)\n", " \n", " # Compute cosine similarity between the abstract and the criteria\n", " similarity_score = util.cos_sim(abstract_embedding, criteria_embedding).item()\n", " \n", " if similarity_score >= similarity_threshold:\n", " screened.append({\n", " \"PMID\": paper['PMID'], \n", " \"Decision\": \"Include\", \n", " \"Reason\": f\"Similarity score {similarity_score:.2f} >= threshold {similarity_threshold}\"\n", " })\n", " else:\n", " screened.append({\n", " \"PMID\": paper['PMID'], \n", " \"Decision\": \"Exclude\", \n", " \"Reason\": f\"Similarity score {similarity_score:.2f} < threshold {similarity_threshold}\"\n", " })\n", " \n", " return screened\n", "\n", "# Define the PubMed Search Tool as a StructuredTool with proper input schema\n", "pubmed_tool = StructuredTool(\n", " name=\"PubMed_Search_Tool\",\n", " func=pubmed_search,\n", " description=\"Search PubMed for research papers and retrieve abstracts. Pass the abstracts (returned results) to another tool.\",\n", " args_schema=PubMedSearchInput # Use Pydantic BaseModel for schema\n", ")\n", "\n", "# Define the Abstract Screening Tool with semantic screening\n", "semantic_screening_tool = StructuredTool(\n", " name=\"Semantic_Abstract_Screening_Tool\",\n", " func=screen_abstracts_semantic,\n", " description=\"\"\"Screen PubMed abstracts based on semantic similarity to inclusion/exclusion criteria. Uses cosine similarity between abstracts and criteria. Requires 'abstracts' and 'screening criteria' as input.\n", " The 'abstracts' is a list of dictionary with keys as PMID, Title, Abstract.\n", " Output a similarity scores for each abstract and send the list of pmids that passed the screening to Fetch_Extract_Tool.\"\"\",\n", " args_schema=AbstractScreeningInput # Pydantic schema remains the same\n", ")\n", "\n", "# 3. Define Full-Text Retrieval Tool\n", "class FetchExtractInput(BaseModel):\n", " pmids: List[str] # List of PubMed IDs to fetch full text for\n", " query: str\n", "\n", "def extract_text_from_pmc_xml(xml_content: str) -> str:\n", " \"\"\"a function to format and clean text from PMC full-text XML.\"\"\"\n", " try:\n", " root = ET.fromstring(xml_content)\n", " \n", " # Find all relevant text sections (e.g., , ,

)\n", " body_text = []\n", " for elem in root.iter():\n", " if elem.tag in ['p', 'sec', 'title', 'abstract', 'body']: # Add more tags as needed\n", " if elem.text:\n", " body_text.append(elem.text.strip())\n", " \n", " # Join all the text elements to form the complete full text\n", " full_text = \"\\n\\n\".join(body_text)\n", " \n", " return full_text\n", " except ET.ParseError:\n", " print(\"Error parsing XML content.\")\n", " return \"\"\n", "\n", "def fetch_and_extract(pmids: List[str], query: str):\n", " \"\"\"Fetch full text from PubMed Central for given PMIDs, split into chunks, \n", " store in a Qdrant vector database, and perform RAG for each paper.\n", " Retrieves exactly 3 chunks per paper (if available) and generates a consolidated answer for each paper.\n", " \"\"\"\n", " embedding_model = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n", " corpus = {}\n", " consolidated_results={}\n", "\n", " # Fetch records from PubMed Central (PMC)\n", " handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n", " records = Entrez.read(handle)\n", " handle.close()\n", "\n", " full_articles = []\n", " for record in records['PubmedArticle']:\n", " try:\n", " title = record['MedlineCitation']['Article']['ArticleTitle']\n", " pmid = record['MedlineCitation']['PMID']\n", " pmc_id = 'nan'\n", " pmc_id_temp = record['PubmedData']['ArticleIdList']\n", " \n", " # Extract PMC ID if available\n", " for ele in pmc_id_temp:\n", " if ele.attributes['IdType'] == 'pmc':\n", " pmc_id = ele.replace('PMC', '')\n", " break\n", "\n", " # Fetch full article from PMC\n", " if pmc_id != 'nan':\n", " handle = Entrez.efetch(db=\"pmc\", id=pmc_id, rettype=\"full\", retmode=\"xml\")\n", " full_article = handle.read()\n", " handle.close()\n", "\n", " # Split the full article into chunks\n", " cleaned_full_article = extract_text_from_pmc_xml(full_article)\n", " full_articles.append({\n", " \"PMID\": pmid,\n", " \"Title\": title,\n", " \"FullText\": cleaned_full_article # Add chunked text\n", " })\n", " else:\n", " full_articles.append({\"PMID\": pmid, \"Title\": title, \"FullText\": \"cannot fetch\"})\n", " except KeyError:\n", " pass\n", "\n", " # Create corpus for each chunk\n", " for article in full_articles:\n", " article_id = str(uuid.uuid4())\n", " corpus[article_id] = {\n", " \"page_content\": article[\"FullText\"],\n", " \"metadata\": {\n", " \"PMID\": article[\"PMID\"],\n", " \"Title\": article[\"Title\"]\n", " }\n", " }\n", "\n", " documents = [\n", " Document(page_content=content[\"page_content\"], metadata=content[\"metadata\"]) \n", " for content in corpus.values()\n", " ]\n", " CHUNK_SIZE = 1000\n", " CHUNK_OVERLAP = 200\n", "\n", " text_splitter = RecursiveCharacterTextSplitter(\n", " chunk_size=CHUNK_SIZE,\n", " chunk_overlap=CHUNK_OVERLAP,\n", " length_function=len,\n", " )\n", " \n", " split_chunks = text_splitter.split_documents(documents)\n", " \n", " id_set = set()\n", " for document in split_chunks:\n", " id = str(uuid.uuid4())\n", " while id in id_set:\n", " id = uuid.uuid4()\n", " id_set.add(id)\n", " document.metadata[\"uuid\"] = id\n", "\n", " LOCATION = \":memory:\"\n", " COLLECTION_NAME = \"pmd_data\"\n", " VECTOR_SIZE = 384\n", "\n", " # Initialize Qdrant client\n", " qdrant_client = QdrantClient(location=LOCATION)\n", "\n", " # Create a collection in Qdrant\n", " qdrant_client.create_collection(\n", " collection_name=COLLECTION_NAME,\n", " vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),\n", " )\n", "\n", " # Initialize the Qdrant vector store without the embedding argument\n", " vdb = QdrantVectorStore(\n", " client=qdrant_client,\n", " collection_name=COLLECTION_NAME,\n", " embedding=embedding_model,\n", " )\n", "\n", " # Add embedded documents to Qdrant\n", " vdb.add_documents(split_chunks)\n", "\n", " # Query for each paper and consolidate answers\n", " for pmid in pmids:\n", " # Correctly structure the filter using Qdrant Filter model\n", " qdrant_filter = Filter(\n", " must=[\n", " FieldCondition(key=\"metadata.PMID\", match=MatchValue(value=pmid))\n", " ]\n", " )\n", "\n", " # Custom filtering for the retriever to only fetch chunks related to the current PMID\n", " retriever_with_filter = vdb.as_retriever(\n", " search_kwargs={\n", " \"filter\": qdrant_filter, # Correctly passing the Qdrant filter\n", " \"k\": 3 # Retrieve 3 chunks per PMID\n", " }\n", " )\n", "\n", " # Reset message history and memory for each query to avoid interference\n", " message_history = ChatMessageHistory()\n", " memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key=\"answer\", chat_memory=message_history, return_messages=True)\n", "\n", " # Create the ConversationalRetrievalChain with the filtered retriever\n", " qa_chain = ConversationalRetrievalChain.from_llm(\n", " ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0),\n", " retriever=retriever_with_filter,\n", " memory=memory,\n", " return_source_documents=True\n", " )\n", "\n", " # Query the vector store for relevant documents and extract information\n", " result = qa_chain({\"question\": query})\n", "\n", " # Generate the final answer based on the retrieved chunks\n", " generated_answer = result[\"answer\"] # This contains the LLM's generated answer based on the retrieved chunks\n", " generated_source = result[\"source_documents\"]\n", "\n", " # Consolidate the results for each paper\n", " paper_info = {\n", " \"PMID\": pmid,\n", " \"Title\": result[\"source_documents\"][0].metadata[\"Title\"] if result[\"source_documents\"] else \"Unknown Title\",\n", " \"Generated Answer\": generated_answer, # Store the generated answer,\n", " \"Sources\": generated_source \n", " }\n", "\n", " consolidated_results[pmid] = paper_info\n", "\n", " # Return consolidated results for all papers\n", " return consolidated_results\n", "\n", "rag_tool = StructuredTool(\n", " name=\"Fetch_Extract_Tool\",\n", " func=fetch_and_extract,\n", " description=\"\"\"Fetch full-text articles based on PMIDs and store them in a Qdrant vector database.\n", " Then extract information based on user's query via Qdrant retriever using a RAG pipeline.\n", " Requires list of PMIDs and user query as input.\"\"\",\n", " args_schema=FetchExtractInput\n", ")\n", "\n", "\n", "tool_belt = [\n", " pubmed_tool,\n", " semantic_screening_tool,\n", " rag_tool\n", "]\n", "\n", "# Model setup with tools bound\n", "model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n", "model = model.bind_tools(tool_belt)\n", "\n", "# Agent state to handle the messages\n", "class AgentState(TypedDict):\n", " messages: Annotated[list, add_messages]\n", " cycle_count: int # Add a counter to track the number of cycles\n", "\n", "# Function to call the model and handle the flow automatically\n", "def call_model(state):\n", " messages = state[\"messages\"]\n", " response = model.invoke(messages)\n", " return {\"messages\": [response], \"cycle_count\": state[\"cycle_count\"] + 1} # Increment cycle count\n", "\n", "tool_node = ToolNode(tool_belt)\n", "\n", "# Create the state graph for managing the flow between the agent and tools\n", "uncompiled_graph = StateGraph(AgentState)\n", "uncompiled_graph.add_node(\"agent\", call_model)\n", "uncompiled_graph.add_node(\"action\", tool_node)\n", "\n", "# Set the entry point for the graph\n", "uncompiled_graph.set_entry_point(\"agent\")\n", "\n", "# Define a function to check if the process should continue\n", "def should_continue(state):\n", " # Check if the cycle count exceeds the limit (e.g., 10)\n", " if state[\"cycle_count\"] > 20:\n", " print(f\"Reached the cycle limit of {state['cycle_count']} cycles. Ending the process.\")\n", " return END\n", " \n", " # If there are tool calls, continue to the action node\n", " last_message = state[\"messages\"][-1]\n", " if last_message.tool_calls:\n", " return \"action\"\n", " \n", " return END\n", "\n", "# Add conditional edges for the agent to action\n", "uncompiled_graph.add_conditional_edges(\"agent\", should_continue)\n", "uncompiled_graph.add_edge(\"action\", \"agent\")\n", "\n", "# Compile the state graph\n", "compiled_graph = uncompiled_graph.compile()\n", "\n", "# SystemMessage that defines the execution flow\n", "system_instructions = SystemMessage(content=\"\"\"Please execute the following steps in sequence:\n", "1. Use the PubMed search tool to search for papers.\n", "2. Retrieve the abstracts from the search results.\n", "3. Screen the abstracts based on the criteria provided by the user.\n", "4. Fetch full-text articles for all the papers that pass step 3. Store the full-text articles in the Qdrant vector database, \n", " and extract the requested information for each article that passed step 3 from the full-text using the query provided by the user.\n", "5. Please provide a full summary at the end of the entire flow executed, detailing the whole process/reasoning for each paper. \n", "The user will provide the search query, screening criteria, and the query for information extraction.\n", "Make sure you finish everything in one step before moving on to next step.\n", "Do not call more than one tool in one action.\"\"\")\n", "\n", "# HumanMessage only includes the necessary inputs\n", "human_inputs = HumanMessage(content=\"\"\"{\n", " \"query\": \"(\\\"Impact\\\"[Title/Abstract]) AND ((\\\"COVID\\\"[Title/Abstract] OR \\\"pandemic\\\"[Title/Abstract]) AND (\\\"healthcare resource utilization\\\"[Title/Abstract] OR \\\"health resource utilization\\\"[Title/Abstract]))\",\n", " \"screening_criteria\": \"comparison of healthcare resource utilization before and after the COVID pandemic\",\n", " \"extraction_query\": \"data source information used in each paper (especially medical records)\"\n", "}\"\"\")\n", "\n", "# \"query\": \"(\"diabetes\"[Title]) AND ((\"quality of life\"[Title]))\",\n", "# \"screening_criteria\": \"how diabetes impact quality of life \",\n", "# \"extraction_query\": \"what kind data they used?\"\n", "\n", "# Combined input for the agent\n", "inputs = {\n", " \"messages\": [system_instructions, human_inputs],\n", " \"cycle_count\": 0, # Initialize cycle count to 0\n", "}\n", "\n", "# # Function to run the graph asynchronously\n", "async def run_graph():\n", " final_message_content = None # Variable to store the final message content\n", "\n", " async for chunk in compiled_graph.astream(inputs, stream_mode=\"updates\"):\n", " for node, values in chunk.items():\n", " print(f\"Receiving update from node: '{node}'\")\n", " pretty_print(values[\"messages\"]) # Print all messages as before\n", " \n", " # Check if the message contains content\n", " if \"messages\" in values and values[\"messages\"]:\n", " final_message = values[\"messages\"][-1] # Access the last message in this chunk\n", " if hasattr(final_message, 'content'): # Check if content exists\n", " final_message_content = final_message.content # Store the last message's content\n", " \n", " print(\"\\n\\n\")\n", "\n", " # After the loop finishes, print the final message content\n", " if final_message_content:\n", " print(\"Final message content from the last chunk:\")\n", " pretty_print(final_message_content)\n", " else:\n", " print(\"No final message content found.\")\n", "\n", "# Run the compiled graph\n", "await run_graph()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n", " warnings.warn(\n" ] }, { "data": { "text/plain": [ "{'39063396': {'PMID': '39063396',\n", " 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.',\n", " 'Generated Answer': \"I don't have that information based on the context provided.\",\n", " 'Sources': [Document(metadata={'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'uuid': 'fd8348fd-b855-45f7-992a-9b916629c09b', '_id': 'a8fbe8e1262f4ec694bff70b1dea2370', '_collection_name': 'pmd_data'}, page_content='Supplementary Materials\\n\\nThe following supporting information can be downloaded at:\\n\\nAuthor Contributions\\n\\nConceptualization: Y.Z. (Yunxi Zhang), L.S.L., J.M.S. and S.C.; Methodology: Y.Z. (Yunxi Zhang), L.S.L. and J.M.S.; Software: Y.Z. (Yunxi Zhang) and Y.Z. (Ying Zhang); Validation: Y.Z. (Yunxi Zhang), Y.Z. (Ying Zhang), and B.F.J.; Formal Analysis: Y.Z. (Yunxi Zhang); Investigation: Y.Z. (Yunxi Zhang), L.S.L., Y.-Y.L., J.M.S., B.F.J., S.C. and M.E.L.; Resources: Y.Z. (Yunxi Zhang), Y.Z. (Ying Zhang), R.L.S., B.F.J., S.C. and M.E.L.; Data Curation: Y.Z. (Ying Zhang); Visualization: Y.-Y.L.; Writing—Original Draft Preparation: Y.Z. (Yunxi Zhang); Writing—Review and Editing: Y.Z. (Yunxi Zhang), L.S.L., Y.-Y.L., J.M.S., Y.Z. (Ying Zhang), R.L.S., B.F.J., S.C. and M.E.L.; Supervision: J.M.S., S.C. and M.E.L.; Project Administration: Y.Z. (Yunxi Zhang) and S.C.; Funding Acquisition: R.L.S. and S.C. All authors have read and agreed to the published version of the manuscript.'),\n", " Document(metadata={'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'uuid': 'a3961e7c-cbb3-44ba-b857-0770544e2fd6', '_id': '35ebfd3607be42fe9779f5d73d12669f', '_collection_name': 'pmd_data'}, page_content='5. Conclusions'),\n", " Document(metadata={'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'uuid': '168c2b95-c340-4ca3-8291-10523de8add9', '_id': '0835f877eb11476a9ee77361ea66f593', '_collection_name': 'pmd_data'}, page_content='2.4. Statistical Analysis\\n\\nDescriptive statistics, including mean with standard deviation (SD) and frequency with percentage (%), were used to summarize continuous and categorical variables. The Shapiro–Wilk test was used to examine the normality of continuous variables for HCRU and medical expenditures. We examined the association between sociodemographic factors and the utilization of TMH services using Pearson’s\\n\\nThe Wilcoxon rank sum test was employed to compare the non-normally distributed variables of HCRU and medical expenditures. To adjust for the sociodemographic factors, generalized linear regression models (GLMs) with log links were constructed to assess the impact of TMH usage on HCRU and medical expenditures. Specifically, we fitted Poisson regression models, negative binomial regression models, or zero-inflated Poisson regression models for HCRU outcomes, depending on their distributions, and Gamma regression models for medical expenditures.')]},\n", " '39051414': {'PMID': '39051414',\n", " 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.',\n", " 'Generated Answer': 'The data source used in the paper provided is the 2020 National Inpatient Sample (NIS) dataset, which covers hospitalizations in the United States from January 1, 2020, to December 31, 2020. The NIS dataset is derived from the State Inpatient Databases (SIDs) and is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ). The dataset is de-identified and publicly available, representing an estimated 98% of the U.S. population.',\n", " 'Sources': [Document(metadata={'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'uuid': '36ab4b73-59f8-4539-94dd-c5d32b0b4380', '_id': 'e7a86941d7fc48c18fb7cb38e58896a4', '_collection_name': 'pmd_data'}, page_content='Supplementary Materials\\n\\nThe following supporting information can be downloaded at:\\n\\nAuthor Contributions\\n\\nConceptualization, Z.H.B. and M.H.; methodology, Z.H.B.; formal analysis, Z.H.B.; investigation and analysis, Z.H.B.; writing—original draft preparation, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; writing—review and editing, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; visualization, Y.B. and C.L.B.; supervision, Y.B. and C.L.B. All authors have read and agreed to the published version of the manuscript.\\n\\nInstitutional Review Board Statement\\n\\nEthical review and approval were waived for this study as it does not involve research with human subjects and the dataset used is de-identified.\\n\\nInformed Consent Statement\\n\\nIt is a retrospective study using publicly available de-identified data and consent is not required.\\n\\nData Availability Statement'),\n", " Document(metadata={'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'uuid': '38957a2b-0cec-4957-95d1-6f1a6eb56df9', '_id': '55e4fa42c60848918e1d2d60c01417ea', '_collection_name': 'pmd_data'}, page_content='3. Materials and Methods\\n\\n\\n\\n3.1. Study Design and Database Description\\n\\nUtilizing the 2020 National Inpatient Sample (NIS) dataset, we conducted a retrospective cohort analysis of adult patients admitted with a primary diagnosis of sickle cell crisis in the United States. The NIS 2020 dataset specifically covers hospitalizations within the period from 1 January 2020 to 31 December 2020. It derives from the State Inpatient Databases (SIDs) that cover an estimated 98% of the U.S. population. As part of the Healthcare Cost and Utilization Project sponsored by Agency for Healthcare Research and Quality (AHRQ), the NIS is the most extensive, de-identified, publicly available inpatient database in the U.S. This database employs a 20% stratified discharge sample, which is then weighted relative to the total discharges to ensure national representativeness.\\n\\n\\n\\n3.2. Study Patients'),\n", " Document(metadata={'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'uuid': '16393d9e-b309-4681-9a96-de3e12262940', '_id': '64c8170f62524d498ec71156452f5bd0', '_collection_name': 'pmd_data'}, page_content='3.4. Statistical Analyses\\n\\nAnalyses were performed using STATA, version MP 14.2 (StataCorp, College Station, TX, USA). The study used univariate and multivariate regression analyses to compute unadjusted and adjusted outcomes, respectively. The univariate analysis was conducted to identify potential confounding factors. All confounders that displayed a significant relationship with the outcome, using a\\n\\n\\n\\n4. Results\\n\\n\\n\\nPatient Characteristics')]}}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result = rag_tool.func(pmids=[\"39063396\",\"39051414\"],query = \"what are the data sources used in each paper?\") # Example PMIDs\n", "result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### also tested to retrieve 10 papers" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2024-10-03 14:29:34 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_SEES104ri8aPSNMcFPXGZI2B', 'function': {'arguments': '{\"query\":\"(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))\"}', 'name': 'PubMed_Search_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 59, 'prompt_tokens': 496, 'total_tokens': 555, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47551650-3541-4800-a25f-847ceb4d21ab-0', tool_calls=[{'name': 'PubMed_Search_Tool', 'args': {'query': '(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))'}, 'id': 'call_SEES104ri8aPSNMcFPXGZI2B', 'type': 'tool_call'}], usage_metadata={'input_tokens': 496, 'output_tokens': 59, 'total_tokens': 555})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'action'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[ToolMessage(content='[{\"PMID\": \"39291999\", \"Title\": \"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\", \"Abstract\": \"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"}, {\"PMID\": \"39063396\", \"Title\": \"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\", \"Abstract\": \"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all p < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both p < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"}, {\"PMID\": \"39051414\", \"Title\": \"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\", \"Abstract\": \"Background: This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. Methods: A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. Results: Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (p = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, p = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, p = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (p < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (p = 0.005). Conclusions: The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"}, {\"PMID\": \"38966443\", \"Title\": \"Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\", \"Abstract\": \"Background The identification of SARS-CoV-2 in December 2019 and its subsequent designation as the causative agent of COVID-19 marked the beginning of an unprecedented global health crisis. As the virus spread rapidly across continents, its impact on various demographic groups, including children, became a subject of intense research. While children were initially thought to be less susceptible to severe COVID-19 illness compared to adults, concerns emerged regarding their vulnerability to other respiratory infections amidst the pandemic. Understanding the epidemiological trends of pediatric respiratory tract infections (RTIs) during the COVID-19 era is crucial for informing public health strategies and clinical management protocols. This study aimed to compare the prevalence and characteristics of pediatric RTIs before and during the COVID-19 pandemic in Lebanon. Methodology A retrospective, observational study was conducted by reviewing medical records of children admitted to three tertiary care hospitals in Lebanon: Sheikh Ragheb Harb University Hospital, Al Sahel General University Hospital, and Rafik Al-Hariri University Hospital. Data were collected from October 2018 to March 2021, encompassing both the pre-COVID-19 and COVID-19 eras. A standardized data collection sheet was utilized to gather information on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage. Results Our analysis revealed significant shifts in the epidemiology of pediatric RTIs between the pre-COVID-19 and COVID-19 eras. There was a marked decline in the proportion of school-age children hospitalized with RTIs during the pandemic period. However, the overall percentage of Lebanese hospitalized children across different age groups increased significantly during the COVID-19 era. Furthermore, the prevalence of specific RTIs, such as pharyngitis, increased from 1.1% in the pre-COVID-19\\\\u00a0to 5.5% during the COVID-19 period (p = 0.016), and the prevalence of bronchiolitis increased from 26.7% to 50.9% (p < 0.001) during the pre-COVID-19 and COVID-19 periods, respectively. This notable rise during the pandemic suggested potential changes in circulating pathogens or diagnostic practices. Importantly, the median length of hospital stays for pediatric RTIs decreased during the COVID-19 era compared to the pre-pandemic period, indicating possible improvements in clinical management or healthcare resource utilization. Analysis of antibiotic usage revealed ceftriaxone as the most frequently prescribed antibiotic in both periods, highlighting its continued relevance in the management of pediatric RTIs. Conclusions This study highlights significant epidemiological shifts in pediatric RTIs during the COVID-19 era in Lebanon. These findings underscore the importance of ongoing surveillance and research to adapt public health interventions and clinical practices to evolving infectious disease dynamics. Further investigation is warranted to elucidate the underlying factors driving these changes and optimize strategies for the prevention and management of pediatric RTIs in the context of the ongoing pandemic.\"}, {\"PMID\": \"38885115\", \"Title\": \"Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\", \"Abstract\": \"Patients with inborn errors of immunity (IEI) are predisposed to severe recurrent/chronic infections, and often require hospitalization, resulting in substantial burden to patients/healthcare systems. While immunoglobulin replacement therapies (IgRTs) are the standard first-line treatment for most forms of IEI, limited real-world data exist regarding clinical characteristics and treatment costs for patients with IEI initiating such treatment. This retrospective analysis examined infection and treatment characteristics in US patients with IEI initiating IgRT with immune globulin infusion (human), 10% (IG10%). Healthcare resource utilization (HCRU) and associated costs before and after treatment initiation were compared. Additionally, the impact of COVID-19 on infection diagnoses was evaluated.\"}, {\"PMID\": \"38779335\", \"Title\": \"Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\", \"Abstract\": \"Background: The economic burden associated with type 2 diabetes mellitus (T2DM) and concurrent cardiovascular disease (CVD) among patients with COVID-19 is unclear. Objective: We compared healthcare resource utilization (HCRU) and costs in patients with COVID-19 and T2DM and CVD (T2DM\\\\u2009+\\\\u2009CVD), T2DM only, or neither T2DM nor CVD (T2DM/CVD). Methods: A retrospective observational study in COVID-19 patients using data from the Healthcare Integrated Research Database (HIRD\\\\u00ae) was conducted. Patients with COVID-19 were identified between March 1, 2020, and May 31, 2021, and followed from first diagnosis or positive lab test to the end of health plan enrollment, end of study period, or death. Patients were assigned one of 3 cohorts: pre-existing T2DM+CVD, T2DM only, or neither T2DM/CVD. Propensity score matching and multivariable analyses were performed to control for differences in baseline characteristics. Study outcomes included all-cause and COVID-19-related HCRU and costs. Results: In all, 321\\\\u202f232 COVID-19 patients were identified (21\\\\u202f651 with T2DM\\\\u2009+\\\\u2009CVD, 28\\\\u202f184 with T2DM only, and 271\\\\u202f397 with neither T2DM/CVD). After matching, 6967 patients were in each group. Before matching, 46.0% of patients in the T2DM\\\\u2009+\\\\u2009CVD cohort were hospitalized for any cause, compared with 18.0% in the T2DM-only cohort and 6.3% in the neither T2DM/CVD cohort; the corresponding values after matching were 34.2%, 26.0%, and 21.2%. The proportion of patients with emergency department visits, telehealth visits, or use of skilled nursing facilities was higher in patients with COVID-19 and T2DM\\\\u2009+\\\\u2009CVD compared with the other cohorts. Average all-cause costs during follow-up were 12\\\\u202f324,7882, and $7277 per-patient-per-month after matching for patients with T2DM\\\\u2009+\\\\u2009CVD, T2DM-only, and neither T2DM/CVD, respectively. COVID-19-related costs contributed to 78%, 75%, and 64% of the overall costs, respectively. The multivariable model showed that per-patient-per-month all-cause costs for T2DM\\\\u2009+\\\\u2009CVD and T2DM-only were 54% and 21% higher, respectively, than those with neither T2DM/CVD after adjusting for residual confounding. Conclusion: HCRU and costs in patients were incrementally higher with COVID-19 and pre-existing T2DM\\\\u2009+\\\\u2009CVD compared with those with T2DM-only and neither T2DM/CVD, even after accounting for baseline differences between groups, confirming that pre-existing T2DM\\\\u2009+\\\\u2009CVD is associated with increased HCRU and costs in COVID-19 patients, highlighting the importance of proactive management.\"}, {\"PMID\": \"38686393\", \"Title\": \"Real-world total cost of care by line of therapy in relapsed/refractory diffuse large B-cell lymphoma.\", \"Abstract\": \"There are multiple recently approved treatments and a lack of clear standard-of-care therapies for relapsed/refractory (R/R) diffuse large B-cell lymphoma (DLBCL). While total cost of care (TCC) by the number of lines of therapy (LoTs) has been evaluated, more recent cost estimates using real-world data are needed. This analysis assessed real-world TCC of R/R DLBCL therapies by LoT using the IQVIA PharMetrics Plus database (1 January 2015-31 December 2021), in US patients aged \\\\u226518\\\\u2009years treated with rituximab plus cyclophosphamide, doxorubicin, vincristine, and prednisone (R-CHOP) or an R-CHOP-like regimen as first-line therapy.\"}, {\"PMID\": \"38644506\", \"Title\": \"Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\", \"Abstract\": \"Most studies on the impact of the COVID-19 pandemic on depression burden focused on the earlier pandemic phase specific to lockdowns, but the longer-term impact of the pandemic is less well-studied. In this population-based cohort study, we examined the short-term and long-term impacts of COVID-19 on depression incidence and healthcare service use among patients with depression.\"}, {\"PMID\": \"38534198\", \"Title\": \"Burden of disease and treatment patterns in patients with vitiligo: findings from a national longitudinal retrospective study in the UK.\", \"Abstract\": \"UK studies examining vitiligo burden and vitiligo-related healthcare resource utilization (HCRU) are lacking.\"}, {\"PMID\": \"38435542\", \"Title\": \"Impact Of body Mass Index on Cardiopulmonary Outcomes of COVID-19 Hospitalizations Complicated by Severe Sepsis.\", \"Abstract\": \"Body Mass Index (BMI) has a significant impact on Coronavirus disease (COVID-19) patient outcomes; however, major adverse cardiac and cerebrovascular outcomes in patients with severe sepsis have been poorly understood. Our study aims to explore and provide insight into its association.\"}]', name='PubMed_Search_Tool', tool_call_id='call_SEES104ri8aPSNMcFPXGZI2B')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "2024-10-03 14:29:40 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_COqnk3EZgSEcOw5kP0XQFX3E', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\"}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 30, 'prompt_tokens': 3595, 'total_tokens': 3625, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-e00108fb-5250-4ed3-952f-10130f5ddd12-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic'}, 'id': 'call_COqnk3EZgSEcOw5kP0XQFX3E', 'type': 'tool_call'}], usage_metadata={'input_tokens': 3595, 'output_tokens': 30, 'total_tokens': 3625})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Receiving update from node: 'action'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[ToolMessage(content=\"Error: 1 validation error for AbstractScreeningInput\\nabstracts\\n Field required [type=missing, input_value={'criteria': 'comparison ...ter the COVID pandemic'}, input_type=dict]\\n For further information visit https://errors.pydantic.dev/2.9/v/missing\\n Please fix your mistakes.\", name='Semantic_Abstract_Screening_Tool', tool_call_id='call_COqnk3EZgSEcOw5kP0XQFX3E')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "2024-10-03 14:30:09 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_JQqUPfw2NKpTgmP4Eaj8xDRt', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\",\"abstracts\":[{\"PMID\":\"39291999\",\"Title\":\"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\",\"Abstract\":\"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"},{\"PMID\":\"39063396\",\"Title\":\"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\",\"Abstract\":\"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all p < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both p < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"},{\"PMID\":\"39051414\",\"Title\":\"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\",\"Abstract\":\"Background: This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. Methods: A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. Results: Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (p = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, p = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, p = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (p < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (p = 0.005). Conclusions: The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"},{\"PMID\":\"38966443\",\"Title\":\"Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\",\"Abstract\":\"Background The identification of SARS-CoV-2 in December 2019 and its subsequent designation as the causative agent of COVID-19 marked the beginning of an unprecedented global health crisis. As the virus spread rapidly across continents, its impact on various demographic groups, including children, became a subject of intense research. While children were initially thought to be less susceptible to severe COVID-19 illness compared to adults, concerns emerged regarding their vulnerability to other respiratory infections amidst the pandemic. Understanding the epidemiological trends of pediatric respiratory tract infections (RTIs) during the COVID-19 era is crucial for informing public health strategies and clinical management protocols. This study aimed to compare the prevalence and characteristics of pediatric RTIs before and during the COVID-19 pandemic in Lebanon. Methodology A retrospective, observational study was conducted by reviewing medical records of children admitted to three tertiary care hospitals in Lebanon: Sheikh Ragheb Harb University Hospital, Al Sahel General University Hospital, and Rafik Al-Hariri University Hospital. Data were collected from October 2018 to March 2021, encompassing both the pre-COVID-19 and COVID-19 eras. A standardized data collection sheet was utilized to gather information on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage. Results Our analysis revealed significant shifts in the epidemiology of pediatric RTIs between the pre-COVID-19 and COVID-19 eras. There was a marked decline in the proportion of school-age children hospitalized with RTIs during the pandemic period. However, the overall percentage of Lebanese hospitalized children across different age groups increased significantly during the COVID-19 era. Furthermore, the prevalence of specific RTIs, such as pharyngitis, increased from 1.1% in the pre-COVID-19 to 5.5% during the COVID-19 period (p = 0.016), and the prevalence of bronchiolitis increased from 26.7% to 50.9% (p < 0.001) during the pre-COVID-19 and COVID-19 periods, respectively. This notable rise during the pandemic suggested potential changes in circulating pathogens or diagnostic practices. Importantly, the median length of hospital stays for pediatric RTIs decreased during the COVID-19 era compared to the pre-pandemic period, indicating possible improvements in clinical management or healthcare resource utilization. Analysis of antibiotic usage revealed ceftriaxone as the most frequently prescribed antibiotic in both periods, highlighting its continued relevance in the management of pediatric RTIs. Conclusions This study highlights significant epidemiological shifts in pediatric RTIs during the COVID-19 era in Lebanon. These findings underscore the importance of ongoing surveillance and research to adapt public health interventions and clinical practices to evolving infectious disease dynamics. Further investigation is warranted to elucidate the underlying factors driving these changes and optimize strategies for the prevention and management of pediatric RTIs in the context of the ongoing pandemic.\"},{\"PMID\":\"38885115\",\"Title\":\"Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\",\"Abstract\":\"Patients with inborn errors of immunity (IEI) are predisposed to severe recurrent/chronic infections, and often require hospitalization, resulting in substantial burden to patients/healthcare systems. While immunoglobulin replacement therapies (IgRTs) are the standard first-line treatment for most forms of IEI, limited real-world data exist regarding clinical characteristics and treatment costs for patients with IEI initiating such treatment. This retrospective analysis examined infection and treatment characteristics in US patients with IEI initiating IgRT with immune globulin infusion (human), 10% (IG10%). Healthcare resource utilization (HCRU) and associated costs before and after treatment initiation were compared. Additionally, the impact of COVID-19 on infection diagnoses was evaluated.\"},{\"PMID\":\"38779335\",\"Title\":\"Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\",\"Abstract\":\"Background: The economic burden associated with type 2 diabetes mellitus (T2DM) and concurrent cardiovascular disease (CVD) among patients with COVID-19 is unclear. Objective: We compared healthcare resource utilization (HCRU) and costs in patients with COVID-19 and T2DM and CVD (T2DM+CVD), T2DM only, or neither T2DM nor CVD (T2DM/CVD). Methods: A retrospective observational study in COVID-19 patients using data from the Healthcare Integrated Research Database (HIRD®) was conducted. Patients with COVID-19 were identified between March 1, 2020, and May 31, 2021, and followed from first diagnosis or positive lab test to the end of health plan enrollment, end of study period, or death. Patients were assigned one of 3 cohorts: pre-existing T2DM+CVD, T2DM only, or neither T2DM/CVD. Propensity score matching and multivariable analyses were performed to control for differences in baseline characteristics. Study outcomes included all-cause and COVID-19-related HCRU and costs. Results: In all, 321\\u202f232 COVID-19 patients were identified (21\\u202f651 with T2DM+CVD, 28\\u202f184 with T2DM only, and 271\\u202f397 with neither T2DM/CVD). After matching, 6967 patients were in each group. Before matching, 46.0% of patients in the T2DM+CVD cohort were hospitalized for any cause, compared with 18.0% in the T2DM-only cohort and 6.3% in the neither T2DM/CVD cohort; the corresponding values after matching were 34.2%, 26.0%, and 21.2%. The proportion of patients with emergency department visits, telehealth visits, or use of skilled nursing facilities was higher in patients with COVID-19 and T2DM+CVD compared with the other cohorts. Average all-cause costs during follow-up were 12\\u202f324,7882, and $7277 per-patient-per-month after matching for patients with T2DM+CVD, T2DM-only, and neither T2DM/CVD, respectively. COVID-19-related costs contributed to 78%, 75%, and 64% of the overall costs, respectively. The multivariable model showed that per-patient-per-month all-cause costs for T2DM+CVD and T2DM-only were 54% and 21% higher, respectively, than those with neither T2DM/CVD after adjusting for residual confounding. Conclusion: HCRU and costs in patients were incrementally higher with COVID-19 and pre-existing T2DM+CVD compared with those with T2DM-only and neither T2DM/CVD, even after accounting for baseline differences between groups, confirming that pre-existing T2DM+CVD is associated with increased HCRU and costs in COVID-19 patients, highlighting the importance of proactive management.\"},{\"PMID\":\"38686393\",\"Title\":\"Real-world total cost of care by line of therapy in relapsed/refractory diffuse large B-cell lymphoma.\",\"Abstract\":\"There are multiple recently approved treatments and a lack of clear standard-of-care therapies for relapsed/refractory (R/R) diffuse large B-cell lymphoma (DLBCL). While total cost of care (TCC) by the number of lines of therapy (LoTs) has been evaluated, more recent cost estimates using real-world data are needed. This analysis assessed real-world TCC of R/R DLBCL therapies by LoT using the IQVIA PharMetrics Plus database (1 January 2015-31 December 2021), in US patients aged ≥18\\u202fyears treated with rituximab plus cyclophosphamide, doxorubicin, vincristine, and prednisone (R-CHOP) or an R-CHOP-like regimen as first-line therapy.\"},{\"PMID\":\"38644506\",\"Title\":\"Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\",\"Abstract\":\"Most studies on the impact of the COVID-19 pandemic on depression burden focused on the earlier pandemic phase specific to lockdowns, but the longer-term impact of the pandemic is less well-studied. In this population-based cohort study, we examined the short-term and long-term impacts of COVID-19 on depression incidence and healthcare service use among patients with depression.\"},{\"PMID\":\"38534198\",\"Title\":\"Burden of disease and treatment patterns in patients with vitiligo: findings from a national longitudinal retrospective study in the UK.\",\"Abstract\":\"UK studies examining vitiligo burden and vitiligo-related healthcare resource utilization (HCRU) are lacking.\"},{\"PMID\":\"38435542\",\"Title\":\"Impact Of body Mass Index on Cardiopulmonary Outcomes of COVID-19 Hospitalizations Complicated by Severe Sepsis.\",\"Abstract\":\"Body Mass Index (BMI) has a significant impact on Coronavirus disease (COVID-19) patient outcomes; however, major adverse cardiac and cerebrovascular outcomes in patients with severe sepsis have been poorly understood. Our study aims to explore and provide insight into its association.\"}]}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 2929, 'prompt_tokens': 3703, 'total_tokens': 6632, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-729796e3-6e83-432e-a748-7eb29289b3d2-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic', 'abstracts': [{'PMID': '39291999', 'Title': 'Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.', 'Abstract': 'Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.'}, {'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'Abstract': 'During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all p < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both p < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.'}, {'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'Abstract': 'Background: This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. Methods: A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. Results: Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (p = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, p = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, p = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (p < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (p = 0.005). Conclusions: The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.'}, {'PMID': '38966443', 'Title': 'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.', 'Abstract': 'Background The identification of SARS-CoV-2 in December 2019 and its subsequent designation as the causative agent of COVID-19 marked the beginning of an unprecedented global health crisis. As the virus spread rapidly across continents, its impact on various demographic groups, including children, became a subject of intense research. While children were initially thought to be less susceptible to severe COVID-19 illness compared to adults, concerns emerged regarding their vulnerability to other respiratory infections amidst the pandemic. Understanding the epidemiological trends of pediatric respiratory tract infections (RTIs) during the COVID-19 era is crucial for informing public health strategies and clinical management protocols. This study aimed to compare the prevalence and characteristics of pediatric RTIs before and during the COVID-19 pandemic in Lebanon. Methodology A retrospective, observational study was conducted by reviewing medical records of children admitted to three tertiary care hospitals in Lebanon: Sheikh Ragheb Harb University Hospital, Al Sahel General University Hospital, and Rafik Al-Hariri University Hospital. Data were collected from October 2018 to March 2021, encompassing both the pre-COVID-19 and COVID-19 eras. A standardized data collection sheet was utilized to gather information on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage. Results Our analysis revealed significant shifts in the epidemiology of pediatric RTIs between the pre-COVID-19 and COVID-19 eras. There was a marked decline in the proportion of school-age children hospitalized with RTIs during the pandemic period. However, the overall percentage of Lebanese hospitalized children across different age groups increased significantly during the COVID-19 era. Furthermore, the prevalence of specific RTIs, such as pharyngitis, increased from 1.1% in the pre-COVID-19 to 5.5% during the COVID-19 period (p = 0.016), and the prevalence of bronchiolitis increased from 26.7% to 50.9% (p < 0.001) during the pre-COVID-19 and COVID-19 periods, respectively. This notable rise during the pandemic suggested potential changes in circulating pathogens or diagnostic practices. Importantly, the median length of hospital stays for pediatric RTIs decreased during the COVID-19 era compared to the pre-pandemic period, indicating possible improvements in clinical management or healthcare resource utilization. Analysis of antibiotic usage revealed ceftriaxone as the most frequently prescribed antibiotic in both periods, highlighting its continued relevance in the management of pediatric RTIs. Conclusions This study highlights significant epidemiological shifts in pediatric RTIs during the COVID-19 era in Lebanon. These findings underscore the importance of ongoing surveillance and research to adapt public health interventions and clinical practices to evolving infectious disease dynamics. Further investigation is warranted to elucidate the underlying factors driving these changes and optimize strategies for the prevention and management of pediatric RTIs in the context of the ongoing pandemic.'}, {'PMID': '38885115', 'Title': 'Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.', 'Abstract': 'Patients with inborn errors of immunity (IEI) are predisposed to severe recurrent/chronic infections, and often require hospitalization, resulting in substantial burden to patients/healthcare systems. While immunoglobulin replacement therapies (IgRTs) are the standard first-line treatment for most forms of IEI, limited real-world data exist regarding clinical characteristics and treatment costs for patients with IEI initiating such treatment. This retrospective analysis examined infection and treatment characteristics in US patients with IEI initiating IgRT with immune globulin infusion (human), 10% (IG10%). Healthcare resource utilization (HCRU) and associated costs before and after treatment initiation were compared. Additionally, the impact of COVID-19 on infection diagnoses was evaluated.'}, {'PMID': '38779335', 'Title': 'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.', 'Abstract': 'Background: The economic burden associated with type 2 diabetes mellitus (T2DM) and concurrent cardiovascular disease (CVD) among patients with COVID-19 is unclear. Objective: We compared healthcare resource utilization (HCRU) and costs in patients with COVID-19 and T2DM and CVD (T2DM+CVD), T2DM only, or neither T2DM nor CVD (T2DM/CVD). Methods: A retrospective observational study in COVID-19 patients using data from the Healthcare Integrated Research Database (HIRD®) was conducted. Patients with COVID-19 were identified between March 1, 2020, and May 31, 2021, and followed from first diagnosis or positive lab test to the end of health plan enrollment, end of study period, or death. Patients were assigned one of 3 cohorts: pre-existing T2DM+CVD, T2DM only, or neither T2DM/CVD. Propensity score matching and multivariable analyses were performed to control for differences in baseline characteristics. Study outcomes included all-cause and COVID-19-related HCRU and costs. Results: In all, 321\\u202f232 COVID-19 patients were identified (21\\u202f651 with T2DM+CVD, 28\\u202f184 with T2DM only, and 271\\u202f397 with neither T2DM/CVD). After matching, 6967 patients were in each group. Before matching, 46.0% of patients in the T2DM+CVD cohort were hospitalized for any cause, compared with 18.0% in the T2DM-only cohort and 6.3% in the neither T2DM/CVD cohort; the corresponding values after matching were 34.2%, 26.0%, and 21.2%. The proportion of patients with emergency department visits, telehealth visits, or use of skilled nursing facilities was higher in patients with COVID-19 and T2DM+CVD compared with the other cohorts. Average all-cause costs during follow-up were 12\\u202f324,7882, and $7277 per-patient-per-month after matching for patients with T2DM+CVD, T2DM-only, and neither T2DM/CVD, respectively. COVID-19-related costs contributed to 78%, 75%, and 64% of the overall costs, respectively. The multivariable model showed that per-patient-per-month all-cause costs for T2DM+CVD and T2DM-only were 54% and 21% higher, respectively, than those with neither T2DM/CVD after adjusting for residual confounding. Conclusion: HCRU and costs in patients were incrementally higher with COVID-19 and pre-existing T2DM+CVD compared with those with T2DM-only and neither T2DM/CVD, even after accounting for baseline differences between groups, confirming that pre-existing T2DM+CVD is associated with increased HCRU and costs in COVID-19 patients, highlighting the importance of proactive management.'}, {'PMID': '38686393', 'Title': 'Real-world total cost of care by line of therapy in relapsed/refractory diffuse large B-cell lymphoma.', 'Abstract': 'There are multiple recently approved treatments and a lack of clear standard-of-care therapies for relapsed/refractory (R/R) diffuse large B-cell lymphoma (DLBCL). While total cost of care (TCC) by the number of lines of therapy (LoTs) has been evaluated, more recent cost estimates using real-world data are needed. This analysis assessed real-world TCC of R/R DLBCL therapies by LoT using the IQVIA PharMetrics Plus database (1 January 2015-31 December 2021), in US patients aged ≥18\\u202fyears treated with rituximab plus cyclophosphamide, doxorubicin, vincristine, and prednisone (R-CHOP) or an R-CHOP-like regimen as first-line therapy.'}, {'PMID': '38644506', 'Title': 'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.', 'Abstract': 'Most studies on the impact of the COVID-19 pandemic on depression burden focused on the earlier pandemic phase specific to lockdowns, but the longer-term impact of the pandemic is less well-studied. In this population-based cohort study, we examined the short-term and long-term impacts of COVID-19 on depression incidence and healthcare service use among patients with depression.'}, {'PMID': '38534198', 'Title': 'Burden of disease and treatment patterns in patients with vitiligo: findings from a national longitudinal retrospective study in the UK.', 'Abstract': 'UK studies examining vitiligo burden and vitiligo-related healthcare resource utilization (HCRU) are lacking.'}, {'PMID': '38435542', 'Title': 'Impact Of body Mass Index on Cardiopulmonary Outcomes of COVID-19 Hospitalizations Complicated by Severe Sepsis.', 'Abstract': 'Body Mass Index (BMI) has a significant impact on Coronavirus disease (COVID-19) patient outcomes; however, major adverse cardiac and cerebrovascular outcomes in patients with severe sepsis have been poorly understood. Our study aims to explore and provide insight into its association.'}]}, 'id': 'call_JQqUPfw2NKpTgmP4Eaj8xDRt', 'type': 'tool_call'}], usage_metadata={'input_tokens': 3703, 'output_tokens': 2929, 'total_tokens': 6632})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "20f005db12534a04b951801c098e1c8b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Batches: 0%| | 0/1 [00:00= threshold 0.4\"}, {\"PMID\": \"39051414\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.45 >= threshold 0.4\"}, {\"PMID\": \"38966443\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.50 >= threshold 0.4\"}, {\"PMID\": \"38885115\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.46 >= threshold 0.4\"}, {\"PMID\": \"38779335\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.60 >= threshold 0.4\"}, {\"PMID\": \"38686393\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.24 < threshold 0.4\"}, {\"PMID\": \"38644506\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.57 >= threshold 0.4\"}, {\"PMID\": \"38534198\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.25 < threshold 0.4\"}, {\"PMID\": \"38435542\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.38 < threshold 0.4\"}]', name='Semantic_Abstract_Screening_Tool', tool_call_id='call_JQqUPfw2NKpTgmP4Eaj8xDRt')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "2024-10-03 14:30:12 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_fR7rclKNBZduynKOpO5AkIBH', 'function': {'arguments': '{\"pmids\":[\"39063396\",\"39051414\",\"38966443\",\"38885115\",\"38779335\",\"38644506\"],\"query\":\"data source information used in each paper (especially medical records)\"}', 'name': 'Fetch_Extract_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 56, 'prompt_tokens': 6967, 'total_tokens': 7023, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-3936e9ef-bc6d-4f1c-acdb-5915b670941a-0', tool_calls=[{'name': 'Fetch_Extract_Tool', 'args': {'pmids': ['39063396', '39051414', '38966443', '38885115', '38779335', '38644506'], 'query': 'data source information used in each paper (especially medical records)'}, 'id': 'call_fR7rclKNBZduynKOpO5AkIBH', 'type': 'tool_call'}], usage_metadata={'input_tokens': 6967, 'output_tokens': 56, 'total_tokens': 7023})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "2024-10-03 14:30:12 - Use pytorch device_name: cpu\n", "2024-10-03 14:30:12 - Load pretrained SentenceTransformer: sentence-transformers/all-MiniLM-L6-v2\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2024-10-03 14:30:23 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "2024-10-03 14:30:27 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "2024-10-03 14:30:29 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "2024-10-03 14:30:30 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "2024-10-03 14:30:33 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "2024-10-03 14:30:37 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "Receiving update from node: 'action'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[ToolMessage(content='{\\'39063396\\': {\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'Generated Answer\\': \"The data for the study was extracted from the UMMC enterprise data warehouse. The medical records used in the research were obtained from this source to examine sociodemographic characteristics, healthcare resource utilization (HCRU), and medical expenditures between telemedicine (TMH) and non-TMH cohorts. The sociodemographic characteristics considered in the study included age, sex, race, primary insurance, rurality, and household income. It\\'s important to note that due to the presence of protected health information (PHI) and in accordance with Institutional Review Board (IRB) regulations, the dataset cannot be made publicly available.\", \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'7174e027-b200-4d9d-9072-45a54d94fd2b\\', \\'_id\\': \\'7d6837bca7324f288effac83838b9ea0\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Institutional Review Board Statement\\\\n\\\\nThis study was approved by the Institutional Review Board (IRB) of the University of Mississippi Medical Center (ID: UMMC-IRB-2022-458; date of approval: 12 April 2023).\\\\n\\\\nInformed Consent Statement\\\\n\\\\nPatient consent was waived following Federal Regulations set forth by 45 CFR 46.116(f).\\\\n\\\\nData Availability Statement\\\\n\\\\nDue to the presence of protected health information (PHI) and in accordance with IRB regulations, the dataset cannot be made publicly available.\\\\n\\\\nConflicts of Interest\\\\n\\\\nLSL was an employee of ConcertAI during the conduct of this study. Other authors have no conflicts of interest to declare.\\\\n\\\\nReferences\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM.\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM of subjects residing in rural areas.\\\\n\\\\nSociodemographic characteristics of all study subjects and using TMH.\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'8a196627-3ff3-4936-bca0-230f89d8aacb\\', \\'_id\\': \\'cd1936164b7743eebf6afef0fe19ce39\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Medical records were extracted from the UMMC enterprise data warehouse to examine sociodemographic characteristics, HCRU, and medical expenditures between TMH and non-TMH cohorts. Sociodemographic characteristics considered in this study include age, sex, race, primary insurance, rurality, and household income. Age was categorized into four groups: 18 to 34 years, 35 to 49 years, 50 to 64 years, and 65 years or older. Race was categorized into three groups: White/Caucasian, Black/African American, and other. The other race group included subjects identifying as American Indian, Alaska Native, Native Hawaiian, other Pacific Islander, Mississippi Band Choctaw Indian, Asian, Hispanic, Multiracial, and others. Subjects of unknown race or those who refused to provide this information were considered missing. Primary insurance was defined as the insurance most frequently used for mental and behavioral health visits during the study period and was categorized into four groups: commercial\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'69265147-6605-4899-813a-cefb9538b690\\', \\'_id\\': \\'27d8a5a5377b410f9a243598172a248a\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'were included, future studies should consider multiple academic centers or healthcare entities to validate the robustness of findings across different geographic regions and patient populations. Additionally, there is potential for missing data since patients may seek care at multiple institutions. This limitation was mitigated by limiting the study sample to patients who had evidence of regular care visits at UMMC and had evidence of insurance coverage for at least one visit. However, as the study sample consisted of insured patients who regularly seek healthcare from UMMC, it may not represent the entire population of Mississippi, such as those without any healthcare access, thereby limiting generalizability to uninsured populations. Future research should identify and address barriers faced by uninsured populations to provide a more comprehensive understanding of TMH utilization and its impact on HCRU and medical expenditures.\\')]}, \\'39051414\\': {\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'Generated Answer\\': \\'The data source used in the study described is the 2020 National Inpatient Sample (NIS) dataset. This dataset covers hospitalizations in the United States from 1 January 2020 to 31 December 2020 and is derived from the State Inpatient Databases (SIDs). The NIS dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ). It is a de-identified, publicly available inpatient database that represents an estimated 98% of the U.S. population. The dataset employs a 20% stratified discharge sample that is weighted to ensure national representativeness. \\\\n\\\\nThe study did not involve direct access to individual medical records. Instead, it utilized aggregated and de-identified data from the NIS dataset, which does not require informed consent as it is publicly available and does not involve research with identifiable human subjects.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'82940dc9-90af-4a8b-afb4-fec2795f43e1\\', \\'_id\\': \\'24d2b583f5e44d579a7ee6569d917be5\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'3. Materials and Methods\\\\n\\\\n\\\\n\\\\n3.1. Study Design and Database Description\\\\n\\\\nUtilizing the 2020 National Inpatient Sample (NIS) dataset, we conducted a retrospective cohort analysis of adult patients admitted with a primary diagnosis of sickle cell crisis in the United States. The NIS 2020 dataset specifically covers hospitalizations within the period from 1 January 2020 to 31 December 2020. It derives from the State Inpatient Databases (SIDs) that cover an estimated 98% of the U.S. population. As part of the Healthcare Cost and Utilization Project sponsored by Agency for Healthcare Research and Quality (AHRQ), the NIS is the most extensive, de-identified, publicly available inpatient database in the U.S. This database employs a 20% stratified discharge sample, which is then weighted relative to the total discharges to ensure national representativeness.\\\\n\\\\n\\\\n\\\\n3.2. Study Patients\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'781f8646-7ab5-4ae3-8655-7d2755588e9f\\', \\'_id\\': \\'7d103fa49a5d426fa959c6caf7568078\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Our study has some limitations. Because it was retrospective, we could not fully randomize exposure. However, by employing multivariate regression models that took into account various patient and hospital traits, as well as co-morbidities, we made an effort to reduce confounding. Still, even with these measures, there is a slight chance that residual confounding occurred. To identify patients with sickle cell crisis and COVID-19, we opted for ICD-10 codes rather than clinical measures. This might have resulted in diagnosis misclassification. Yet, the legitimacy of using ICD-10 codes for this purpose is backed by earlier studies that utilized HCUP data [\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'9807f9d5-936c-4dc5-b997-c1f185eede4a\\', \\'_id\\': \\'2f953983923c4fffbcf1f3f2c1bfbd83\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Supplementary Materials\\\\n\\\\nThe following supporting information can be downloaded at:\\\\n\\\\nAuthor Contributions\\\\n\\\\nConceptualization, Z.H.B. and M.H.; methodology, Z.H.B.; formal analysis, Z.H.B.; investigation and analysis, Z.H.B.; writing—original draft preparation, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; writing—review and editing, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; visualization, Y.B. and C.L.B.; supervision, Y.B. and C.L.B. All authors have read and agreed to the published version of the manuscript.\\\\n\\\\nInstitutional Review Board Statement\\\\n\\\\nEthical review and approval were waived for this study as it does not involve research with human subjects and the dataset used is de-identified.\\\\n\\\\nInformed Consent Statement\\\\n\\\\nIt is a retrospective study using publicly available de-identified data and consent is not required.\\\\n\\\\nData Availability Statement\\')]}, \\'38966443\\': {\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'Generated Answer\\': \\'The study mentioned in the provided context utilized medical records as the primary data source. The data collection process involved reviewing the medical records of children admitted to three major hospitals in Lebanon. The information extracted from these records was gathered according to a standardized questionnaire to collect data on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage among hospitalized children with respiratory tract infections.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'uuid\\': \\'fd8709b4-a96a-4736-9996-7877086006a5\\', \\'_id\\': \\'5f75387f879646e49fd39d9f69da92bb\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Despite providing valuable insights, our study has several limitations. Data collection constraints, including missing variables such as bacterial cultures and viral panels, may have impacted the accuracy of our analyses. Additionally, the absence of information on co-infections limits our understanding of the full spectrum of respiratory pathogens circulating during the study periods.\\\\n\\\\n\\\\n\\\\nConclusions\\'), Document(metadata={\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'uuid\\': \\'ab77edb9-c670-47df-b1f4-cf75ceffbc54\\', \\'_id\\': \\'853f756a0c6c486d8ab3e4906027d396\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Materials and methods\\\\n\\\\nEthical considerations\\\\n\\\\nOur study was conducted with adherence to ethical standards, and all necessary approvals were obtained before data collection. Institutional Review Board approval was obtained from the Sheikh Ragheb Harb University Hospital (authorization number: 3279/1/22).\\\\n\\\\nStudy design\\\\n\\\\nThis study employed a retrospective observational design to investigate the epidemiology of pediatric RTIs in hospitalized children. Data collection was conducted through the review of medical records of children aged between one month and 13 years admitted to three major hospitals in Lebanon. The participating hospitals included Sheikh Ragheb Harb University Hospital located in Toul, Nabatieh Governorate, Al Sahel Hospital in Beirut, and Rafik Hariri University Hospital in Beirut.\\'), Document(metadata={\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'uuid\\': \\'3da29fc9-4ab5-4965-a1ff-380fa33de2e3\\', \\'_id\\': \\'0b55a36f2330462db6992886670a189f\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'The study period spanned from October 2018 to March 2021, allowing for a comparison between the pre-COVID-19 era (October 2018 to February 2020) and the COVID-19 era (February 2020 to March 2021).\\\\n\\\\nData collection involved a systematic review of medical files and the extraction of relevant information according to a standardized questionnaire. This approach facilitated the collection of comprehensive data on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage among hospitalized children with RTIs.\\\\n\\\\nStudy population\\\\n\\\\nWe\\\\xa0recruited 500 cases of children with RTI between the period of 2018 and 2021.\\\\n\\\\nInclusion Criteria\\\\n\\\\nWe included children between one month and 13 years old admitted with upper or lower RTI with symptoms such as fever, cough, and dyspnea.\\\\n\\\\nExclusion Criteria\\')]}, \\'38885115\\': {\\'PMID\\': \\'38885115\\', \\'Title\\': \\'Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\\', \\'Generated Answer\\': \"I don\\'t know.\", \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38885115\\', \\'Title\\': \\'Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\\', \\'uuid\\': \\'0c1f8c0c-3d99-4db3-b4b2-7afed82ec04a\\', \\'_id\\': \\'5b3f7d953eff4ab5a3875ff1564eeef3\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'cannot fetch\\')]}, \\'38779335\\': {\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'Generated Answer\\': \\'The data used in the study were patient medical claims related to COVID-19. The study was conducted in compliance with the Health Insurance Portability and Accountability Act (HIPAA) and Privacy Rule 45 CFR 164.514(e). The data were used in accordance with these regulations, and the study was exempt from Institutional Review Board review. The study mentioned limitations related to potential underestimation or overestimation of costs due to selection bias, as patients who did not seek medical care or were not tested for COVID-19 may not have been included in the data.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'uuid\\': \\'0b12d97c-19d6-42be-b09c-9335d3de025b\\', \\'_id\\': \\'0115abbac6614701bc002b7012e138d9\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'The data were used in full compliance with the relevant provisions of the Health Insurance Portability and Accountability Act. The study was conducted under the research provisions of Privacy Rule 45 CFR 164.514(e) and was exempt from Institutional Review Board review.\\\\n\\\\n\\\\n\\\\nPatient Identification\\\\n\\\\nPatients with COVID-19, as defined by at least 1 COVID-19 medical claim (\\'), Document(metadata={\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'uuid\\': \\'a42b6e59-5f9e-4c94-9e4c-3ca915fe2e46\\', \\'_id\\': \\'1ea5fc2e7a694d25a191cd2ad179b198\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Supplementary Material\\\\n\\\\nOnline Supplementary Material\\\\n\\\\n\\\\n\\\\nAcknowledgments\\\\n\\\\nLeena Patel, PhD, Chrysi Petraki, PhD, and Daria Renshaw from IQVIA provided medical writing and editorial support, which was funded by Carelon Research.\\'), Document(metadata={\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'uuid\\': \\'ee1f65dc-ba23-4d15-a78d-dc1489be0897\\', \\'_id\\': \\'826dec8407ff49bab845948970d8197a\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Limitations\\\\n\\\\nThis study has a few limitations that require consideration. There is a possibility of underestimation or overestimation of costs, depending on how they were being reported, due to selection bias, as patients who did not seek medical care (including those who were not tested or did not report COVID-19 infection, or those with asymptomatic infections) would not have available data and therefore would not have been included.\\')]}, \\'38644506\\': {\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'Generated Answer\\': \\'The data source used in the study mentioned is the Clinical Data Analysis and Reporting System (CDARS), which is a territory-wide routine electronic medical record (EMR) developed by the Hospital Authority in Hong Kong. CDARS contains anonymized patient-level data, including demographics, deaths, attendances, and diagnoses coded based on the International Classification of Diseases, 9th Revision, Clinical Modification (ICD-9-CM). This system has been used since 1993 across outpatient, inpatient, and emergency settings for research and auditing purposes in the public sector. The quality and accuracy of CDARS have been demonstrated in population-based studies on COVID-19.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'uuid\\': \\'3c2e17a7-2d1b-4743-bb63-dc384edbcd53\\', \\'_id\\': \\'739fb264248f4163aa0ec5cce1944110\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Availability of data and materials\\\\n\\\\nWe are unable to directly share the data used in this study since the data custodian, the Hong Kong Hospital Authority who manages the Clinical Data Analysis and Reporting System (CDARS), has not given permission. However, CDARS data can be accessed via the Hospital Authority Data Sharing Portal for research purpose. The relevant information can be found online (\\\\n\\\\nDeclarations\\\\n\\\\nEthics approval and consent to participate\\\\n\\\\nThis study received ethics approval from the Institutional Review Board of The University of Hong Kong/Hospital Authority Hong Kong Western Cluster (UW 20-218). Informed consent has been waived as the study utilized de-identified data.\\\\n\\\\nConsent for publication\\\\n\\\\nNot applicable.\\\\n\\\\nCompeting interests\\'), Document(metadata={\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'uuid\\': \\'6e69cd61-ae72-47d0-b96e-faf5509c6428\\', \\'_id\\': \\'a23228f9e72f4326bf782f8b37970e57\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Methods\\\\n\\\\n\\\\n\\\\nData source\\\\n\\\\nWe analyzed the Clinical Data Analysis and Reporting System (CDARS), the territory-wide routine electronic medical record (EMR) developed by the Hospital Authority, which manages all public healthcare services in Hong Kong and provides publicly funded healthcare services to all eligible residents (>\\\\u20097.6 million). CDARS covers real-time anonymized patient-level data, including demographics, deaths, attendances, and all-cause diagnoses coded based on the International Classification of Diseases, 9th Revision, Clinical Modification (ICD-9-CM), since 1993 across outpatient, inpatient, and emergency settings for research and auditing purposes in the public sector. The quality and accuracy of CDARS have been demonstrated in population-based studies on COVID-19 [\\\\n\\\\n\\\\n\\\\nStudy design and participants\\'), Document(metadata={\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'uuid\\': \\'e9c2bafd-9ab8-4afc-893c-c3e3f8450988\\', \\'_id\\': \\'a960c7d3c7d1403eb4ee947ea2a36081\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Authors’ Twitter handles\\\\n\\\\nVivien Kin Yi Chan: @vivienkinyichan\\\\n\\\\nMartin Knapp: @knappem\\\\n\\\\nHao Luo: @HaoLuo429\\\\n\\\\nIan Chi Kei Wong: @Ian_HKU\\\\n\\\\nXue Li: @snowly12191\\\\n\\\\nHKU Pharmacy: @HkuPharm\\\\n\\\\nFunding\\\\n\\\\nThe study was jointly supported by the Collaborative Research Fund (ACESO, C7154-20GF), the Research Impact Fund (SCAN-2030, R7007-22) granted by the Research Grant Council, University Grants Committee, and\\\\xa0the Health and Medical Research Fund (COVID19F04; COVID19F11) granted by the Health Bureau, The Government of the Hong Kong Special Administrative Region, and the Laboratory of Data Discovery for Health (D\\\\n\\\\nAvailability of data and materials\\')]}}', name='Fetch_Extract_Tool', tool_call_id='call_fR7rclKNBZduynKOpO5AkIBH')]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "2024-10-03 14:30:44 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "Receiving update from node: 'agent'\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "[AIMessage(content=\"Here's a summary of the entire process and findings for each paper:\\n\\n1. **Search and Retrieval**: I used the PubMed search tool to find papers related to the impact of COVID-19 on healthcare resource utilization. The search returned several papers, and I retrieved their abstracts.\\n\\n2. **Screening**: I screened the abstracts based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic. The screening tool evaluated the abstracts for semantic similarity to the criteria, resulting in the inclusion of six papers for further analysis.\\n\\n3. **Full-Text Retrieval and Information Extraction**: I fetched the full-text articles for the included papers and extracted information about the data sources used in each study, focusing on medical records.\\n\\n - **PMID 39063396**: The study used medical records from the University of Mississippi Medical Center's enterprise data warehouse to examine healthcare resource utilization and expenditures during the COVID-19 pandemic.\\n \\n - **PMID 39051414**: This study utilized the 2020 National Inpatient Sample (NIS) dataset, a de-identified, publicly available inpatient database in the U.S., to analyze the impact of COVID-19 on sickle cell crisis outcomes.\\n \\n - **PMID 38966443**: The study reviewed medical records from three hospitals in Lebanon to compare pediatric respiratory tract infections before and during the COVID-19 pandemic.\\n \\n - **PMID 38885115**: The data source information was not available for this study.\\n \\n - **PMID 38779335**: The study used patient medical claims data related to COVID-19, compliant with HIPAA regulations, to assess healthcare resource utilization and costs.\\n \\n - **PMID 38644506**: The study analyzed data from the Clinical Data Analysis and Reporting System (CDARS) in Hong Kong, which contains anonymized patient-level data from public healthcare services.\\n\\n4. **Summary**: The process involved searching for relevant papers, screening them based on specific criteria, and extracting detailed data source information from the full-text articles. The studies utilized various data sources, including medical records, national inpatient samples, and electronic medical records, to analyze the impact of COVID-19 on healthcare resource utilization.\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 455, 'prompt_tokens': 12075, 'total_tokens': 12530, 'prompt_tokens_details': {'cached_tokens': 6912}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'stop', 'logprobs': None}, id='run-716ed46c-b9ee-40a1-83a4-00c10b76c534-0', usage_metadata={'input_tokens': 12075, 'output_tokens': 455, 'total_tokens': 12530})]\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "Final message content from the last chunk:\n" ] }, { "data": { "text/markdown": [ "```markdown\n", "Here's a summary of the entire process and findings for each paper:\n", "\n", "1. **Search and Retrieval**: I used the PubMed search tool to find papers related to the impact of COVID-19 on healthcare resource utilization. The search returned several papers, and I retrieved their abstracts.\n", "\n", "2. **Screening**: I screened the abstracts based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic. The screening tool evaluated the abstracts for semantic similarity to the criteria, resulting in the inclusion of six papers for further analysis.\n", "\n", "3. **Full-Text Retrieval and Information Extraction**: I fetched the full-text articles for the included papers and extracted information about the data sources used in each study, focusing on medical records.\n", "\n", " - **PMID 39063396**: The study used medical records from the University of Mississippi Medical Center's enterprise data warehouse to examine healthcare resource utilization and expenditures during the COVID-19 pandemic.\n", " \n", " - **PMID 39051414**: This study utilized the 2020 National Inpatient Sample (NIS) dataset, a de-identified, publicly available inpatient database in the U.S., to analyze the impact of COVID-19 on sickle cell crisis outcomes.\n", " \n", " - **PMID 38966443**: The study reviewed medical records from three hospitals in Lebanon to compare pediatric respiratory tract infections before and during the COVID-19 pandemic.\n", " \n", " - **PMID 38885115**: The data source information was not available for this study.\n", " \n", " - **PMID 38779335**: The study used patient medical claims data related to COVID-19, compliant with HIPAA regulations, to assess healthcare resource utilization and costs.\n", " \n", " - **PMID 38644506**: The study analyzed data from the Clinical Data Analysis and Reporting System (CDARS) in Hong Kong, which contains anonymized patient-level data from public healthcare services.\n", "\n", "4. **Summary**: The process involved searching for relevant papers, screening them based on specific criteria, and extracting detailed data source information from the full-text articles. The studies utilized various data sources, including medical records, national inpatient samples, and electronic medical records, to analyze the impact of COVID-19 on healthcare resource utilization.\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from langchain_core.messages import SystemMessage, HumanMessage\n", "from langchain.tools import StructuredTool\n", "from langchain.agents import initialize_agent, Tool, AgentType\n", "from langchain_openai import ChatOpenAI\n", "from langgraph.graph.message import add_messages\n", "from langgraph.graph import StateGraph, END\n", "from pydantic import BaseModel\n", "from typing import List, TypedDict, Annotated\n", "import xml.etree.ElementTree as ET\n", "import uuid\n", "import re\n", "from langgraph.prebuilt import ToolNode\n", "from Bio import Entrez\n", "from langchain_qdrant import QdrantVectorStore\n", "from qdrant_client import QdrantClient\n", "from qdrant_client.http.models import Distance, VectorParams\n", "from qdrant_client.http.models import Filter, FieldCondition, MatchValue\n", "from langchain_huggingface import HuggingFaceEmbeddings\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "from langchain.chains import (\n", " ConversationalRetrievalChain,\n", ")\n", "from langchain.docstore.document import Document\n", "from langchain.memory import ChatMessageHistory, ConversationBufferMemory\n", "\n", "# 1. Define PubMed Search Tool\n", "class PubMedSearchInput(BaseModel):\n", " query: str\n", "\n", "# PubMed search tool using Entrez (now with structured inputs)\n", "def pubmed_search(query: str, max_results: int = 10):\n", " \"\"\"Search PubMed using Entrez API and return abstracts.\"\"\"\n", " handle = Entrez.esearch(db=\"pubmed\", term=query, retmax=max_results)\n", " record = Entrez.read(handle)\n", " handle.close()\n", " pmids = record[\"IdList\"]\n", " \n", " # Fetch abstracts\n", " handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n", " records = Entrez.read(handle)\n", " handle.close()\n", "\n", " abstracts = []\n", " for record in records['PubmedArticle']:\n", " try:\n", " title = record['MedlineCitation']['Article']['ArticleTitle']\n", " abstract = record['MedlineCitation']['Article']['Abstract']['AbstractText'][0]\n", " pmid = record['MedlineCitation']['PMID']\n", " abstracts.append({\"PMID\": pmid, \"Title\": title, \"Abstract\": abstract})\n", " except KeyError:\n", " pass\n", " return abstracts\n", "\n", "# Define the AbstractScreeningInput using Pydantic BaseModel\n", "class AbstractScreeningInput(BaseModel):\n", " abstracts: List[dict]\n", " criteria: str\n", "\n", "def screen_abstracts_semantic(abstracts: List[dict], criteria: str, similarity_threshold: float = 0.4):\n", " \"\"\"Screen abstracts based on semantic similarity to the criteria.\"\"\"\n", " \n", " # Compute the embedding of the criteria\n", " criteria_embedding = semantic_model.encode(criteria, convert_to_tensor=True)\n", " \n", " screened = []\n", " for paper in abstracts:\n", " abstract_text = paper['Abstract']\n", " \n", " # Compute the embedding of the abstract\n", " abstract_embedding = semantic_model.encode(abstract_text, convert_to_tensor=True)\n", " \n", " # Compute cosine similarity between the abstract and the criteria\n", " similarity_score = util.cos_sim(abstract_embedding, criteria_embedding).item()\n", " \n", " if similarity_score >= similarity_threshold:\n", " screened.append({\n", " \"PMID\": paper['PMID'], \n", " \"Decision\": \"Include\", \n", " \"Reason\": f\"Similarity score {similarity_score:.2f} >= threshold {similarity_threshold}\"\n", " })\n", " else:\n", " screened.append({\n", " \"PMID\": paper['PMID'], \n", " \"Decision\": \"Exclude\", \n", " \"Reason\": f\"Similarity score {similarity_score:.2f} < threshold {similarity_threshold}\"\n", " })\n", " \n", " return screened\n", "\n", "# Define the PubMed Search Tool as a StructuredTool with proper input schema\n", "pubmed_tool = StructuredTool(\n", " name=\"PubMed_Search_Tool\",\n", " func=pubmed_search,\n", " description=\"Search PubMed for research papers and retrieve abstracts. Pass the abstracts (returned results) to another tool.\",\n", " args_schema=PubMedSearchInput # Use Pydantic BaseModel for schema\n", ")\n", "\n", "# Define the Abstract Screening Tool with semantic screening\n", "semantic_screening_tool = StructuredTool(\n", " name=\"Semantic_Abstract_Screening_Tool\",\n", " func=screen_abstracts_semantic,\n", " description=\"\"\"Screen PubMed abstracts based on semantic similarity to inclusion/exclusion criteria. Uses cosine similarity between abstracts and criteria. Requires 'abstracts' and 'screening criteria' as input.\n", " The 'abstracts' is a list of dictionary with keys as PMID, Title, Abstract.\n", " Output a similarity scores for each abstract and send the list of pmids that passed the screening to Fetch_Extract_Tool.\"\"\",\n", " args_schema=AbstractScreeningInput # Pydantic schema remains the same\n", ")\n", "\n", "# 3. Define Full-Text Retrieval Tool\n", "class FetchExtractInput(BaseModel):\n", " pmids: List[str] # List of PubMed IDs to fetch full text for\n", " query: str\n", "\n", "def extract_text_from_pmc_xml(xml_content: str) -> str:\n", " \"\"\"a function to format and clean text from PMC full-text XML.\"\"\"\n", " try:\n", " root = ET.fromstring(xml_content)\n", " \n", " # Find all relevant text sections (e.g., , ,

)\n", " body_text = []\n", " for elem in root.iter():\n", " if elem.tag in ['p', 'sec', 'title', 'abstract', 'body']: # Add more tags as needed\n", " if elem.text:\n", " body_text.append(elem.text.strip())\n", " \n", " # Join all the text elements to form the complete full text\n", " full_text = \"\\n\\n\".join(body_text)\n", " \n", " return full_text\n", " except ET.ParseError:\n", " print(\"Error parsing XML content.\")\n", " return \"\"\n", "\n", "def fetch_and_extract(pmids: List[str], query: str):\n", " \"\"\"Fetch full text from PubMed Central for given PMIDs, split into chunks, \n", " store in a Qdrant vector database, and perform RAG for each paper.\n", " Retrieves exactly 3 chunks per paper (if available) and generates a consolidated answer for each paper.\n", " \"\"\"\n", " embedding_model = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n", " corpus = {}\n", " consolidated_results={}\n", "\n", " # Fetch records from PubMed Central (PMC)\n", " handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n", " records = Entrez.read(handle)\n", " handle.close()\n", "\n", " full_articles = []\n", " for record in records['PubmedArticle']:\n", " try:\n", " title = record['MedlineCitation']['Article']['ArticleTitle']\n", " pmid = record['MedlineCitation']['PMID']\n", " pmc_id = 'nan'\n", " pmc_id_temp = record['PubmedData']['ArticleIdList']\n", " \n", " # Extract PMC ID if available\n", " for ele in pmc_id_temp:\n", " if ele.attributes['IdType'] == 'pmc':\n", " pmc_id = ele.replace('PMC', '')\n", " break\n", "\n", " # Fetch full article from PMC\n", " if pmc_id != 'nan':\n", " handle = Entrez.efetch(db=\"pmc\", id=pmc_id, rettype=\"full\", retmode=\"xml\")\n", " full_article = handle.read()\n", " handle.close()\n", "\n", " # Split the full article into chunks\n", " cleaned_full_article = extract_text_from_pmc_xml(full_article)\n", " full_articles.append({\n", " \"PMID\": pmid,\n", " \"Title\": title,\n", " \"FullText\": cleaned_full_article # Add chunked text\n", " })\n", " else:\n", " full_articles.append({\"PMID\": pmid, \"Title\": title, \"FullText\": \"cannot fetch\"})\n", " except KeyError:\n", " pass\n", "\n", " # Create corpus for each chunk\n", " for article in full_articles:\n", " article_id = str(uuid.uuid4())\n", " corpus[article_id] = {\n", " \"page_content\": article[\"FullText\"],\n", " \"metadata\": {\n", " \"PMID\": article[\"PMID\"],\n", " \"Title\": article[\"Title\"]\n", " }\n", " }\n", "\n", " documents = [\n", " Document(page_content=content[\"page_content\"], metadata=content[\"metadata\"]) \n", " for content in corpus.values()\n", " ]\n", " CHUNK_SIZE = 1000\n", " CHUNK_OVERLAP = 200\n", "\n", " text_splitter = RecursiveCharacterTextSplitter(\n", " chunk_size=CHUNK_SIZE,\n", " chunk_overlap=CHUNK_OVERLAP,\n", " length_function=len,\n", " )\n", " \n", " split_chunks = text_splitter.split_documents(documents)\n", " \n", " id_set = set()\n", " for document in split_chunks:\n", " id = str(uuid.uuid4())\n", " while id in id_set:\n", " id = uuid.uuid4()\n", " id_set.add(id)\n", " document.metadata[\"uuid\"] = id\n", "\n", " LOCATION = \":memory:\"\n", " COLLECTION_NAME = \"pmd_data\"\n", " VECTOR_SIZE = 384\n", "\n", " # Initialize Qdrant client\n", " qdrant_client = QdrantClient(location=LOCATION)\n", "\n", " # Create a collection in Qdrant\n", " qdrant_client.create_collection(\n", " collection_name=COLLECTION_NAME,\n", " vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),\n", " )\n", "\n", " # Initialize the Qdrant vector store without the embedding argument\n", " vdb = QdrantVectorStore(\n", " client=qdrant_client,\n", " collection_name=COLLECTION_NAME,\n", " embedding=embedding_model,\n", " )\n", "\n", " # Add embedded documents to Qdrant\n", " vdb.add_documents(split_chunks)\n", "\n", " # Query for each paper and consolidate answers\n", " for pmid in pmids:\n", " # Correctly structure the filter using Qdrant Filter model\n", " qdrant_filter = Filter(\n", " must=[\n", " FieldCondition(key=\"metadata.PMID\", match=MatchValue(value=pmid))\n", " ]\n", " )\n", "\n", " # Custom filtering for the retriever to only fetch chunks related to the current PMID\n", " retriever_with_filter = vdb.as_retriever(\n", " search_kwargs={\n", " \"filter\": qdrant_filter, # Correctly passing the Qdrant filter\n", " \"k\": 3 # Retrieve 3 chunks per PMID\n", " }\n", " )\n", "\n", " # Reset message history and memory for each query to avoid interference\n", " message_history = ChatMessageHistory()\n", " memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key=\"answer\", chat_memory=message_history, return_messages=True)\n", "\n", " # Create the ConversationalRetrievalChain with the filtered retriever\n", " qa_chain = ConversationalRetrievalChain.from_llm(\n", " ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0),\n", " retriever=retriever_with_filter,\n", " memory=memory,\n", " return_source_documents=True\n", " )\n", "\n", " # Query the vector store for relevant documents and extract information\n", " result = qa_chain({\"question\": query})\n", "\n", " # Generate the final answer based on the retrieved chunks\n", " generated_answer = result[\"answer\"] # This contains the LLM's generated answer based on the retrieved chunks\n", " generated_source = result[\"source_documents\"]\n", "\n", " # Consolidate the results for each paper\n", " paper_info = {\n", " \"PMID\": pmid,\n", " \"Title\": result[\"source_documents\"][0].metadata[\"Title\"] if result[\"source_documents\"] else \"Unknown Title\",\n", " \"Generated Answer\": generated_answer, # Store the generated answer,\n", " \"Sources\": generated_source \n", " }\n", "\n", " consolidated_results[pmid] = paper_info\n", "\n", " # Return consolidated results for all papers\n", " return consolidated_results\n", "\n", "rag_tool = StructuredTool(\n", " name=\"Fetch_Extract_Tool\",\n", " func=fetch_and_extract,\n", " description=\"\"\"Fetch full-text articles based on PMIDs and store them in a Qdrant vector database.\n", " Then extract information based on user's query via Qdrant retriever using a RAG pipeline.\n", " Requires list of PMIDs and user query as input.\"\"\",\n", " args_schema=FetchExtractInput\n", ")\n", "\n", "\n", "tool_belt = [\n", " pubmed_tool,\n", " semantic_screening_tool,\n", " rag_tool\n", "]\n", "\n", "# Model setup with tools bound\n", "model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n", "model = model.bind_tools(tool_belt)\n", "\n", "# Agent state to handle the messages\n", "class AgentState(TypedDict):\n", " messages: Annotated[list, add_messages]\n", " cycle_count: int # Add a counter to track the number of cycles\n", "\n", "# Function to call the model and handle the flow automatically\n", "def call_model(state):\n", " messages = state[\"messages\"]\n", " response = model.invoke(messages)\n", " return {\"messages\": [response], \"cycle_count\": state[\"cycle_count\"] + 1} # Increment cycle count\n", "\n", "tool_node = ToolNode(tool_belt)\n", "\n", "# Create the state graph for managing the flow between the agent and tools\n", "uncompiled_graph = StateGraph(AgentState)\n", "uncompiled_graph.add_node(\"agent\", call_model)\n", "uncompiled_graph.add_node(\"action\", tool_node)\n", "\n", "# Set the entry point for the graph\n", "uncompiled_graph.set_entry_point(\"agent\")\n", "\n", "# Define a function to check if the process should continue\n", "def should_continue(state):\n", " # Check if the cycle count exceeds the limit (e.g., 10)\n", " if state[\"cycle_count\"] > 20:\n", " print(f\"Reached the cycle limit of {state['cycle_count']} cycles. Ending the process.\")\n", " return END\n", " \n", " # If there are tool calls, continue to the action node\n", " last_message = state[\"messages\"][-1]\n", " if last_message.tool_calls:\n", " return \"action\"\n", " \n", " return END\n", "\n", "# Add conditional edges for the agent to action\n", "uncompiled_graph.add_conditional_edges(\"agent\", should_continue)\n", "uncompiled_graph.add_edge(\"action\", \"agent\")\n", "\n", "# Compile the state graph\n", "compiled_graph = uncompiled_graph.compile()\n", "\n", "# SystemMessage that defines the execution flow\n", "system_instructions = SystemMessage(content=\"\"\"Please execute the following steps in sequence:\n", "1. Use the PubMed search tool to search for papers.\n", "2. Retrieve the abstracts from the search results.\n", "3. Screen the abstracts based on the criteria provided by the user.\n", "4. Fetch full-text articles for all the papers that pass step 3. Store the full-text articles in the Qdrant vector database, \n", " and extract the requested information for each article that passed step 3 from the full-text using the query provided by the user.\n", "5. Please provide a full summary at the end of the entire flow executed, detailing the whole process/reasoning for each paper. \n", "The user will provide the search query, screening criteria, and the query for information extraction.\n", "Make sure you finish everything in one step before moving on to next step.\n", "Do not call more than one tool in one action.\"\"\")\n", "\n", "# HumanMessage only includes the necessary inputs\n", "human_inputs = HumanMessage(content=\"\"\"{\n", " \"query\": \"(\\\"Impact\\\"[Title/Abstract]) AND ((\\\"COVID\\\"[Title/Abstract] OR \\\"pandemic\\\"[Title/Abstract]) AND (\\\"healthcare resource utilization\\\"[Title/Abstract] OR \\\"health resource utilization\\\"[Title/Abstract]))\",\n", " \"screening_criteria\": \"comparison of healthcare resource utilization before and after the COVID pandemic\",\n", " \"extraction_query\": \"data source information used in each paper (especially medical records)\"\n", "}\"\"\")\n", "\n", "# Combined input for the agent\n", "inputs = {\n", " \"messages\": [system_instructions, human_inputs],\n", " \"cycle_count\": 0, # Initialize cycle count to 0\n", "}\n", "\n", "# # Function to run the graph asynchronously\n", "async def run_graph():\n", " final_message_content = None # Variable to store the final message content\n", "\n", " async for chunk in compiled_graph.astream(inputs, stream_mode=\"updates\"):\n", " for node, values in chunk.items():\n", " print(f\"Receiving update from node: '{node}'\")\n", " pretty_print(values[\"messages\"]) # Print all messages as before\n", " \n", " # Check if the message contains content\n", " if \"messages\" in values and values[\"messages\"]:\n", " final_message = values[\"messages\"][-1] # Access the last message in this chunk\n", " if hasattr(final_message, 'content'): # Check if content exists\n", " final_message_content = final_message.content # Store the last message's content\n", " \n", " print(\"\\n\\n\")\n", "\n", " # After the loop finishes, print the final message content\n", " if final_message_content:\n", " print(\"Final message content from the last chunk:\")\n", " pretty_print(final_message_content)\n", " else:\n", " print(\"No final message content found.\")\n", "\n", "# Run the compiled graph\n", "await run_graph()" ] }, { "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.9" } }, "nbformat": 4, "nbformat_minor": 2 }