Skip to content

Commit

Permalink
Meidcal Insight Summary Added
Browse files Browse the repository at this point in the history
  • Loading branch information
sajedjalil committed Oct 1, 2024
1 parent 64f07b6 commit 8fad11c
Show file tree
Hide file tree
Showing 16 changed files with 1,502 additions and 554 deletions.
13 changes: 0 additions & 13 deletions Patient_Chat/urls.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
"""
URL configuration for Patient_Chat project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
Expand Down
3 changes: 3 additions & 0 deletions home/constants/chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@
# OpenAI Models
# model_gpt_3_5_turbo_0125 = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
# model_chatgpt_4o = ChatOpenAI(model="chatgpt-4o-latest", temperature=0)


predefined_medical_model = model_claude_3_haiku
25 changes: 16 additions & 9 deletions home/constants/constants.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
from langchain_core.prompts import PromptTemplate

summary_prompt = "Create a summary of the conversation above in less than 300 words: "
summary_prompt = "Create a summary of the conversation above. Try to summarize within 200 words: "
summarize_trigger_count = 4

prompt_text = '''You are a helpful AI medical assistant namely Patient Chat and are developed by a software engineer named Sajed.
You should only respond to health-related topics such as:
- General human health and lifestyle inquiries.
- Questions about men, women and children health
- Questions about the patient's medical condition, medication regimen, diet, etc.
- Various requests from the patient to their doctor such as make appointments, modify appointments and medication changes.
You should filter out and ignore any unrelated, overly sensitive, or controversial topics.'''
llm_prompt_text = '''You are a helpful AI medical assistant namely Patient Chat and are developed by a software
engineer named Sajed. You should only respond to health-related topics such as:
- General human health and lifestyle
inquiries.
- Questions about men, women and children health - Questions about the patient's medical condition,
medication regimen, diet, etc.
- Various requests from the patient to their doctor such as make appointments,
modify appointments and medication changes. You should filter out and ignore any unrelated, overly sensitive,
or controversial topics.'''

rag_prompt_text = '''You are a helpful AI medical assistant specialized in making medical insights. You also take
account patient name, date of birth, medical conditions and medications that are taken by a patient. You will build
your responses based on these information and other provided medical knowledge. Now use your medical expertise to
provide a comprehensive medical insight for the texts below:'''

history_one_turn = history = [
{
Expand Down Expand Up @@ -51,4 +57,5 @@
a Nobel Prize twice, and the only person to win a Nobel Prize in two scientific fields. Her husband, Pierre Curie,
was a co-winner of her first Nobel Prize, making them the first-ever married couple to win the Nobel Prize and
launching the Curie family legacy of five Nobel Prizes. She was, in 1906, the first woman to become a professor at
the University of Paris. She also won a US presidential award."""
the University of Paris. She also won a US presidential award."""

22 changes: 12 additions & 10 deletions home/llm/llm_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
from home.constants.chat_models import model_claude_3_haiku
from home.constants.constants import summary_prompt, summarize_trigger_count
from home.llm.function_tools.tools import Tools
from home.models.patient import Patient

tool_list = [
Tools.request_medication_change,
Tools.make_appointment,
Tools.request_appointment_change
]


class State(MessagesState):
Expand All @@ -17,17 +24,12 @@ class State(MessagesState):
class LLMGraph:
def __init__(self):
self.model = model_claude_3_haiku
self.tool_list = [
Tools.request_medication_change,
Tools.make_appointment,
Tools.request_appointment_change
]
self.model = self.model.bind_tools(self.tool_list)
self.model = self.model.bind_tools(tool_list)
memory = MemorySaver()
self.graph = self.build_graph().compile(checkpointer=memory)

def ai_agent(self, state: State):
sys_msg = SystemMessage(content=constants.prompt_text)
sys_msg = SystemMessage(content=constants.llm_prompt_text)
return {"messages": [self.model.invoke([sys_msg] + state["messages"])]}

def build_summarize_subgraph(self) -> StateGraph:
Expand All @@ -40,7 +42,7 @@ def build_summarize_subgraph(self) -> StateGraph:
def build_tool_call_subgraph(self) -> StateGraph:
builder = StateGraph(State)
builder.add_node("ai_agent", self.ai_agent)
builder.add_node("tools", ToolNode(self.tool_list))
builder.add_node("tools", ToolNode(tool_list))

builder.add_edge(START, "ai_agent")
builder.add_conditional_edges("ai_agent", tools_condition)
Expand All @@ -59,15 +61,15 @@ def build_graph(self) -> StateGraph:

return builder

def inference(self, user_message: str, history: List[dict], thread_id: str):
def chat_inference(self, user_message: str, history: List[dict], thread_id: str):
config = {"configurable": {"thread_id": thread_id}}
messages = self.convert_history_to_messages(history)
messages.append(HumanMessage(content=user_message))

result = self.graph.invoke({"messages": messages}, config)
assistant_response = result['messages'][-1].content

summary = self.graph.get_state(config).values.get("summary", "")
summary = self.graph.get_state(config).values.get("summary", None)
return assistant_response, summary

def summarize_conversation(self, state: State):
Expand Down
475 changes: 0 additions & 475 deletions home/llm/notebooks/agent.ipynb

This file was deleted.

755 changes: 755 additions & 0 deletions home/llm/notebooks/llm_agent.ipynb

Large diffs are not rendered by default.

59 changes: 33 additions & 26 deletions home/llm/notebooks/neo4j.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"metadata": {
"collapsed": true,
"ExecuteTime": {
"end_time": "2024-10-01T02:47:16.566973Z",
"start_time": "2024-10-01T02:47:16.563050Z"
"end_time": "2024-10-01T22:27:19.253371Z",
"start_time": "2024-10-01T22:27:19.248928Z"
}
},
"outputs": [],
Expand Down Expand Up @@ -45,8 +45,8 @@
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2024-10-01T02:47:17.879863Z",
"start_time": "2024-10-01T02:47:17.099496Z"
"end_time": "2024-10-01T22:27:23.401248Z",
"start_time": "2024-10-01T22:27:22.496708Z"
}
},
"id": "748847bca9e66706"
Expand All @@ -68,8 +68,8 @@
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2024-10-01T02:47:18.287052Z",
"start_time": "2024-10-01T02:47:17.881153Z"
"end_time": "2024-10-01T22:27:25.346671Z",
"start_time": "2024-10-01T22:27:24.954838Z"
}
},
"id": "99176a0f27f3ee88"
Expand All @@ -86,12 +86,13 @@
"\n",
"\u001B[1m> Entering new GraphCypherQAChain chain...\u001B[0m\n",
"Generated Cypher:\n",
"\u001B[32;1m\u001B[1;3m\u001B[0m\n",
"\u001B[32;1m\u001B[1;3mMATCH (p:Person {id: 'Marie Curie'})-[:WON]->(a:Award)\n",
"RETURN a.id\u001B[0m\n",
"Full Context:\n",
"\u001B[32;1m\u001B[1;3m[]\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m[{'a.id': 'Nobel Prize'}, {'a.id': 'Us Presidential Award'}]\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"{'query': 'What awards Marie Curie had?', 'result': \"I'm afraid I don't have any information about what awards Marie Curie had. The provided information is empty, so I don't have enough details to give a helpful answer.\"}\n"
"{'query': 'What awards Marie Curie had?', 'result': 'According to the provided information, Marie Curie had the following awards:\\n- Nobel Prize\\n- Us Presidential Award'}\n"
]
}
],
Expand All @@ -102,8 +103,8 @@
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2024-10-01T02:47:19.648836Z",
"start_time": "2024-10-01T02:47:18.704713Z"
"end_time": "2024-10-01T22:27:28.961497Z",
"start_time": "2024-10-01T22:27:27.550042Z"
}
},
"id": "b57b158d3a091e8a"
Expand All @@ -113,18 +114,23 @@
"execution_count": 5,
"outputs": [],
"source": [
"text = \"\"\" \n",
"Marie Curie, born in 1867, was a Polish and naturalised-French physicist and chemist who conducted pioneering research on radioactivity. \n",
"She was the first woman to win a Nobel Prize, the first person to win a Nobel Prize twice, and the only person to win a Nobel Prize in two scientific fields. \n",
"Her husband, Pierre Curie, was a co-winner of her first Nobel Prize, making them the first-ever married couple to win the Nobel Prize and launching the Curie family legacy of five Nobel Prizes. \n",
"She was, in 1906, the first woman to become a professor at the University of Paris. She also won presidential awards.\n",
"text = \"\"\"Medical information about Nicola Tesla:\n",
"Mental health: Tesla was known to have obsessive-compulsive tendencies. He was particular about cleanliness and had specific routines and habits.\n",
"Sleep patterns: Tesla reportedly slept very little, claiming to sleep only about two hours per night. However, he was said to occasionally nap during the day.\n",
"Diet: In his later years, Tesla became a vegetarian. He was very particular about his food and would often only eat honey, milk, and vegetables.\n",
"Celibacy: Tesla practiced lifelong celibacy, believing it helped him focus on his work.\n",
"Phobias: He had several phobias, including a fear of germs (mysophobia) and an aversion to pearls and earrings on women.\n",
"Physical health: Despite his eccentric habits, Tesla lived to be 86 years old, which was well above the average life expectancy for his time.\n",
"Possible neurological condition: Some modern researchers have speculated that Tesla may have had a neurological condition, possibly a high-functioning form of autism or Asperger's syndrome, based on his behaviors and work patterns.\n",
"Vision and auditory experiences: Tesla claimed to have vivid flashes of light accompanied by visions, particularly in his younger years. He also reported having acute hearing sensitivity.\n",
"Later life health issues: In his later years, Tesla was known to have become increasingly frail and had suffered at least one nervous breakdown.\n",
"\"\"\""
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2024-10-01T02:47:30.104156Z",
"start_time": "2024-10-01T02:47:30.074407Z"
"end_time": "2024-10-01T22:29:20.976298Z",
"start_time": "2024-10-01T22:29:20.972927Z"
}
},
"id": "31ebb9cc4bcfed79"
Expand All @@ -146,8 +152,8 @@
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2024-10-01T02:47:35.906964Z",
"start_time": "2024-10-01T02:47:32.560235Z"
"end_time": "2024-10-01T22:29:28.152030Z",
"start_time": "2024-10-01T22:29:22.129745Z"
}
},
"id": "cd9eb11f56c011c5"
Expand All @@ -164,13 +170,14 @@
"\n",
"\u001B[1m> Entering new GraphCypherQAChain chain...\u001B[0m\n",
"Generated Cypher:\n",
"\u001B[32;1m\u001B[1;3mMATCH (p:Person {id: 'Marie Curie'})-[:WON_AWARD]->(a:Award)\n",
"RETURN a.id\u001B[0m\n",
"\u001B[32;1m\u001B[1;3mMATCH (p:Person)-[:HAS]->(n:Neurological_condition), (p)-[:HAS]->(ph:Physical_health), (p)-[:HAS]->(ph2:Phobias), (p)-[:HAS]->(c:Celibacy), (p)-[:HAS]->(d:Diet), (p)-[:HAS]->(s:Sleep_patterns), (p)-[:HAS]->(m:Mental_health), (p)-[:HAS]->(h:Health_issues), (p)-[:HAS]->(se:Sensory_experiences)\n",
"WHERE p.id = 'Marie Curie'\n",
"RETURN p, n, ph, ph2, c, d, s, m, h, se\u001B[0m\n",
"Full Context:\n",
"\u001B[32;1m\u001B[1;3m[{'a.id': 'Nobel Prize'}, {'a.id': 'Presidential Awards'}]\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m[]\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n",
"{'query': 'What awards Marie Curie had?', 'result': 'According to the provided information, Marie Curie had the following awards:\\n- Nobel Prize\\n- Presidential Awards'}\n"
"{'query': 'What awards Marie Curie had?', 'result': \"I'm afraid I don't have any information about what awards Marie Curie had. The provided information is empty, so I don't have enough details to give a helpful answer.\"}\n"
]
}
],
Expand All @@ -181,8 +188,8 @@
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2024-10-01T02:47:39.309322Z",
"start_time": "2024-10-01T02:47:38.492755Z"
"end_time": "2024-10-01T22:29:30.934867Z",
"start_time": "2024-10-01T22:29:28.146693Z"
}
},
"id": "8a2d56a7313f79a4"
Expand Down
Loading

0 comments on commit 8fad11c

Please sign in to comment.