Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Healthcare_with_Nutrition.ipynb #72

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
323 changes: 323 additions & 0 deletions all_agents_tutorials/Healthcare_with_Nutrition.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,323 @@

Building an Healthcare with Nutrition AI Agent with LngGraph
Overview
This tutorial demonstrates how to create an intelligent healthcare AI Agent by using LangGraph, a powerful tool for building complex language model workflows. The agent is designed to dignosis a disease from patient query and provide a nutrition guidance to patient according to disease when necessary.

Motivation
In today's world, where health concerns and lifestyle diseases are on the rise, personalized and accessible healthcare guidance is more critical than ever. Combining nutritional expertise with advanced AI capabilities can empower individuals to make informed decisions about their health. This project aims to demonstrate how cutting-edge language models and graph-based workflows can be leveraged to create an intelligent healthcare agent.

Key Components
State Management: Using TypedDict to define and manage the state of each customer interaction.
Patient Query: Captures the patient's query or concern, such as symptoms.
Disease Dignose:Processes the user-provided symptoms to identify potential diseases or conditions.
Nutritional Guidance : Provides dietary suggestions tailored to the user's health status and conditions.
Workflow Graph: Utilizing LangGraph to create a flexible and extensible workflow.
Method Details
Initialization: Set up the environment and import necessary libraries.
State Definition: Create a structure to hold query information from user.
Tools: Create tools for handle dignose disease and recommend food/nutrition.
Node Functions: Implement separate functions for patienbt query, dignose disease, nutrirional guidance and response generation.
Graph Construction: Use StateGraph to define the workflow, adding nodes and edges to represent the support process.
Workflow Compilation: Compile the graph into an executable application.
Execution: Process customer queries through the workflow and retrieve results.
Conclusion
This project highlights the potential of LangGraph in building sophisticated, AI-driven healthcare workflows. By integrating advanced natural language processing capabilities with a structured graph-based approach, we've developed a Healthcare with Nutrition Agent that provides personalized disease diagnosis and nutritional guidance. This agent not only empowers users with actionable health insights but also showcases the seamless integration of AI tools for meaningful problem-solving.

The approach demonstrated here has broad applications, showcasing how AI-powered workflows can address complex, multi-step challenges in healthcare and beyond, transforming how we interact with and manage our well-being.

import os
from dotenv import load_dotenv
from typing import TypedDict, List, Dict
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langgraph.graph import StateGraph, END, START
from langgraph.graph.state import CompiledStateGraph
from langgraph.checkpoint.memory import MemorySaver
from IPython.display import display, Image
from langchain_core.tools import Tool
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
model = ChatOpenAI(model="gpt-4o-mini")
langsmith_api_key = os.getenv("LANGCHAIN_API_KEY")
LANGCHAIN_TRACING_V2 = True
LANGCHAIN_PROJECT= 'project_chatbot'
class State(TypedDict):
"""
Represents the state for the healthcare support agent's responses.
"""
patient_query : str
disease_dignose : str
nutritional_guidance : str
def patient_data(state: State) -> State:
"""Collect patient data from the user."""
prompt = ChatPromptTemplate.from_template(
"You are a healthcare specialist. Collect the following data from the user: "
" symptoms or condition.\n"
"Patient Query: {patient_query}"
)
response = model.invoke(prompt.format_messages(patient_query=state["patient_query"]))
return {"patient_query": state["patient_query"], "disease_dignose": response.content}
def diagnose_disease(patient_data: str) -> dict:
"""Diagnose a disease based on user-provided data."""
prompt = ChatPromptTemplate.from_template(
"You are a medical diagnostic assistant. Based on the following symptoms or condition, "
"identify the most likely disease or condition. Provide a brief explanation "
"and suggest next steps for the user.\n\npatient_data: {patient_data}"
)
response = model.invoke(prompt.format_messages(patient_data=patient_data))
diagnosis_details = response.content.strip().split("\n", 1)
diagnosis = diagnosis_details[0] if diagnosis_details else "Unknown"
details = diagnosis_details[1] if len(diagnosis_details) > 1 else "No additional details provided."
return {"diagnosis": diagnosis, "details": details}

diagnose_tool = Tool.from_function(
func=diagnose_disease,
name="disease_diagnosis",
description="Diagnose a disease based on symptoms provided by the user.",
)
def recommend_food_general(condition: str) -> Dict[str, List[str]]:
"""Provide general food recommendations based on the condition."""
prompt = ChatPromptTemplate.from_template(
"You are a healthcare specialist. Based on the function diagnose_disease, "
"recommend 3-5 foods along with reasons why these foods are beneficial. "
"Condition: {condition}"
)
response = model.invoke(prompt.format_messages(condition=condition))
content = response.content
foods, reasons = [], []
for line in content.splitlines():
if ": " in line:
food, reason = line.split(": ", 1)
foods.append(food.strip())
reasons.append(reason.strip())
return {"foods": foods, "reasons": reasons}
food_recommendation_tool = Tool.from_function(
func=recommend_food_general,
name="food_recommendation",
description="Recommend foods based on the patient's condition or symptom.",
)
tools: List[Tool] = [diagnose_tool]
llm_with_tools = model.bind_tools(tools)
def diagnose(state: State) -> State:
"""Diagnose a disease based on patient symptoms."""
prompt = f"patient_data: {state['disease_dignose']}"
response = llm_with_tools.invoke(prompt)
return {
"patient_query": state["patient_query"],
"disease_dignose": response.content,
"nutritional_guidance": "",
}
tools: List[Tool] = [food_recommendation_tool]
llm_with_tool = model.bind_tools(tools)
def nutrition_guide(state: State) -> State:
"""Recommend nutrition based on dignose_disease."""
response = llm_with_tools.invoke(state["nutritional_guidance"])
return {
"patient_query": state["patient_query"],
"disease_dignose": state["disease_dignose"],
"nutritional_guidance": response.content,
}
memory : MemorySaver = MemorySaver()

builder : StateGraph = StateGraph(State)

builder.add_node("patient_data", patient_data)
builder.add_node("diagnose_disease", diagnose)
builder.add_node("nutrition_guidance", nutrition_guide)

builder.add_edge(START, "patient_data")
builder.add_edge("patient_data", "diagnose_disease")
builder.add_edge("diagnose_disease", "nutrition_guidance")
builder.add_edge("nutrition_guidance", END)

graph : CompiledStateGraph = builder.compile(checkpointer=memory)

display(Image(graph.get_graph().draw_mermaid_png()))

import pprint
config = {"configurable": {"thread_id": "1"}}
state_input = {
"patient_query": "my name is aamir, my cholesterol is high last few months, i feel pain in my joints.no symptoms of any disease, please provide me a full nutrirition guidance for less to my chlosterol level, i hane no medical history, no family medicl history, my age is 30 and my height is 6 ft",
"nutrition_guide" : "",
}
result = graph.invoke(state_input, config)

# Pretty print the result
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(result)
{ 'disease_dignose': "It looks like you've provided detailed nutritional "
'guidance and lifestyle modifications for managing high '
'cholesterol and joint pain. If you have specific '
'questions or need further assistance regarding this '
'information, please let me know!',
'nutritional_guidance': 'Hello! How can I assist you today? If you have '
'any questions or need help with something, feel '
'free to ask.',
'patient_query': 'my name is aamir, my cholesterol is high last few '
'months, i feel pain in my joints.no symptoms of any '
'disease, please provide me a full nutrirition guidance '
'for less to my chlosterol level, i hane no medical '
'history, no family medicl history, my age is 30 and my '
'height is 6 ft'}
config = {"configurable": {"thread_id": "1"}}
state_input = {
"patient_query": "there is no provided me any assistance for lowring my choestrol level?",
"nutrition_guide" : "provide me a complete nutrition guidance , i want to normalize cholesterol with natural foods.",
}


result = graph.invoke(state_input, config)

# Pretty print the result
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(result)
{ 'disease_dignose': 'To assist you effectively with lowering your '
'cholesterol levels, please provide the following '
'details:\n'
'\n'
'1. **Current Cholesterol Levels**: Have you had a '
'recent cholesterol test? If so, what were your total '
'cholesterol, LDL (bad cholesterol), HDL (good '
'cholesterol), and triglyceride levels?\n'
'\n'
'2. **Medical History**: Do you have any existing '
'medical conditions (e.g., diabetes, hypertension, '
'heart disease)?\n'
'\n'
'3. **Medications**: Are you currently taking any '
'medications, including over-the-counter supplements?\n'
'\n'
'4. **Diet**: What does your typical diet look like? Do '
'you consume a lot of saturated fats, trans fats, or '
'sugars?\n'
'\n'
'5. **Physical Activity**: How often do you exercise, '
'and what type of physical activity do you engage in?\n'
'\n'
'6. **Family History**: Is there a family history of '
'high cholesterol or heart disease?\n'
'\n'
'7. **Symptoms**: Are you experiencing any symptoms '
'such as chest pain, shortness of breath, or fatigue?\n'
'\n'
'Providing this information will help me offer more '
'tailored advice for managing your cholesterol levels.',
'nutritional_guidance': 'Hello! How can I assist you today?',
'patient_query': 'there is no provided me any assistance for lowring my '
'choestrol level?'}
config = {"configurable": {"thread_id": "1"}}
state_input = {
"patient_query": "there is no Symptoms of fatigue and chest pain, Cholesterol Levels is 7.2, no dietry restrictions, my ageis 30 and weight is 77kg, no medical history and no family cholesterol history",
"nutrition_guide" : "provide me a complete nutrition guidance , i want to normalize cholesterol with natural foods.",
}


result = graph.invoke(state_input, config)

# Pretty print the result
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(result)
{ 'disease_dignose': 'It looks like you have high cholesterol levels (7.2 '
'mmol/L), which is above the recommended threshold. '
'Here are some tailored recommendations based on your '
'profile:\n'
'\n'
'### Lifestyle Modifications:\n'
'1. **Diet**:\n'
' - Incorporate more fruits, vegetables, whole '
'grains, and lean proteins.\n'
' - Limit saturated fats (found in red meat and '
'full-fat dairy products) and trans fats (found in many '
'fried and processed foods).\n'
'\n'
'2. **Exercise**:\n'
' - Aim for at least 150 minutes of moderate aerobic '
'exercise (like brisk walking) or 75 minutes of '
'vigorous exercise (like running) each week.\n'
'\n'
'3. **Weight Management**:\n'
' - Maintaining a healthy weight is crucial. Consider '
'working with a healthcare professional to develop a '
'personalized weight management plan if needed.\n'
'\n'
'### Regular Monitoring:\n'
'- Schedule regular check-ups to monitor your '
'cholesterol levels and overall heart health.\n'
'\n'
'### Consult a Healthcare Professional:\n'
"- Given your elevated cholesterol level, it's "
'advisable to consult with a healthcare provider. They '
'can evaluate your situation further and discuss '
'medication options if necessary.\n'
'\n'
'Would you like me to help you with anything specific, '
'such as finding resources for diet plans or exercise '
'routines?',
'nutritional_guidance': 'Hello! How can I assist you today?',
'patient_query': 'there is no Symptoms of fatigue and chest pain, '
'Cholesterol Levels is 7.2, no dietry restrictions, my '
'ageis 30 and weight is 77kg, no medical history and no '
'family cholesterol history'}
config = {"configurable": {"thread_id": "1"}}
state_input = {
"patient_query": " Dietary recommendations for lowering cholesterol? and Exercise plans and activities to improve heart health?",
"nutritional_guidance" : "",
}


result = graph.invoke(state_input, config)

# Pretty print the result
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(result)
{ 'disease_dignose': 'To provide tailored dietary recommendations and '
'exercise plans for lowering cholesterol and improving '
'heart health, please answer the following questions:\n'
'\n'
'### Symptoms or Condition:\n'
'1. **Have you been diagnosed with high cholesterol or '
'any other heart-related conditions?**\n'
'2. **What are your current cholesterol levels (if '
'known)?** (e.g., total cholesterol, LDL, HDL, '
'triglycerides)\n'
'3. **Do you have any other health conditions (e.g., '
'diabetes, hypertension)?**\n'
'4. **Are you currently taking any medications related '
'to cholesterol or heart health?**\n'
'\n'
'### Dietary Preferences:\n'
'5. **What is your current diet like?** (e.g., '
'vegetarian, vegan, omnivorous, any specific '
'restrictions)\n'
'6. **Do you have any food allergies or '
'intolerances?**\n'
'7. **What types of foods do you enjoy eating?**\n'
'8. **How often do you eat out or consume processed '
'foods?**\n'
'\n'
'### Exercise Preferences:\n'
'9. **What is your current activity level?** (e.g., '
'sedentary, moderately active, very active)\n'
'10. **Do you have any physical limitations or '
'injuries?**\n'
'11. **What types of exercise do you enjoy or are you '
'willing to try?** (e.g., walking, running, swimming, '
'cycling, strength training, yoga)\n'
'12. **How many days per week are you able to dedicate '
'to exercise?**\n'
'\n'
'### Lifestyle Factors:\n'
'13. **What is your age, weight, and height?** (to '
'assess BMI)\n'
'14. **Do you smoke or consume alcohol?** If so, how '
'frequently?\n'
'15. **How would you rate your current stress level?** '
'(low, medium, high)\n'
'\n'
'Once you provide this information, I can offer more '
'specific dietary and exercise recommendations to help '
'lower your cholesterol and improve your heart health.',
'nutritional_guidance': 'Hello! How can I assist you today?',
'patient_query': ' Dietary recommendations for lowering cholesterol? and '
'Exercise plans and activities to improve heart health?'}