Talk2KGs Agentic Tools¶
In this tutorial, we showcase how to invoke tools of Talk2KnowledgeGraphs via Jupiter Notebook.
As of now, the agent has the following capabilities:
- Subgraph Extraction: to extract a subgraph from a knowledge graph provided by the user
- Subgraph Summarization: to summarize a subgraph extracted from textualized subgraph obtained from the previous step
- GraphRAG Reasoning: to perform reasoning on a subgraph extracted from a knowledge graph by taking into account the context of the subgraph and documents provided by the user
# Import necessary libraries
import os
import networkx as nx
import openai
import matplotlib.pyplot as plt
import sys
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
sys.path.append('../../..')
from aiagents4pharma.talk2knowledgegraphs.tools.subgraph_extraction import SubgraphExtractionTool
from aiagents4pharma.talk2knowledgegraphs.tools.subgraph_summarization import SubgraphSummarizationTool
from aiagents4pharma.talk2knowledgegraphs.tools.graphrag_reasoning import GraphRAGReasoningTool
Set up your API key¶
Before following this tutorial, make sure that you set up necessary environment variables, especially the API key if you are using LLM models from OpenAI.
You can use the following options to set API key.
Option 1 : Retrieve API Key from Environment Variable¶
# Retrieve API key from environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")
Option 2: Store API Key Directly in the Script (Temporary)¶
os.environ["OPENAI_API_KEY"] = "your_api_key"
# Make sure to replace "your_api_key" with your actual API key.
SubgraphExtractionTool¶
Before invoking the tool, we need to define a dictionary as agent state that will be passed to the tool along with a prompt from user.
# Define the data path
DATA_PATH = "../../../aiagents4pharma/talk2knowledgegraphs/tests/files"
# DATA_PATH = "../../../../data"
# Setup dictionary as agent state
agent_state = {
"llm_model": ChatOpenAI(model="gpt-4o-mini", temperature=0.0),
"embedding_model": OpenAIEmbeddings(model="text-embedding-3-small"),
"uploaded_files": [],
"topk_nodes": 3,
"topk_edges": 3,
"dic_source_graph": [
{
"name": "PrimeKG",
"kg_pyg_path": f"{DATA_PATH}/primekg_ibd_pyg_graph.pkl",
"kg_text_path": f"{DATA_PATH}/primekg_ibd_text_graph.pkl",
}
],
"dic_extracted_graph": []
}
# Prepare the prompt for subgraph extraction
prompt = """
Extract all relevant information related to nodes of genes related to inflammatory bowel disease
(IBD) that existed in the knowledge graph.
Please set the extraction name for this process as `subkg_12345`."""
# Instantiate the SubgraphExtractionTool
subgraph_extraction_tool = SubgraphExtractionTool()
# Invoking the subgraph_extraction_tool
result = subgraph_extraction_tool.invoke(input={"prompt": prompt,
"tool_call_id": "subgraph_extraction_tool",
"state": agent_state,
"arg_data": {"extraction_name": "subkg_12345"}})
INFO:aiagents4pharma.talk2knowledgegraphs.tools.subgraph_extraction:Invoking subgraph_extraction tool INFO:httpx:HTTP Request: GET http://127.0.0.1:11434/api/tags "HTTP/1.1 200 OK" INFO:httpx:HTTP Request: POST http://127.0.0.1:11434/api/embed "HTTP/1.1 200 OK"
We can check the result of the subgraph extraction tool by two approachs:
- Visualize the extracted subgraph by firstly converting the extracted subgraph to a networkx graph and then visualizing it using matplotlib.
- Print the extracted textualized subgraph.
Subgraph Visualization
def dict_to_nx_graph(graph_dict):
"""
Convert a dictionary representation of a graph to a NetworkX graph.
"""
# Create a directed graph
graph = nx.DiGraph()
# Add nodes with attributes
for node, attrs in graph_dict["nodes"]:
graph.add_node(node, **attrs)
# Add edges with attributes
for source, target, attrs in graph_dict["edges"]:
graph.add_edge(source, target, **attrs)
return graph
# Extracted subgraph
nx_graph = dict_to_nx_graph(result.update['dic_extracted_graph'][0]['graph_dict'])
# Visualize the extracted subgraph
# Make a simple plot of the knowledge graph
plt.figure(figsize=(10, 10))
pos = nx.shell_layout(nx_graph)
nx.draw(nx_graph, pos, with_labels=True, node_size=3000, node_color='skyblue')
nx.draw_networkx_edge_labels(nx_graph, pos, edge_labels={(u, v): d['relation'] for u, v, d in nx_graph.edges(data=True)})
plt.show()
Textualized Subgraph Printing
# Checking the result of subgraph extraction
print(result.update['dic_extracted_graph'][0]['graph_text'])
node_id,node_attr IFNG_(3495),"IFNG belongs to gene/protein category. This gene encodes a soluble cytokine that is a member of the type II interferon class. The encoded protein is secreted by cells of both the innate and adaptive immune systems. The active protein is a homodimer that binds to the interferon gamma receptor which triggers a cellular response to viral and microbial infections. Mutations in this gene are associated with an increased susceptibility to viral, bacterial and parasitic infections and to several autoimmune diseases. [provided by RefSeq, Dec 2015]." ATG16L1_(6661),"ATG16L1 belongs to gene/protein category. The protein encoded by this gene is part of a large protein complex that is necessary for autophagy, the major process by which intracellular components are targeted to lysosomes for degradation. Defects in this gene are a cause of susceptibility to inflammatory bowel disease type 10 (IBD10). Several transcript variants encoding different isoforms have been found for this gene.[provided by RefSeq, Jun 2010]." INAVA_(9104),"INAVA belongs to gene/protein category. Involved in several processes, including nucleotide-binding activity oligomerization domain containing 2 signaling pathway; positive regulation of cytokine production; and positive regulation of intracellular signal transduction. Located in cytoplasm and nucleus. Implicated in inflammatory bowel disease 29. [provided by Alliance of Genome Resources, Apr 2022]" inflammatory bowel disease_(28158),inflammatory bowel disease belongs to disease category. Any inflammatory bowel disease in which the cause of the disease is a mutation in the NOD2 gene. Crohn ileitis and jejunitis_(35814),Crohn ileitis and jejunitis belongs to disease category. An Crohn disease involving a pathogenic inflammatory response in the ileum. Crohn's colitis_(83770),Crohn's colitis belongs to disease category. Crohn's disease affecting the colon. head_id,edge_type,tail_id inflammatory bowel disease_(28158),"('disease', 'associated with', 'gene/protein')",INAVA_(9104) Crohn's colitis_(83770),"('disease', 'associated with', 'gene/protein')",ATG16L1_(6661) IFNG_(3495),"('gene/protein', 'associated with', 'disease')",inflammatory bowel disease_(28158) IFNG_(3495),"('gene/protein', 'associated with', 'disease')",Crohn's colitis_(83770) IFNG_(3495),"('gene/protein', 'associated with', 'disease')",Crohn ileitis and jejunitis_(35814)
Lastly, we can store the result of the subgraph extraction in the agent state to be used in the next tutorial for subgraph summarization.
# Store the result of subgraph extraction
agent_state["dic_extracted_graph"] = result.update["dic_extracted_graph"]
# Check current agent state
print(agent_state)
{'llm_model': ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x7003297ea7b0>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x70032971c560>, root_client=<openai.OpenAI object at 0x700428c27a70>, root_async_client=<openai.AsyncOpenAI object at 0x70049d756a80>, model_name='gpt-4o-mini', temperature=0.0, model_kwargs={}, openai_api_key=SecretStr('**********')), 'embedding_model': OpenAIEmbeddings(client=<openai.resources.embeddings.Embeddings object at 0x70032971ccb0>, async_client=<openai.resources.embeddings.AsyncEmbeddings object at 0x70032971eb40>, model='text-embedding-3-small', dimensions=None, deployment='text-embedding-ada-002', openai_api_version=None, openai_api_base=None, openai_api_type=None, openai_proxy=None, embedding_ctx_length=8191, openai_api_key=SecretStr('**********'), openai_organization=None, allowed_special=None, disallowed_special=None, chunk_size=1000, max_retries=2, request_timeout=None, headers=None, tiktoken_enabled=True, tiktoken_model_name=None, show_progress_bar=False, model_kwargs={}, skip_empty=False, default_headers=None, default_query=None, retry_min_seconds=4, retry_max_seconds=20, http_client=None, http_async_client=None, check_embedding_ctx_length=True), 'uploaded_files': [], 'topk_nodes': 3, 'topk_edges': 3, 'dic_source_graph': [{'name': 'PrimeKG', 'kg_pyg_path': '../../../aiagents4pharma/talk2knowledgegraphs/tests/files/primekg_ibd_pyg_graph.pkl', 'kg_text_path': '../../../aiagents4pharma/talk2knowledgegraphs/tests/files/primekg_ibd_text_graph.pkl'}], 'dic_extracted_graph': [{'name': 'subkg_12345', 'tool_call_id': 'subgraph_extraction_tool', 'graph_source': 'PrimeKG', 'topk_nodes': 3, 'topk_edges': 3, 'graph_dict': {'nodes': [('IFNG_(3495)', {}), ('ATG16L1_(6661)', {}), ('INAVA_(9104)', {}), ('inflammatory bowel disease_(28158)', {}), ('Crohn ileitis and jejunitis_(35814)', {}), ("Crohn's colitis_(83770)", {})], 'edges': [('IFNG_(3495)', 'inflammatory bowel disease_(28158)', {'relation': ['gene/protein', 'associated with', 'disease'], 'label': ['gene/protein', 'associated with', 'disease']}), ('IFNG_(3495)', "Crohn's colitis_(83770)", {'relation': ['gene/protein', 'associated with', 'disease'], 'label': ['gene/protein', 'associated with', 'disease']}), ('IFNG_(3495)', 'Crohn ileitis and jejunitis_(35814)', {'relation': ['gene/protein', 'associated with', 'disease'], 'label': ['gene/protein', 'associated with', 'disease']}), ('inflammatory bowel disease_(28158)', 'INAVA_(9104)', {'relation': ['disease', 'associated with', 'gene/protein'], 'label': ['disease', 'associated with', 'gene/protein']}), ("Crohn's colitis_(83770)", 'ATG16L1_(6661)', {'relation': ['disease', 'associated with', 'gene/protein'], 'label': ['disease', 'associated with', 'gene/protein']})]}, 'graph_text': 'node_id,node_attr\nIFNG_(3495),"IFNG belongs to gene/protein category. This gene encodes a soluble cytokine that is a member of the type II interferon class. The encoded protein is secreted by cells of both the innate and adaptive immune systems. The active protein is a homodimer that binds to the interferon gamma receptor which triggers a cellular response to viral and microbial infections. Mutations in this gene are associated with an increased susceptibility to viral, bacterial and parasitic infections and to several autoimmune diseases. [provided by RefSeq, Dec 2015]."\nATG16L1_(6661),"ATG16L1 belongs to gene/protein category. The protein encoded by this gene is part of a large protein complex that is necessary for autophagy, the major process by which intracellular components are targeted to lysosomes for degradation. Defects in this gene are a cause of susceptibility to inflammatory bowel disease type 10 (IBD10). Several transcript variants encoding different isoforms have been found for this gene.[provided by RefSeq, Jun 2010]."\nINAVA_(9104),"INAVA belongs to gene/protein category. Involved in several processes, including nucleotide-binding activity oligomerization domain containing 2 signaling pathway; positive regulation of cytokine production; and positive regulation of intracellular signal transduction. Located in cytoplasm and nucleus. Implicated in inflammatory bowel disease 29. [provided by Alliance of Genome Resources, Apr 2022]"\ninflammatory bowel disease_(28158),inflammatory bowel disease belongs to disease category. Any inflammatory bowel disease in which the cause of the disease is a mutation in the NOD2 gene. \nCrohn ileitis and jejunitis_(35814),Crohn ileitis and jejunitis belongs to disease category. An Crohn disease involving a pathogenic inflammatory response in the ileum. \nCrohn\'s colitis_(83770),Crohn\'s colitis belongs to disease category. Crohn\'s disease affecting the colon. \n\nhead_id,edge_type,tail_id\ninflammatory bowel disease_(28158),"(\'disease\', \'associated with\', \'gene/protein\')",INAVA_(9104)\nCrohn\'s colitis_(83770),"(\'disease\', \'associated with\', \'gene/protein\')",ATG16L1_(6661)\nIFNG_(3495),"(\'gene/protein\', \'associated with\', \'disease\')",inflammatory bowel disease_(28158)\nIFNG_(3495),"(\'gene/protein\', \'associated with\', \'disease\')",Crohn\'s colitis_(83770)\nIFNG_(3495),"(\'gene/protein\', \'associated with\', \'disease\')",Crohn ileitis and jejunitis_(35814)\n', 'graph_summary': None}]}
SubgraphSummarizationTool¶
# Prepare the prompt for subgraph summarization
prompt = """You are given a subgraph in the forms of textualized subgraph representing
nodes and edges (triples) obtained from extraction_name `subkg_12345`.
Summarize the given subgraph and higlight the importance nodes and edges.
"""
# Instantiate the SubgraphSummarizationTool
subgraph_summarization_tool = SubgraphSummarizationTool()
# Invoking the subgraph_summarization_tool
result = subgraph_summarization_tool.invoke(input={"prompt": prompt,
"extraction_name": "subkg_12345",
"tool_call_id": "subgraph_summarization_tool",
"state": agent_state,
"arg_data": {"extraction_name": "subkg_12345"}})
INFO:aiagents4pharma.talk2knowledgegraphs.tools.subgraph_summarization:Invoking subgraph_summarization tool for subkg_12345 INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"
We can check the result of subgraph summarization tool by printing the value of graph_summary
key in the result.
# Checking the result of subgraph summarization
print(result.update['dic_extracted_graph'][0]['graph_summary'])
The subgraph extracted from `subkg_12345` includes several important nodes and their relationships, primarily focusing on genes/proteins and their associations with inflammatory bowel diseases (IBD) and specific forms of Crohn's disease. ### Key Nodes: 1. **IFNG (Interferon Gamma)**: - Gene/protein that encodes a cytokine involved in immune responses. - Associated with increased susceptibility to various infections and autoimmune diseases, including inflammatory bowel diseases. 2. **ATG16L1**: - Gene/protein essential for autophagy, with defects linked to inflammatory bowel disease type 10 (IBD10). 3. **INAVA**: - Gene/protein involved in cytokine production and intracellular signaling, implicated in inflammatory bowel disease 29. 4. **Inflammatory Bowel Disease (IBD)**: - A disease category that includes conditions caused by mutations in the NOD2 gene. 5. **Crohn Ileitis and Jejunitis**: - A specific form of Crohn's disease affecting the ileum. 6. **Crohn's Colitis**: - A form of Crohn's disease affecting the colon. ### Important Edges: - **IFNG is associated with IBD**: This highlights the role of IFNG in the susceptibility to inflammatory bowel diseases. - **IFNG is associated with Crohn's Colitis and Crohn Ileitis and Jejunitis**: This indicates that IFNG may play a role in these specific forms of Crohn's disease. - **ATG16L1 is associated with Crohn's Colitis**: Suggests a link between autophagy processes and this form of Crohn's disease. - **INAVA is associated with IBD**: Indicates its involvement in the pathogenesis of inflammatory bowel diseases. ### Summary: The subgraph illustrates the connections between key genes/proteins (IFNG, ATG16L1, INAVA) and their associations with inflammatory bowel diseases, particularly Crohn's disease. IFNG is central to the immune response and is linked to multiple forms of IBD, while ATG16L1 and INAVA are implicated in specific disease mechanisms. This information is crucial for understanding the genetic factors contributing to these inflammatory conditions.
Afterward, we can store the result of subgraph summarization in the agent state to be used in the final step of the tutorial, which is reasoning.
# Store the result of subgraph summarization in the agent state
agent_state['dic_extracted_graph'][0]["graph_summary"] = result.update['dic_extracted_graph'][0]["graph_summary"]
# Check current agent state
print(agent_state)
{'llm_model': ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x7003297ea7b0>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x70032971c560>, root_client=<openai.OpenAI object at 0x700428c27a70>, root_async_client=<openai.AsyncOpenAI object at 0x70049d756a80>, model_name='gpt-4o-mini', temperature=0.0, model_kwargs={}, openai_api_key=SecretStr('**********')), 'embedding_model': OpenAIEmbeddings(client=<openai.resources.embeddings.Embeddings object at 0x70032971ccb0>, async_client=<openai.resources.embeddings.AsyncEmbeddings object at 0x70032971eb40>, model='text-embedding-3-small', dimensions=None, deployment='text-embedding-ada-002', openai_api_version=None, openai_api_base=None, openai_api_type=None, openai_proxy=None, embedding_ctx_length=8191, openai_api_key=SecretStr('**********'), openai_organization=None, allowed_special=None, disallowed_special=None, chunk_size=1000, max_retries=2, request_timeout=None, headers=None, tiktoken_enabled=True, tiktoken_model_name=None, show_progress_bar=False, model_kwargs={}, skip_empty=False, default_headers=None, default_query=None, retry_min_seconds=4, retry_max_seconds=20, http_client=None, http_async_client=None, check_embedding_ctx_length=True), 'uploaded_files': [], 'topk_nodes': 3, 'topk_edges': 3, 'dic_source_graph': [{'name': 'PrimeKG', 'kg_pyg_path': '../../../aiagents4pharma/talk2knowledgegraphs/tests/files/primekg_ibd_pyg_graph.pkl', 'kg_text_path': '../../../aiagents4pharma/talk2knowledgegraphs/tests/files/primekg_ibd_text_graph.pkl'}], 'dic_extracted_graph': [{'name': 'subkg_12345', 'tool_call_id': 'subgraph_extraction_tool', 'graph_source': 'PrimeKG', 'topk_nodes': 3, 'topk_edges': 3, 'graph_dict': {'nodes': [('IFNG_(3495)', {}), ('ATG16L1_(6661)', {}), ('INAVA_(9104)', {}), ('inflammatory bowel disease_(28158)', {}), ('Crohn ileitis and jejunitis_(35814)', {}), ("Crohn's colitis_(83770)", {})], 'edges': [('IFNG_(3495)', 'inflammatory bowel disease_(28158)', {'relation': ['gene/protein', 'associated with', 'disease'], 'label': ['gene/protein', 'associated with', 'disease']}), ('IFNG_(3495)', "Crohn's colitis_(83770)", {'relation': ['gene/protein', 'associated with', 'disease'], 'label': ['gene/protein', 'associated with', 'disease']}), ('IFNG_(3495)', 'Crohn ileitis and jejunitis_(35814)', {'relation': ['gene/protein', 'associated with', 'disease'], 'label': ['gene/protein', 'associated with', 'disease']}), ('inflammatory bowel disease_(28158)', 'INAVA_(9104)', {'relation': ['disease', 'associated with', 'gene/protein'], 'label': ['disease', 'associated with', 'gene/protein']}), ("Crohn's colitis_(83770)", 'ATG16L1_(6661)', {'relation': ['disease', 'associated with', 'gene/protein'], 'label': ['disease', 'associated with', 'gene/protein']})]}, 'graph_text': 'node_id,node_attr\nIFNG_(3495),"IFNG belongs to gene/protein category. This gene encodes a soluble cytokine that is a member of the type II interferon class. The encoded protein is secreted by cells of both the innate and adaptive immune systems. The active protein is a homodimer that binds to the interferon gamma receptor which triggers a cellular response to viral and microbial infections. Mutations in this gene are associated with an increased susceptibility to viral, bacterial and parasitic infections and to several autoimmune diseases. [provided by RefSeq, Dec 2015]."\nATG16L1_(6661),"ATG16L1 belongs to gene/protein category. The protein encoded by this gene is part of a large protein complex that is necessary for autophagy, the major process by which intracellular components are targeted to lysosomes for degradation. Defects in this gene are a cause of susceptibility to inflammatory bowel disease type 10 (IBD10). Several transcript variants encoding different isoforms have been found for this gene.[provided by RefSeq, Jun 2010]."\nINAVA_(9104),"INAVA belongs to gene/protein category. Involved in several processes, including nucleotide-binding activity oligomerization domain containing 2 signaling pathway; positive regulation of cytokine production; and positive regulation of intracellular signal transduction. Located in cytoplasm and nucleus. Implicated in inflammatory bowel disease 29. [provided by Alliance of Genome Resources, Apr 2022]"\ninflammatory bowel disease_(28158),inflammatory bowel disease belongs to disease category. Any inflammatory bowel disease in which the cause of the disease is a mutation in the NOD2 gene. \nCrohn ileitis and jejunitis_(35814),Crohn ileitis and jejunitis belongs to disease category. An Crohn disease involving a pathogenic inflammatory response in the ileum. \nCrohn\'s colitis_(83770),Crohn\'s colitis belongs to disease category. Crohn\'s disease affecting the colon. \n\nhead_id,edge_type,tail_id\ninflammatory bowel disease_(28158),"(\'disease\', \'associated with\', \'gene/protein\')",INAVA_(9104)\nCrohn\'s colitis_(83770),"(\'disease\', \'associated with\', \'gene/protein\')",ATG16L1_(6661)\nIFNG_(3495),"(\'gene/protein\', \'associated with\', \'disease\')",inflammatory bowel disease_(28158)\nIFNG_(3495),"(\'gene/protein\', \'associated with\', \'disease\')",Crohn\'s colitis_(83770)\nIFNG_(3495),"(\'gene/protein\', \'associated with\', \'disease\')",Crohn ileitis and jejunitis_(35814)\n', 'graph_summary': "The subgraph extracted from `subkg_12345` includes several important nodes and their relationships, primarily focusing on genes/proteins and their associations with inflammatory bowel diseases (IBD) and specific forms of Crohn's disease.\n\n### Key Nodes:\n1. **IFNG (Interferon Gamma)**: \n - Gene/protein that encodes a cytokine involved in immune responses. \n - Associated with increased susceptibility to various infections and autoimmune diseases, including inflammatory bowel diseases.\n\n2. **ATG16L1**: \n - Gene/protein essential for autophagy, with defects linked to inflammatory bowel disease type 10 (IBD10).\n\n3. **INAVA**: \n - Gene/protein involved in cytokine production and intracellular signaling, implicated in inflammatory bowel disease 29.\n\n4. **Inflammatory Bowel Disease (IBD)**: \n - A disease category that includes conditions caused by mutations in the NOD2 gene.\n\n5. **Crohn Ileitis and Jejunitis**: \n - A specific form of Crohn's disease affecting the ileum.\n\n6. **Crohn's Colitis**: \n - A form of Crohn's disease affecting the colon.\n\n### Important Edges:\n- **IFNG is associated with IBD**: This highlights the role of IFNG in the susceptibility to inflammatory bowel diseases.\n- **IFNG is associated with Crohn's Colitis and Crohn Ileitis and Jejunitis**: This indicates that IFNG may play a role in these specific forms of Crohn's disease.\n- **ATG16L1 is associated with Crohn's Colitis**: Suggests a link between autophagy processes and this form of Crohn's disease.\n- **INAVA is associated with IBD**: Indicates its involvement in the pathogenesis of inflammatory bowel diseases.\n\n### Summary:\nThe subgraph illustrates the connections between key genes/proteins (IFNG, ATG16L1, INAVA) and their associations with inflammatory bowel diseases, particularly Crohn's disease. IFNG is central to the immune response and is linked to multiple forms of IBD, while ATG16L1 and INAVA are implicated in specific disease mechanisms. This information is crucial for understanding the genetic factors contributing to these inflammatory conditions."}]}
GraphRAGReasoningTool¶
We would like to perform reasoning on the extracted subgraph and documents to answer a question.
For this purpose, we can set path to each document in the agent state.
# Set path to document
agent_state["uploaded_files"] = [
{
"file_name": "adalimumab",
"file_path": f"{DATA_PATH}/adalimumab.pdf",
"file_type": "drug_data",
"uploaded_by": "VPEUser",
"uploaded_timestamp": "2024-11-05 00:00:00",
},
]
# Instantiate the GraphRAGReasoningTool
graphrag_reasoning_tool = GraphRAGReasoningTool()
# Prepare the prompt for graph reasoning
prompt = """
Without extracting a new subgraph, based on subgraph extracted from `subkg_12345`
perform Graph RAG reasoning to get insights related to nodes of genes
mentioned in the knowledge graph related to Adalimumab.
Here is an additional context:
Adalimumab is a fully human monoclonal antibody (IgG1)
that specifically binds to tumor necrosis factor-alpha (TNF-α), a pro-inflammatory cytokine.
"""
# Invoking the graphrag_reasoning_tool
result = graphrag_reasoning_tool.invoke(input={"prompt": prompt,
"extraction_name": "subkg_12345",
"tool_call_id": "graphrag_reasoning_tool",
"state": agent_state,
"arg_data": {"extraction_name": "subkg_12345"}})
INFO:aiagents4pharma.talk2knowledgegraphs.tools.graphrag_reasoning:Invoking graphrag_reasoning tool for subkg_12345 INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK" INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK" INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"
Finally, we can check the result of GraphRAG reasoning tool that taking into accounts extracted subgraph and DrugA document provided by the user.
# Checking the result of graph reasoning
print(result.update["messages"])
[ToolMessage(content='{\'input\': \'\\nWithout extracting a new subgraph, based on subgraph extracted from `subkg_12345`\\nperform Graph RAG reasoning to get insights related to nodes of genes \\nmentioned in the knowledge graph related to Adalimumab. \\n\\nHere is an additional context:\\nAdalimumab is a fully human monoclonal antibody (IgG1) \\nthat specifically binds to tumor necrosis factor-alpha (TNF-α), a pro-inflammatory cytokine.\\n\', \'subgraph_summary\': "The subgraph extracted from `subkg_12345` includes several important nodes and their relationships, primarily focusing on genes/proteins and their associations with inflammatory bowel diseases (IBD) and specific forms of Crohn\'s disease.\\n\\n### Key Nodes:\\n1. **IFNG (Interferon Gamma)**: \\n - Gene/protein that encodes a cytokine involved in immune responses. \\n - Associated with increased susceptibility to various infections and autoimmune diseases, including inflammatory bowel diseases.\\n\\n2. **ATG16L1**: \\n - Gene/protein essential for autophagy, with defects linked to inflammatory bowel disease type 10 (IBD10).\\n\\n3. **INAVA**: \\n - Gene/protein involved in cytokine production and intracellular signaling, implicated in inflammatory bowel disease 29.\\n\\n4. **Inflammatory Bowel Disease (IBD)**: \\n - A disease category that includes conditions caused by mutations in the NOD2 gene.\\n\\n5. **Crohn Ileitis and Jejunitis**: \\n - A specific form of Crohn\'s disease affecting the ileum.\\n\\n6. **Crohn\'s Colitis**: \\n - A form of Crohn\'s disease affecting the colon.\\n\\n### Important Edges:\\n- **IFNG is associated with IBD**: This highlights the role of IFNG in the susceptibility to inflammatory bowel diseases.\\n- **IFNG is associated with Crohn\'s Colitis and Crohn Ileitis and Jejunitis**: This indicates that IFNG may play a role in these specific forms of Crohn\'s disease.\\n- **ATG16L1 is associated with Crohn\'s Colitis**: Suggests a link between autophagy processes and this form of Crohn\'s disease.\\n- **INAVA is associated with IBD**: Indicates its involvement in the pathogenesis of inflammatory bowel diseases.\\n\\n### Summary:\\nThe subgraph illustrates the connections between key genes/proteins (IFNG, ATG16L1, INAVA) and their associations with inflammatory bowel diseases, particularly Crohn\'s disease. IFNG is central to the immune response and is linked to multiple forms of IBD, while ATG16L1 and INAVA are implicated in specific disease mechanisms. This information is crucial for understanding the genetic factors contributing to these inflammatory conditions.", \'context\': [Document(id=\'6000cae4-6d3a-4d57-9805-a83d0327dec5\', metadata={\'source\': \'../../../aiagents4pharma/talk2knowledgegraphs/tests/files/adalimumab.pdf\', \'page\': 0}, page_content=\'adalimumab.md 2025-02-13\\n / \\n1. Drug Name\\nAdalimumab\\n2. Mechanism of Action (MoA)\\nAdalimumab is a fully human monoclonal antibody (IgG1) that speci\\x00cally binds to tumor necrosis\\nfactor-alpha (TNF-α), a pro-in\\x00ammatory cytokine. By neutralizing TNF-α, Adalimumab reduces\\nin\\x00ammation and prevents immune-mediated tissue damage, making it e\\x00ective in treating\\nin\\x00ammatory bowel diseases such as Crohn’s disease (CD) and ulcerative colitis (UC).\\n3. Pharmacokinetics\\nAbsorption: Administered subcutaneously (SC), reaching peak plasma concentration in approximately\\n4–6 days. Distribution: Exhibits a biphasic distribution with high speci\\x00city for TNF-α. Metabolism:\\nDegraded via proteolysis in the reticuloendothelial system. Excretion: Eliminated mainly via\\nintracellular catabolism, as monoclonal antibodies are not excreted through the liver or kidneys.\\n4. ADME (Absorption, Distribution, Metabolism, Excretion)\\nAbsorption: Bioavailability of approximately 64% after SC administration. Distribution: Volume of\'), Document(id=\'1050ff43-853b-468b-85b2-fa7c4cd52a54\', metadata={\'source\': \'../../../aiagents4pharma/talk2knowledgegraphs/tests/files/adalimumab.pdf\', \'page\': 0}, page_content=\'6. Target Binding\\nHigh speci\\x00city and a\\x00nity for TNF-α (~0.1 nM binding a\\x00nity). Inhibits both soluble and\\ntransmembrane TNF-α, preventing its interaction with TNF receptors. Reduces downstream pro-\\nin\\x00ammatory signaling cascades, such as NF-κB and MAPK pathways.\\n7. Pharmacodynamics\\nReduces pro-in\\x00ammatory cytokine production, including IL-1, IL-6, and interferon-γ. Decreases\\nleukocyte migration and adhesion, preventing tissue damage in the gastrointestinal (GI) tract.\\nImproves mucosal healing, reducing disease severity in Crohn’s disease and ulcerative colitis. Onset of\\naction: E\\x00ects observed within 2–4 weeks, with sustained response in long-term therapy.\\n8. Abbreviations\\nIBD – In\\x00ammatory Bowel Disease TNF-α – Tumor Necrosis Factor-alpha SC – Subcutaneous NF-κB –\\nNuclear Factor Kappa B MAPK – Mitogen-Activated Protein Kinase FcRn – Neonatal Fc Receptor CD –\\nCrohn’s Disease UC – Ulcerative Colitis\\nReferences\'), Document(id=\'a0d1d8f8-7a0b-45a5-9246-2ba8609ecfd7\', metadata={\'source\': \'../../../aiagents4pharma/talk2knowledgegraphs/tests/files/adalimumab.pdf\', \'page\': 1}, page_content=\'adalimumab.md 2025-02-13\\n / \\nhttps://pubmed.ncbi.nlm.nih.gov/24831559/ \\nhttps://www.cghjournal.org/article/S1542-3565%2813%2901050-1/fulltext \\nhttps://www.mdpi.com/2077-0383/12/22/7132\')], \'answer\': "Based on the subgraph extracted from `subkg_12345`, we can draw several insights related to the genes mentioned and their connection to Adalimumab, particularly in the context of inflammatory bowel diseases (IBD) such as Crohn\'s disease.\\n\\n1. **IFNG (Interferon Gamma)**:\\n - IFNG is a cytokine involved in immune responses and is associated with increased susceptibility to IBD. Since Adalimumab works by neutralizing TNF-α, which is a pro-inflammatory cytokine, it may indirectly influence the pathways involving IFNG. By reducing TNF-α levels, Adalimumab could potentially modulate the immune response mediated by IFNG, leading to decreased inflammation in IBD patients.\\n\\n2. **ATG16L1**:\\n - This gene is essential for autophagy and is linked to Crohn\'s Colitis. Given that Adalimumab is effective in treating Crohn\'s disease, the relationship between ATG16L1 and the disease suggests that the drug may help manage inflammation in patients with specific genetic predispositions. The autophagy process could be influenced by the reduction of inflammatory cytokines like TNF-α, potentially improving the overall disease outcome.\\n\\n3. **INAVA**:\\n - INAVA is involved in cytokine production and intracellular signaling, and it is associated with IBD. The action of Adalimumab in inhibiting TNF-α may also affect the signaling pathways that involve INAVA, leading to a reduction in the production of other pro-inflammatory cytokines. This could further contribute to the therapeutic effects of Adalimumab in IBD.\\n\\n4. **Inflammatory Bowel Disease (IBD)**:\\n - The subgraph highlights that IBD encompasses various conditions, including those caused by mutations in the NOD2 gene. Adalimumab\'s mechanism of action in targeting TNF-α is crucial for managing inflammation in these conditions. The interplay between genetic factors (like those involving IFNG, ATG16L1, and INAVA) and the therapeutic effects of Adalimumab underscores the importance of personalized medicine in treating IBD.\\n\\n5. **Crohn\'s Disease Forms**:\\n - The specific forms of Crohn\'s disease, such as Crohn Ileitis and Crohn\'s Colitis, are directly linked to the genes mentioned. The effectiveness of Adalimumab in treating these forms suggests that the drug\'s ability to reduce TNF-α levels can lead to significant improvements in symptoms and disease management for patients with these specific genetic backgrounds.\\n\\nIn summary, the genes IFNG, ATG16L1, and INAVA are integral to understanding the pathogenesis of IBD and Crohn\'s disease. Adalimumab\'s role in targeting TNF-α can modulate the inflammatory pathways associated with these genes, providing a therapeutic benefit in managing these complex conditions. This highlights the interconnectedness of genetic factors and therapeutic interventions in the treatment of inflammatory bowel diseases."}', tool_call_id='graphrag_reasoning_tool')]