bnewcomer commited on
Commit
9fe9e1e
·
1 Parent(s): 0671cbd

Updates to app.py

Browse files
Files changed (1) hide show
  1. app.py +523 -581
app.py CHANGED
@@ -1,581 +1,523 @@
1
- # -------------------------------------------------------------------
2
- # 1. Import libraries
3
- # -------------------------------------------------------------------
4
- # For environment variable management
5
- from dotenv import load_dotenv
6
-
7
- # For data manipulation
8
- import os
9
- import re
10
- import json
11
- from typing import List, Dict, Any, Optional
12
- import pandas as pd
13
- import numpy as np
14
- from pydantic import BaseModel, Field
15
-
16
- # For LangChain agent and tools
17
- from langchain.tools import tool
18
- from langchain.chat_models import init_chat_model
19
- from langchain_core.documents import Document
20
- from langchain.agents import create_agent
21
- from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage, SystemMessage, FunctionMessage
22
-
23
- # Use OpenAI for embeddings and LLM
24
- from langchain_openai import OpenAIEmbeddings, ChatOpenAI
25
- # Use FAISS for vector store
26
- from langchain_community.vectorstores import FAISS
27
-
28
- # For loading CSV files
29
- import csv
30
-
31
- # For type hints
32
- from typing import List, Dict, Any, Tuple
33
-
34
- # For gradio UI
35
- import gradio as gr
36
-
37
- # Load environment variables from .env file
38
- load_dotenv()
39
- os.getenv("OPENAI_API_KEY")
40
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
41
-
42
- # Expect OPENAI_API_KEY to be set in HF Space secrets
43
- if not OPENAI_API_KEY:
44
- raise RuntimeError("OPENAI_API_KEY environment variable is not set.")
45
-
46
- # Constants and config
47
- ## Dataset folder
48
- DATA_DIR = "./data"
49
- ## FAISS vector store cache path
50
- FAISS_PATH = "./faiss_store"
51
-
52
- ## Dataset file paths
53
- DATASET_PATH = os.path.join(DATA_DIR, "dataset.csv")
54
- SYMPTOM_SEVERITY_PATH = os.path.join(DATA_DIR, "Symptom-severity.csv")
55
- SYMPTOM_DESC_PATH = os.path.join(DATA_DIR, "symptom_Description.csv")
56
- SYMPTOM_PREC_PATH = os.path.join(DATA_DIR, "symptom_precaution.csv")
57
-
58
- # -------------------------------------------------------------------
59
- # 2. Load data
60
- # -------------------------------------------------------------------
61
- # Load the disease and related symptom data
62
- dataset = pd.read_csv(DATASET_PATH)
63
- # Load the symptom severity data
64
- symptom_severity = pd.read_csv(SYMPTOM_SEVERITY_PATH)
65
- # Load the symptom description data
66
- symptom_desc = pd.read_csv(SYMPTOM_DESC_PATH)
67
- # Load the symptom precaution data
68
- symptom_prec = pd.read_csv(SYMPTOM_PREC_PATH)
69
-
70
- # Display part of the data
71
- dataset.head()
72
- dataset.info()
73
-
74
- """### Dataset insights
75
- - The dataset has 4,920 entries
76
- - The majority of diseases in the dataset have 3 or 4 symptoms, so the data is very sparse
77
- """
78
-
79
- # Display part of the symptom severity data
80
- symptom_severity.head()
81
- symptom_severity.info()
82
- print()
83
- print(f"Min weight: {symptom_severity['weight'].min()}")
84
- print()
85
- print(f"Max weight: {symptom_severity['weight'].max()}")
86
-
87
- """### Symptom severity insights
88
- - There are 133 symptoms and their associated severity values (numeric)
89
- - The severity values range from 1 to 7 (1 being low severity, 7 being high severity)
90
- """
91
-
92
- # Display part of the symptom description data
93
- symptom_desc.head()
94
- # Display part of the symptom precautions data
95
- symptom_prec.head()
96
-
97
- """# Data cleanup and standardization"""
98
-
99
- # Canonicalize the symptom data (clean it so it has consistent and compatible formatting)
100
- def canon_symptom(x: str) -> str:
101
- # Convert nulls to blanks ("")
102
- if pd.isna(x):
103
- return ""
104
- # Remove spaces and convert to lowercase
105
- x = str(x).strip().lower()
106
- # The symptoms may include underscores and some also have spaces (i.e. "_ "), so replace these with a single space
107
- x = re.sub(r"\s*_\s*", " ", x)
108
- # Replace multiple spaces with a single space
109
- x = re.sub(r" +", " ", x)
110
- return x
111
-
112
- # Generic text canonicalization (for disease names, descriptions, and precautions)
113
- def canon_text(x: str) -> str:
114
- # Convert nulls to blanks ("")
115
- if pd.isna(x):
116
- return ""
117
- # Strip spaces
118
- return str(x).strip()
119
-
120
- """## Format the disease and symptom data"""
121
-
122
- # Create a list of all symptom columns
123
- symp_cols = [c for c in dataset.columns if c.lower().startswith("symptom_")]
124
-
125
- # Convert the dataset to a long format with "Disease" and "symptom" columns
126
- long = (
127
- dataset.melt(id_vars=["Disease"], value_vars=symp_cols, value_name="symptom").drop(columns=["variable"])
128
- )
129
-
130
- # Clean up the disease column
131
- long["Disease"] = long["Disease"].map(canon_text)
132
- # Clean up the symptoms
133
- long["symptom"] = long["symptom"].map(canon_symptom)
134
- # Drop duplicate symptoms
135
- long = long[long["symptom"] != ""].drop_duplicates()
136
-
137
- # Create a dictionary of diseases (key) each with a set of symptoms (value)
138
- disease_to_symptoms = long.groupby("Disease")["symptom"].apply(set).to_dict()
139
-
140
- # Clean up the symptom values
141
- symptom_severity["Symptom"] = symptom_severity["Symptom"].map(canon_symptom)
142
- # Set the symptom weights - if the weight is null, set to 0
143
- symptom_severity["weight"] = pd.to_numeric(symptom_severity["weight"], errors="coerce").fillna(0).astype(int)
144
- # Convert to a dictionary of symptom (key) and weight (value) for lookups
145
- symptom_to_weight = dict(zip(symptom_severity["Symptom"], symptom_severity["weight"]))
146
-
147
- """## Join symptom description and precautions data"""
148
-
149
- # Clean the disease names and descriptions
150
- symptom_desc["Disease"] = symptom_desc["Disease"].map(canon_text)
151
- symptom_prec["Disease"] = symptom_prec["Disease"].map(canon_text)
152
- symptom_desc["Description"] = symptom_desc["Description"].map(canon_text)
153
-
154
- # Create a dictionary of disease names (key) and symptom descriptions (value)
155
- disease_to_desc = dict(zip(symptom_desc["Disease"], symptom_desc["Description"]))
156
- # Get a list of the precaution columns (excludes the "Disease" column)
157
- prec_cols = [c for c in symptom_prec.columns if c.lower().startswith("precaution_")]
158
-
159
- # Create a dictionary and map the precautions to the diseases
160
- disease_to_prec = {}
161
- for _, row in symptom_prec.iterrows():
162
- dis = row["Disease"]
163
- # Get a list of the precautions (not blank) for the current disease
164
- prec_list = [canon_text(row[c]) for c in prec_cols if canon_text(row[c])]
165
- disease_to_prec[dis] = prec_list
166
-
167
- # Get the top K candidate diagnoses (diseases) for given symptoms
168
- # This function gives highly explainable results for diagnoses
169
- def disease_candidates(user_symptoms: list[str], top_k: int = 5):
170
- # Clean the symptom list
171
- clean_symp = {canon_symptom(s) for s in user_symptoms}
172
- # Only keep the non-blank symptoms
173
- clean_symp = {s for s in clean_symp if s}
174
- # If the symptom list is empty, return an empty list
175
- if not clean_symp:
176
- return []
177
-
178
- # The denominator should be the sum of symptom weights (if the symptom is not in the dictionary, then just use 1 for the weight)
179
- denominator = sum(symptom_to_weight.get(s, 0) for s in clean_symp) or 1
180
-
181
- candidate_list = []
182
-
183
- for disease, symp in disease_to_symptoms.items():
184
- # Find the intersection of user symptoms w/symptoms for the current disease
185
- inter = clean_symp.intersection(symp)
186
- # If we didn't find matching symptoms, this is not a good candidate
187
- if not inter:
188
- continue
189
- # The numerator should be the sum of symptom weights for matching symptoms
190
- numerator = sum(symptom_to_weight.get(s, 0) for s in inter)
191
- candidate_score = numerator / denominator
192
- # Add the candidate disease, score, and sorted maching symptom list
193
- candidate_list.append((disease, candidate_score, sorted(inter)))
194
-
195
- # Sort the list in descending order (highest scored first)
196
- candidate_list.sort(key=lambda x: x[1], reverse=True)
197
- # Return the top K candidates by score
198
- return candidate_list[:top_k]
199
-
200
- # Get a report of severity based on symptoms
201
- def severity_report(user_symptoms: list[str]):
202
- # Clean the symptoms and only keep non-blank symptoms
203
- clean_symp = [canon_symptom(s) for s in user_symptoms]
204
- clean_symp = [s for s in clean_symp if s]
205
-
206
- # Get weights per symptom
207
- weight_per_symp = [(s, symptom_to_weight.get(s, 0)) for s in clean_symp]
208
- # Get the total weight for all symptoms
209
- total = sum(w for _, w in weight_per_symp)
210
-
211
- # Give severity levels based on total symptom weight
212
- if total <= 5:
213
- level = "mild"
214
- elif total <= 12:
215
- level = "moderate"
216
- else:
217
- level = "high"
218
-
219
- # Track the symptoms that were not found in the severity table (i.e. have no weight)
220
- no_severity = [s for s in clean_symp if s not in symptom_to_weight]
221
-
222
- return {
223
- "Total": total,
224
- "Level": level,
225
- "Per symptom": weight_per_symp,
226
- "Symptoms not in severity table": no_severity
227
- }
228
-
229
- # Check data quality
230
- all_symptoms = set().union(*disease_to_symptoms.values())
231
- # Get all symptoms w/out a severity weight
232
- missing_severity = sorted([s for s in all_symptoms if s not in symptom_to_weight])
233
-
234
- all_diseases = set(disease_to_symptoms.keys())
235
- # Get diseases missing a description
236
- missing_desc = sorted([d for d in all_diseases if d not in disease_to_desc])
237
- # Get diseases missing precautions
238
- missing_prec = sorted([d for d in all_diseases if d not in disease_to_prec])
239
-
240
- print(f"Symptom count: {len(all_symptoms)}")
241
- print(f"Symptoms missing severity: {missing_severity}")
242
- print(f"Diseases missing description: {missing_desc}")
243
- print(f"Diseases missing precautions: {missing_prec}")
244
-
245
- # Create disease documents
246
- def disease_doc(disease: str) -> str:
247
- # Get the symptoms for this disease (from the dataset)
248
- symptoms = sorted(disease_to_symptoms.get(disease, set()))
249
- # Get the description for this disease (from the dataset)
250
- description = disease_to_desc.get(disease, "")
251
- # Get the precaustions for this disease (from the dataset)
252
- precautions = disease_to_prec.get(disease, [])
253
-
254
- return "\n".join([
255
- f"Disease: {disease}",
256
- f"Description: {description}",
257
- "Symptoms: " + ", ".join(symptoms),
258
- "Precautions: " + ", ".join(precautions) if precautions else "Precautions: (none listed)"
259
- ])
260
-
261
- docs: List[Document] = []
262
- for d in sorted(disease_to_symptoms.keys()):
263
- docs.append(
264
- Document(
265
- page_content = disease_doc(d),
266
- metadata={"disease": d}
267
- )
268
- )
269
-
270
- # Created embeddings of the disease docs and store in a vector store
271
- embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
272
- # If we don't have embeddings in cache, create them
273
- def load_or_create_faiss(docs, faiss_path="faiss_store"):
274
- """ Load FAISS index if it exists, otherwise create it from docs and save it. """
275
- index_file = os.path.join(faiss_path, "index.faiss")
276
- store_file = os.path.join(faiss_path, "index.pkl")
277
- # If FAISS cache exists, load it
278
- if os.path.exists(index_file) and os.path.exists(store_file):
279
- print("Loading FAISS index from cache...")
280
- return FAISS.load_local(faiss_path, embeddings, allow_dangerous_deserialization=True)
281
- # Otherwise create a new FAISS index
282
- print("⚙️ Building new FAISS index...")
283
- vectorstore = FAISS.from_documents(docs, embeddings)
284
- # Ensure directory exists
285
- os.makedirs(faiss_path, exist_ok=True)
286
- # Save to disk
287
- vectorstore.save_local(faiss_path)
288
- print("💾 Saved FAISS index to disk.")
289
- return vectorstore
290
-
291
- # Create or load the FAISS vector store for the disease documents
292
- vector_store = load_or_create_faiss(docs, faiss_path="faiss_store")
293
-
294
- # Define schemas to use for the tools
295
-
296
- # Define the input schema for each tool using Pydantic BaseModel
297
- class DiagnoseInput(BaseModel):
298
- # List of symptoms
299
- symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
300
- # Top K candidates to return (default to 5, but should be between 1 and 10)
301
- top_k: int = Field(5, ge=1, le=10, description="Number of candidate diseases to return")
302
-
303
- class SeverityInput(BaseModel):
304
- # List of symptoms
305
- symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
306
-
307
- class DiseaseInfoInput(BaseModel):
308
- # Disease name
309
- disease: str = Field(..., description="Disease name (must match name in dataset)")
310
-
311
- class RetrieveDocsInput(BaseModel):
312
- # Search query
313
- query: str = Field(..., description="A search query (i.e. symptoms list or disease name)")
314
- # Top K docs to retrieve (default to 3, but should be between 1 and 10)
315
- k: int = Field(3, ge=1, le=10, description="How many disease docs to retrieve")
316
-
317
- # Tools (using RAG, so they are deterministic)
318
-
319
- # Create a diagnosic tool, using our schema
320
- @tool(args_schema=DiagnoseInput)
321
- def diagnose_diseases(symptoms: List[str], top_k: int=5) -> str:
322
- """
323
- Suggest likely diseases based on matching symptoms (using severity weights) from the dataset.
324
- Returns a JSON string of ranked candidates.
325
- """
326
- # Get the top K disease diagnoses
327
- results = disease_candidates(symptoms, top_k=top_k)
328
- # Return a JSON formatted string from the list
329
- return json.dumps({"candidates": results}, indent=2)
330
-
331
- # Create a symptom severity calculation tool, using our schema
332
- @tool(args_schema=SeverityInput)
333
- def calc_symptom_severity(symptoms: List[str]) -> str:
334
- """
335
- Calculate a symptom severity score using weights from the Symptom-severity.csv dataset.
336
- Returns a JSON string with the total score, severity level, and weights per symptom.
337
- """
338
- # Get the symptoms severity summary
339
- report = severity_report(symptoms)
340
- # Return a JSON formatted string
341
- return json.dumps(report, indent=2)
342
-
343
- # Create a tool to get disease description, using our schema
344
- @tool(args_schema=DiseaseInfoInput)
345
- def get_disease_description(disease: str) -> str:
346
- """
347
- Get the description for a disease (from the symptom_Description.csv dataset)
348
- """
349
- # Clean the disease name
350
- disease = canon_text(disease)
351
- # Lookup the disease description and return
352
- return disease_to_desc.get(disease, "")
353
-
354
- # Create a tool to get disease precaution advice, using our schema
355
- @tool(args_schema=DiseaseInfoInput)
356
- def get_precaution_advice(disease: str) -> str:
357
- """
358
- Get precaution steps for a disease (from the symptom_precaution.csv dataset)
359
- """
360
- # Clean the disease name
361
- disease = canon_text(disease)
362
- # Lookup the disease precautions and return
363
- return json.dumps(disease_to_prec.get(disease, []), indent=2)
364
-
365
- # Create a tool to retrieve disease documents from the vector store, using our schema
366
- @tool(args_schema=RetrieveDocsInput)
367
- def retrieve_disease_docs(query: str, k: int = 3):
368
- """
369
- Retrieve disease documents from the vector store for "ground truth" and explanations.
370
- Returns (serialized_text, retrieved_documents).)
371
- """
372
- # Get K similar docs from the vector store, based on the query
373
- retrieved = vector_store.similarity_search(query, k=k)
374
- # Get a serialized string of the top K matching disease docs
375
- serialized = "\n\n".join(
376
- f"Source: {doc.metadata}\nContent\n{doc.page_content}"
377
- for doc in retrieved
378
- )
379
- return serialized, retrieved
380
-
381
- tools = [
382
- diagnose_diseases,
383
- calc_symptom_severity,
384
- get_disease_description,
385
- get_precaution_advice,
386
- retrieve_disease_docs,
387
- ]
388
-
389
- # LLM + orchestrator agent
390
-
391
- # Use a deterministic model since we are using tools for diagnosis and severity calculation and use the mini model for faster responses
392
- model = init_chat_model(
393
- "gpt-4.1-mini",
394
- temperature=0,
395
- model_provider="openai",
396
- api_key=OPENAI_API_KEY,
397
- )
398
- system_prompt = """
399
- You are a medical decision support assistant, not to be used as a replacement for professional medical care.
400
- In your responses, always:
401
- - Use tools to identify diagnosis candidates and symptom severity
402
- - Provider a disclaimer that the user should consult with a doctor
403
- - Give precaution advice and recommend professional medical care when appropriate (i.e. moderate to severe symptoms)
404
- - If symptoms suggests a serious emergency risk (e.g. chest pain, difficulty breathing, serious bleeding), then recommend urgent care or emergency room services
405
-
406
- Workflow to follow:
407
- 1) Ask for symptoms if not provided by user
408
- 2) Call calc_symptom_severity(symptoms)
409
- 3) Call diagnose_diseases(symptoms, top_k=5)
410
- 4) For the top 1-3 diseases, call retreive_disease_docs using the disease name or symptoms.
411
- 5) Return: top candidates also with why (matched symptoms), severity level, description + precautions for the top candidate(s), and provide follow-up questions to refine.
412
-
413
- Responses should always be concise.
414
- """.strip()
415
-
416
- agent = create_agent(model, tools, system_prompt=system_prompt)
417
-
418
- # Multi-turn chat
419
- def chat_once(messages: List[Dict[str, str]]) -> List[Dict[str, str]]:
420
- """
421
- messages: [{"role": "user"|"assistant", "content": "..."}]
422
- Returns updated messages with the agent's final response added to the end.
423
- """
424
-
425
- final_state = None
426
- # Stream the agent's "thought" process, one step at a time - uses the "OPENAI_API_KEY" environment variable to get the API key
427
- for step in agent.stream({"messages": messages}, stream_mode="values"):
428
- print(f"Current step: {step}")
429
- final_state = step
430
-
431
- # Get the role and content from the final state of the agent
432
- new_messages = final_state["messages"]
433
- # Parse out the role and content
434
- out = []
435
- for m in new_messages:
436
- # Get the type (if available) or the role/assistant
437
- role = getattr(m, "type", None) or getattr(m, "role", "assistant")
438
- # Get the content if available (otherwise use "")
439
- content = getattr(m, "content", "")
440
- # Add to the list
441
- out.append({"role": role, "content": content})
442
- return out
443
-
444
- # Redefine chat_once to correctly handle messages in multi-turn conversations
445
- def chat_once(messages: List[BaseMessage]) -> List[BaseMessage]:
446
- """
447
- messages: List of BaseMessage objects for the conversation history.
448
- Returns updated list of BaseMessage objects with the agent's final response added.
449
- """
450
- final_state = None
451
- for step in agent.stream({"messages": messages}, stream_mode="values"):
452
- print(f"Current step: {step}")
453
- final_state = step
454
-
455
- # Return the actual BaseMessage objects from the final state
456
- return final_state["messages"]
457
-
458
- # For the Gradio UI, we want to run the agent and get the updated LangChain message history, so we can extract the assistant's final response and also maintain the full conversation state (including tool calls) in the UI.
459
- def run_agent_once(lc_history: List[BaseMessage]) -> List[BaseMessage]:
460
- """
461
- Runs the agent on the current conversation and returns the updated LangChain message history.
462
- """
463
- final_state = None
464
- for step in agent.stream({"messages": lc_history}, stream_mode="values"):
465
- final_state = step
466
- return final_state["messages"]
467
-
468
- # Helper function to extract the last assistant response content from the LangChain message history
469
- def get_last_ai_content(lc_history: List[BaseMessage]) -> str:
470
- """
471
- Extract the last assistant response content from the LangChain message history.
472
- """
473
- for m in reversed(lc_history):
474
- if isinstance(m, AIMessage):
475
- return (m.content or "").strip()
476
- return ""
477
-
478
- # Gradio UI handlers
479
- def submit_chat(user_text: str, chat_history: List[dict], lc_state: Optional[List[BaseMessage]]):
480
- """
481
- Gradio handler:
482
- - user_text: current textbox input
483
- - chat_history: list of {"role": "...", "content": "..."} used by gr.Chatbot(type="messages")
484
- - lc_state: LangChain BaseMessage history stored in gr.State
485
-
486
- Returns:
487
- - updated chat_history (for UI)
488
- - cleared textbox
489
- - updated lc_state
490
- """
491
- user_text = (user_text or "").strip()
492
- if not user_text:
493
- return chat_history, "", lc_state
494
-
495
- if lc_state is None:
496
- lc_state = []
497
-
498
- # 1) Add user message to LangChain state
499
- lc_state.append(HumanMessage(content=user_text))
500
-
501
- # 2) Run agent, get updated LangChain history (includes tool calls, etc.)
502
- lc_state = run_agent_once(lc_state)
503
-
504
- # 3) Extract the assistant’s final natural-language response
505
- assistant_text = get_last_ai_content(lc_state)
506
- if not assistant_text:
507
- assistant_text = "I couldn't generate a response. Please try rephrasing your symptoms."
508
-
509
- # 4) Update the Gradio chat history (messages format)
510
- chat_history = chat_history + [
511
- {"role": "user", "content": user_text},
512
- {"role": "assistant", "content": assistant_text},
513
- ]
514
-
515
- return chat_history, "", lc_state
516
-
517
- # Handler to reset the chat - clears the Gradio chat history and the LangChain state
518
- def reset_chat():
519
- return [], [], # chat_history, lc_state
520
-
521
- # Build the Gradio UI
522
- with gr.Blocks(title="MediBot – Disease & Symptom Assistant") as demo:
523
- gr.Markdown(
524
- """
525
- # MediBot (RAG + Tools)
526
- Enter your symptoms in plain language (comma-separated is fine).
527
- **Note:** This is not medical advice—consult a clinician for diagnosis and treatment.
528
- """.strip()
529
- )
530
-
531
- chatbot = gr.Chatbot(height=420) #type="messages", height=420)
532
- lc_state = gr.State([])
533
-
534
- # User input row
535
- with gr.Row():
536
- user_box = gr.Textbox(
537
- label="Your message",
538
- placeholder="e.g., fever, headache, chills, fatigue",
539
- scale=8,
540
- )
541
- send_btn = gr.Button("Send", scale=2)
542
-
543
- with gr.Row():
544
- examples = gr.Examples(
545
- examples=[
546
- ["I have fever, headache, chills, and fatigue. What could it be?"],
547
- ["I also have nausea and joint pain."],
548
- ["Sore throat, runny nose, mild cough for 2 days."],
549
- ["Chest pain and shortness of breath."],
550
- ],
551
- inputs=user_box,
552
- label="Examples",
553
- )
554
-
555
- clear_btn = gr.Button("Clear chat")
556
-
557
- # Wire events
558
-
559
- # When the send button is clicked, run the submit_chat function with the current user input, chat history, and LangChain state, and update the chatbot and clear the user input box
560
- send_btn.click(
561
- fn=submit_chat,
562
- inputs=[user_box, chatbot, lc_state],
563
- outputs=[chatbot, user_box, lc_state],
564
- )
565
-
566
- # Allow pressing Enter in the textbox to submit the chat as well
567
- user_box.submit(
568
- fn=submit_chat,
569
- inputs=[user_box, chatbot, lc_state],
570
- outputs=[chatbot, user_box, lc_state],
571
- )
572
-
573
- # Clear button resets both the Gradio chat history and the LangChain state
574
- clear_btn.click(
575
- fn=lambda: ([], [], []),
576
- inputs=[],
577
- outputs=[chatbot, user_box, lc_state],
578
- )
579
-
580
- # Launch the UI
581
- demo.launch(share=True)
 
1
+ # -------------------------------------------------------------------
2
+ # 1. Import libraries
3
+ # -------------------------------------------------------------------
4
+ # For environment variable management
5
+ from dotenv import load_dotenv
6
+
7
+ # For data manipulation
8
+ import os
9
+ import re
10
+ import json
11
+ from typing import List, Dict, Any, Optional, Tuple
12
+ import pandas as pd
13
+ from pydantic import BaseModel, Field
14
+
15
+ # For LangChain agent and tools
16
+ from langchain.tools import tool
17
+ from langchain.chat_models import init_chat_model
18
+ from langchain_core.documents import Document
19
+ from langchain.agents import create_agent
20
+ from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage, SystemMessage, FunctionMessage
21
+
22
+ # Use OpenAI for embeddings and LLM
23
+ from langchain_openai import OpenAIEmbeddings
24
+ # Use FAISS for vector store
25
+ from langchain_community.vectorstores import FAISS
26
+
27
+ # For filepaths
28
+ from pathlib import Path
29
+
30
+ # For gradio UI
31
+ import gradio as gr
32
+
33
+ # Load environment variables from .env file
34
+ load_dotenv()
35
+ os.getenv("OPENAI_API_KEY")
36
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
37
+
38
+ # Expect OPENAI_API_KEY to be set in HF Space secrets
39
+ if not OPENAI_API_KEY:
40
+ raise RuntimeError("OPENAI_API_KEY environment variable is not set.")
41
+
42
+ # Constants and config
43
+ ## Dataset folder
44
+ BASE_DIR = Path(__file__).resolve().parent
45
+ DATA_DIR = BASE_DIR / "data"
46
+ FAISS_PATH = BASE_DIR / "faiss_store"
47
+
48
+ ## Dataset file paths
49
+ DATASET_PATH = DATA_DIR / "dataset.csv"
50
+ SYMPTOM_SEVERITY_PATH = DATA_DIR / "Symptom-severity.csv"
51
+ SYMPTOM_DESC_PATH = DATA_DIR / "symptom_Description.csv"
52
+ SYMPTOM_PREC_PATH = DATA_DIR / "symptom_precaution.csv"
53
+
54
+ for path in [DATASET_PATH, SYMPTOM_SEVERITY_PATH, SYMPTOM_DESC_PATH, SYMPTOM_PREC_PATH]:
55
+ if not path.exists():
56
+ raise FileNotFoundError(f"Missing required data file: {path}")
57
+
58
+ # -------------------------------------------------------------------
59
+ # 2. Load data
60
+ # -------------------------------------------------------------------
61
+ # Load the disease and related symptom data
62
+ dataset = pd.read_csv(DATASET_PATH)
63
+ # Load the symptom severity data
64
+ symptom_severity = pd.read_csv(SYMPTOM_SEVERITY_PATH)
65
+ # Load the symptom description data
66
+ symptom_desc = pd.read_csv(SYMPTOM_DESC_PATH)
67
+ # Load the symptom precaution data
68
+ symptom_prec = pd.read_csv(SYMPTOM_PREC_PATH)
69
+
70
+ """# Data cleanup and standardization"""
71
+
72
+ # Canonicalize the symptom data (clean it so it has consistent and compatible formatting)
73
+ def canon_symptom(x: str) -> str:
74
+ # Convert nulls to blanks ("")
75
+ if pd.isna(x):
76
+ return ""
77
+ # Remove spaces and convert to lowercase
78
+ x = str(x).strip().lower()
79
+ # The symptoms may include underscores and some also have spaces (i.e. "_ "), so replace these with a single space
80
+ x = re.sub(r"\s*_\s*", " ", x)
81
+ # Replace multiple spaces with a single space
82
+ x = re.sub(r" +", " ", x)
83
+ return x
84
+
85
+ # Generic text canonicalization (for disease names, descriptions, and precautions)
86
+ def canon_text(x: str) -> str:
87
+ # Convert nulls to blanks ("")
88
+ if pd.isna(x):
89
+ return ""
90
+ # Strip spaces
91
+ return str(x).strip()
92
+
93
+ """## Format the disease and symptom data"""
94
+
95
+ # Create a list of all symptom columns
96
+ symp_cols = [c for c in dataset.columns if c.lower().startswith("symptom_")]
97
+
98
+ # Convert the dataset to a long format with "Disease" and "symptom" columns
99
+ long = (
100
+ dataset.melt(id_vars=["Disease"], value_vars=symp_cols, value_name="symptom").drop(columns=["variable"])
101
+ )
102
+
103
+ # Clean up the disease column
104
+ long["Disease"] = long["Disease"].map(canon_text)
105
+ # Clean up the symptoms
106
+ long["symptom"] = long["symptom"].map(canon_symptom)
107
+ # Drop duplicate symptoms
108
+ long = long[long["symptom"] != ""].drop_duplicates()
109
+
110
+ # Create a dictionary of diseases (key) each with a set of symptoms (value)
111
+ disease_to_symptoms = long.groupby("Disease")["symptom"].apply(set).to_dict()
112
+
113
+ # Clean up the symptom values
114
+ symptom_severity["Symptom"] = symptom_severity["Symptom"].map(canon_symptom)
115
+ # Set the symptom weights - if the weight is null, set to 0
116
+ symptom_severity["weight"] = pd.to_numeric(symptom_severity["weight"], errors="coerce").fillna(0).astype(int)
117
+ # Convert to a dictionary of symptom (key) and weight (value) for lookups
118
+ symptom_to_weight = dict(zip(symptom_severity["Symptom"], symptom_severity["weight"]))
119
+
120
+ """## Join symptom description and precautions data"""
121
+
122
+ # Clean the disease names and descriptions
123
+ symptom_desc["Disease"] = symptom_desc["Disease"].map(canon_text)
124
+ symptom_prec["Disease"] = symptom_prec["Disease"].map(canon_text)
125
+ symptom_desc["Description"] = symptom_desc["Description"].map(canon_text)
126
+
127
+ # Create a dictionary of disease names (key) and symptom descriptions (value)
128
+ disease_to_desc = dict(zip(symptom_desc["Disease"], symptom_desc["Description"]))
129
+ # Get a list of the precaution columns (excludes the "Disease" column)
130
+ prec_cols = [c for c in symptom_prec.columns if c.lower().startswith("precaution_")]
131
+
132
+ # Create a dictionary and map the precautions to the diseases
133
+ disease_to_prec = {}
134
+ for _, row in symptom_prec.iterrows():
135
+ dis = row["Disease"]
136
+ # Get a list of the precautions (not blank) for the current disease
137
+ prec_list = [canon_text(row[c]) for c in prec_cols if canon_text(row[c])]
138
+ disease_to_prec[dis] = prec_list
139
+
140
+ # Get the top K candidate diagnoses (diseases) for given symptoms
141
+ # This function gives highly explainable results for diagnoses
142
+ def disease_candidates(user_symptoms: list[str], top_k: int = 5):
143
+ # Clean the symptom list
144
+ clean_symp = {canon_symptom(s) for s in user_symptoms}
145
+ # Only keep the non-blank symptoms
146
+ clean_symp = {s for s in clean_symp if s}
147
+ # If the symptom list is empty, return an empty list
148
+ if not clean_symp:
149
+ return []
150
+
151
+ # The denominator should be the sum of symptom weights (if the symptom is not in the dictionary, then just use 1 for the weight)
152
+ denominator = sum(symptom_to_weight.get(s, 0) for s in clean_symp) or 1
153
+
154
+ candidate_list = []
155
+
156
+ for disease, symp in disease_to_symptoms.items():
157
+ # Find the intersection of user symptoms w/symptoms for the current disease
158
+ inter = clean_symp.intersection(symp)
159
+ # If we didn't find matching symptoms, this is not a good candidate
160
+ if not inter:
161
+ continue
162
+ # The numerator should be the sum of symptom weights for matching symptoms
163
+ numerator = sum(symptom_to_weight.get(s, 0) for s in inter)
164
+ candidate_score = numerator / denominator
165
+ # Add the candidate disease, score, and sorted maching symptom list
166
+ candidate_list.append((disease, candidate_score, sorted(inter)))
167
+
168
+ # Sort the list in descending order (highest scored first)
169
+ candidate_list.sort(key=lambda x: x[1], reverse=True)
170
+ # Return the top K candidates by score
171
+ return candidate_list[:top_k]
172
+
173
+ # Get a report of severity based on symptoms
174
+ def severity_report(user_symptoms: list[str]):
175
+ # Clean the symptoms and only keep non-blank symptoms
176
+ clean_symp = [canon_symptom(s) for s in user_symptoms]
177
+ clean_symp = [s for s in clean_symp if s]
178
+
179
+ # Get weights per symptom
180
+ weight_per_symp = [(s, symptom_to_weight.get(s, 0)) for s in clean_symp]
181
+ # Get the total weight for all symptoms
182
+ total = sum(w for _, w in weight_per_symp)
183
+
184
+ # Give severity levels based on total symptom weight
185
+ if total <= 5:
186
+ level = "mild"
187
+ elif total <= 12:
188
+ level = "moderate"
189
+ else:
190
+ level = "high"
191
+
192
+ # Track the symptoms that were not found in the severity table (i.e. have no weight)
193
+ no_severity = [s for s in clean_symp if s not in symptom_to_weight]
194
+
195
+ return {
196
+ "Total": total,
197
+ "Level": level,
198
+ "Per symptom": weight_per_symp,
199
+ "Symptoms not in severity table": no_severity
200
+ }
201
+
202
+ # Check data quality
203
+ all_symptoms = set().union(*disease_to_symptoms.values())
204
+ # Get all symptoms w/out a severity weight
205
+ missing_severity = sorted([s for s in all_symptoms if s not in symptom_to_weight])
206
+
207
+ all_diseases = set(disease_to_symptoms.keys())
208
+ # Get diseases missing a description
209
+ missing_desc = sorted([d for d in all_diseases if d not in disease_to_desc])
210
+ # Get diseases missing precautions
211
+ missing_prec = sorted([d for d in all_diseases if d not in disease_to_prec])
212
+
213
+ # Create disease documents
214
+ def disease_doc(disease: str) -> str:
215
+ # Get the symptoms for this disease (from the dataset)
216
+ symptoms = sorted(disease_to_symptoms.get(disease, set()))
217
+ # Get the description for this disease (from the dataset)
218
+ description = disease_to_desc.get(disease, "")
219
+ # Get the precaustions for this disease (from the dataset)
220
+ precautions = disease_to_prec.get(disease, [])
221
+
222
+ return "\n".join([
223
+ f"Disease: {disease}",
224
+ f"Description: {description}",
225
+ "Symptoms: " + ", ".join(symptoms),
226
+ "Precautions: " + ", ".join(precautions) if precautions else "Precautions: (none listed)"
227
+ ])
228
+
229
+ docs: List[Document] = []
230
+ for d in sorted(disease_to_symptoms.keys()):
231
+ docs.append(
232
+ Document(
233
+ page_content = disease_doc(d),
234
+ metadata={"disease": d}
235
+ )
236
+ )
237
+
238
+ # Created embeddings of the disease docs and store in a vector store
239
+ embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
240
+ # If we don't have embeddings in cache, create them
241
+ def load_or_create_faiss(docs, faiss_path=FAISS_PATH):
242
+ """ Load FAISS index if it exists, otherwise create it from docs and save it. """
243
+ index_file = os.path.join(faiss_path, "index.faiss")
244
+ store_file = os.path.join(faiss_path, "index.pkl")
245
+ # If FAISS cache exists, load it
246
+ if os.path.exists(index_file) and os.path.exists(store_file):
247
+ print("Loading FAISS index from cache...")
248
+ return FAISS.load_local(faiss_path, embeddings, allow_dangerous_deserialization=True)
249
+ # Otherwise create a new FAISS index
250
+ print("⚙️ Building new FAISS index...")
251
+ vectorstore = FAISS.from_documents(docs, embeddings)
252
+ # Ensure directory exists
253
+ os.makedirs(faiss_path, exist_ok=True)
254
+ # Save to disk
255
+ vectorstore.save_local(faiss_path)
256
+ print("💾 Saved FAISS index to disk.")
257
+ return vectorstore
258
+
259
+ # Create or load the FAISS vector store for the disease documents
260
+ vector_store = load_or_create_faiss(docs, faiss_path=FAISS_PATH)
261
+
262
+ # Define schemas to use for the tools
263
+
264
+ # Define the input schema for each tool using Pydantic BaseModel
265
+ class DiagnoseInput(BaseModel):
266
+ # List of symptoms
267
+ symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
268
+ # Top K candidates to return (default to 5, but should be between 1 and 10)
269
+ top_k: int = Field(5, ge=1, le=10, description="Number of candidate diseases to return")
270
+
271
+ class SeverityInput(BaseModel):
272
+ # List of symptoms
273
+ symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
274
+
275
+ class DiseaseInfoInput(BaseModel):
276
+ # Disease name
277
+ disease: str = Field(..., description="Disease name (must match name in dataset)")
278
+
279
+ class RetrieveDocsInput(BaseModel):
280
+ # Search query
281
+ query: str = Field(..., description="A search query (i.e. symptoms list or disease name)")
282
+ # Top K docs to retrieve (default to 3, but should be between 1 and 10)
283
+ k: int = Field(3, ge=1, le=10, description="How many disease docs to retrieve")
284
+
285
+ # Tools (using RAG, so they are deterministic)
286
+
287
+ # Create a diagnosic tool, using our schema
288
+ @tool(args_schema=DiagnoseInput)
289
+ def diagnose_diseases(symptoms: List[str], top_k: int=5) -> str:
290
+ """
291
+ Suggest likely diseases based on matching symptoms (using severity weights) from the dataset.
292
+ Returns a JSON string of ranked candidates.
293
+ """
294
+ # Get the top K disease diagnoses
295
+ results = disease_candidates(symptoms, top_k=top_k)
296
+ # Return a JSON formatted string from the list
297
+ return json.dumps({"candidates": results}, indent=2)
298
+
299
+ # Create a symptom severity calculation tool, using our schema
300
+ @tool(args_schema=SeverityInput)
301
+ def calc_symptom_severity(symptoms: List[str]) -> str:
302
+ """
303
+ Calculate a symptom severity score using weights from the Symptom-severity.csv dataset.
304
+ Returns a JSON string with the total score, severity level, and weights per symptom.
305
+ """
306
+ # Get the symptoms severity summary
307
+ report = severity_report(symptoms)
308
+ # Return a JSON formatted string
309
+ return json.dumps(report, indent=2)
310
+
311
+ # Create a tool to get disease description, using our schema
312
+ @tool(args_schema=DiseaseInfoInput)
313
+ def get_disease_description(disease: str) -> str:
314
+ """
315
+ Get the description for a disease (from the symptom_Description.csv dataset)
316
+ """
317
+ # Clean the disease name
318
+ disease = canon_text(disease)
319
+ # Lookup the disease description and return
320
+ return disease_to_desc.get(disease, "")
321
+
322
+ # Create a tool to get disease precaution advice, using our schema
323
+ @tool(args_schema=DiseaseInfoInput)
324
+ def get_precaution_advice(disease: str) -> str:
325
+ """
326
+ Get precaution steps for a disease (from the symptom_precaution.csv dataset)
327
+ """
328
+ # Clean the disease name
329
+ disease = canon_text(disease)
330
+ # Lookup the disease precautions and return
331
+ return json.dumps(disease_to_prec.get(disease, []), indent=2)
332
+
333
+ # Create a tool to retrieve disease documents from the vector store, using our schema
334
+ @tool(args_schema=RetrieveDocsInput)
335
+ def retrieve_disease_docs(query: str, k: int = 3):
336
+ """
337
+ Retrieve disease documents from the vector store for "ground truth" and explanations.
338
+ Returns (serialized_text, retrieved_documents).)
339
+ """
340
+ # Get K similar docs from the vector store, based on the query
341
+ retrieved = vector_store.similarity_search(query, k=k)
342
+ # Get a serialized string of the top K matching disease docs
343
+ serialized = "\n\n".join(
344
+ f"Source: {doc.metadata}\nContent\n{doc.page_content}"
345
+ for doc in retrieved
346
+ )
347
+ return serialized
348
+
349
+ tools = [
350
+ diagnose_diseases,
351
+ calc_symptom_severity,
352
+ get_disease_description,
353
+ get_precaution_advice,
354
+ retrieve_disease_docs,
355
+ ]
356
+
357
+ # LLM + orchestrator agent
358
+
359
+ # Use a deterministic model since we are using tools for diagnosis and severity calculation and use the mini model for faster responses
360
+ model = init_chat_model(
361
+ "gpt-4.1-mini",
362
+ temperature=0,
363
+ model_provider="openai",
364
+ api_key=OPENAI_API_KEY,
365
+ )
366
+ system_prompt = """
367
+ You are a medical decision support assistant, not to be used as a replacement for professional medical care.
368
+ In your responses, always:
369
+ - Use tools to identify diagnosis candidates and symptom severity
370
+ - Provide a disclaimer that the user should consult with a doctor
371
+ - Give precaution advice and recommend professional medical care when appropriate (i.e. moderate to severe symptoms)
372
+ - If symptoms suggest a serious emergency risk (e.g. chest pain, difficulty breathing, serious bleeding), then recommend urgent care or emergency room services
373
+
374
+ Workflow to follow:
375
+ 1) Ask for symptoms if not provided by user
376
+ 2) Call calc_symptom_severity(symptoms)
377
+ 3) Call diagnose_diseases(symptoms, top_k=5)
378
+ 4) For the top 1-3 diseases, call retreive_disease_docs using the disease name or symptoms.
379
+ 5) Return: top candidates also with why (matched symptoms), severity level, description + precautions for the top candidate(s), and provide follow-up questions to refine.
380
+
381
+ Responses should always be concise.
382
+ """.strip()
383
+
384
+ agent = create_agent(model, tools, system_prompt=system_prompt)
385
+
386
+ # Multi-turn chat
387
+ def chat_once(messages: List[BaseMessage]) -> List[BaseMessage]:
388
+ """
389
+ messages: List of BaseMessage objects for the conversation history.
390
+ Returns updated list of BaseMessage objects with the agent's final response added.
391
+ """
392
+ final_state = None
393
+ for step in agent.stream({"messages": messages}, stream_mode="values"):
394
+ final_state = step
395
+
396
+ # Return the actual BaseMessage objects from the final state
397
+ return final_state["messages"]
398
+
399
+ # For the Gradio UI, we want to run the agent and get the updated LangChain message history, so we can extract the assistant's final response and also maintain the full conversation state (including tool calls) in the UI.
400
+ def run_agent_once(lc_history: List[BaseMessage]) -> List[BaseMessage]:
401
+ """
402
+ Runs the agent on the current conversation and returns the updated LangChain message history.
403
+ """
404
+ final_state = None
405
+ for step in agent.stream({"messages": lc_history}, stream_mode="values"):
406
+ final_state = step
407
+ return final_state["messages"]
408
+
409
+ # Helper function to extract the last assistant response content from the LangChain message history
410
+ def get_last_ai_content(lc_history: List[BaseMessage]) -> str:
411
+ """
412
+ Extract the last assistant response content from the LangChain message history.
413
+ """
414
+ for m in reversed(lc_history):
415
+ if isinstance(m, AIMessage):
416
+ return (m.content or "").strip()
417
+ return ""
418
+
419
+ # Gradio UI handlers
420
+ def submit_chat(user_text: str, chat_history: List[dict], lc_state: Optional[List[BaseMessage]]):
421
+ """
422
+ Gradio handler:
423
+ - user_text: current textbox input
424
+ - chat_history: list of {"role": "...", "content": "..."} used by gr.Chatbot(type="messages")
425
+ - lc_state: LangChain BaseMessage history stored in gr.State
426
+
427
+ Returns:
428
+ - updated chat_history (for UI)
429
+ - cleared textbox
430
+ - updated lc_state
431
+ """
432
+ user_text = (user_text or "").strip()
433
+ if not user_text:
434
+ return chat_history, "", lc_state
435
+
436
+ if lc_state is None:
437
+ lc_state = []
438
+
439
+ # 1) Add user message to LangChain state
440
+ lc_state.append(HumanMessage(content=user_text))
441
+
442
+ # 2) Run agent, get updated LangChain history (includes tool calls, etc.)
443
+ lc_state = run_agent_once(lc_state)
444
+
445
+ # 3) Extract the assistant’s final natural-language response
446
+ assistant_text = get_last_ai_content(lc_state)
447
+ if not assistant_text:
448
+ assistant_text = "I couldn't generate a response. Please try rephrasing your symptoms."
449
+
450
+ # 4) Update the Gradio chat history (messages format)
451
+ chat_history = chat_history + [
452
+ {"role": "user", "content": user_text},
453
+ {"role": "assistant", "content": assistant_text},
454
+ ]
455
+
456
+ return chat_history, "", lc_state
457
+
458
+ # Handler to reset the chat - clears the Gradio chat history and the LangChain state
459
+ def reset_chat():
460
+ return [], [] # chat_history, lc_state
461
+
462
+ # Build the Gradio UI
463
+ with gr.Blocks(title="MediBot – Disease & Symptom Assistant") as demo:
464
+ gr.Markdown(
465
+ """
466
+ # MediBot (RAG + Tools)
467
+ Enter your symptoms in plain language (comma-separated is fine).
468
+ **Note:** This is not medical advice—consult a clinician for diagnosis and treatment.
469
+ """.strip()
470
+ )
471
+
472
+ chatbot = gr.Chatbot(height=420)
473
+ lc_state = gr.State([])
474
+
475
+ # User input row
476
+ with gr.Row():
477
+ user_box = gr.Textbox(
478
+ label="Your message",
479
+ placeholder="e.g., fever, headache, chills, fatigue",
480
+ scale=8,
481
+ )
482
+ send_btn = gr.Button("Send", scale=2)
483
+
484
+ with gr.Row():
485
+ examples = gr.Examples(
486
+ examples=[
487
+ ["I have fever, headache, chills, and fatigue. What could it be?"],
488
+ ["I also have nausea and joint pain."],
489
+ ["Sore throat, runny nose, mild cough for 2 days."],
490
+ ["Chest pain and shortness of breath."],
491
+ ],
492
+ inputs=user_box,
493
+ label="Examples",
494
+ )
495
+
496
+ clear_btn = gr.Button("Clear chat")
497
+
498
+ # Wire events
499
+
500
+ # When the send button is clicked, run the submit_chat function with the current user input, chat history, and LangChain state, and update the chatbot and clear the user input box
501
+ send_btn.click(
502
+ fn=submit_chat,
503
+ inputs=[user_box, chatbot, lc_state],
504
+ outputs=[chatbot, user_box, lc_state],
505
+ )
506
+
507
+ # Allow pressing Enter in the textbox to submit the chat as well
508
+ user_box.submit(
509
+ fn=submit_chat,
510
+ inputs=[user_box, chatbot, lc_state],
511
+ outputs=[chatbot, user_box, lc_state],
512
+ )
513
+
514
+ # Clear button resets both the Gradio chat history and the LangChain state
515
+ clear_btn.click(
516
+ fn=lambda: ([], "", []),
517
+ inputs=[],
518
+ outputs=[chatbot, user_box, lc_state],
519
+ )
520
+
521
+ # Launch the UI
522
+ if __name__ == "__main__":
523
+ demo.launch()