Initial MediBot deployment
Browse filesOpenAI GPT-4o-mini + FAISS RAG + LangGraph ReAct agent + Gradio UI.
Datasets bundled in datasets/; FAISS index builds on first launch.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (21)
- .gitignoreAdded+6
- README.md+83-7
- agents/__init__.pyAdded
- agents/memory.pyAdded+8
- agents/react_agent.pyAdded+31
- agents/tools.pyAdded+101
- app.pyAdded+110
- config.pyAdded+32
- data/__init__.pyAdded
- data/loader.pyAdded+44
- data/preprocessor.pyAdded+98
- datasets/Symptom-severity.csvAdded+134
- datasets/dataset.csvAdded
- datasets/symptom_Description.csvAdded+42
- datasets/symptom_precaution.csvAdded+42
- prompts/__init__.pyAdded
- prompts/templates.pyAdded+51
- rag/__init__.pyAdded
- rag/faiss_index.pyAdded+32
- rag/retriever.pyAdded+73
- requirements.txtAdded+11
123456.env__pycache__/*.pyc*.pyofaiss_index/.DS_Store12345678910111213---title: Medi Botemoji: 🐠colorFrom: purplecolorTo: redsdk: gradiosdk_version: 6.14.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889---title: MediBot - AI Medical Symptom Checkeremoji: 🏥colorFrom: bluecolorTo: cyansdk: gradiosdk_version: "5.0"app_file: app.pypinned: falselicense: mittags:- medical- nlp- langchain- faiss- rag- openai- symptom-checker---# 🏥 MediBot — AI Medical Symptom CheckerAn intelligent medical chatbot that uses **Retrieval-Augmented Generation (RAG)**, **FAISS vector search**, and **LangChain ReAct agents** to help users understand their symptoms and identify possible conditions.## ⚠️ DisclaimerMediBot is for **informational purposes only** and does NOT replace professional medical advice. Always consult a licensed healthcare provider.## Architecture```User Input → LangChain ReAct Agent → FAISS VectorStore (41 diseases)↓ ↓Tool Selection Semantic Symptom Search↓ ↓Disease Details Lookup Severity Score Calculation↓Gradio Chat Response```## Tech Stack| Component | Technology ||---|---|| LLM | OpenAI GPT-4o-mini || Embeddings | OpenAI text-embedding-3-small || Vector Store | FAISS (Facebook AI Similarity Search) || Agent Framework | LangChain ReAct || Memory | LangGraph MemorySaver (per thread_id) || UI | Gradio || Deployment | HuggingFace Spaces |## Key Features- **Semantic symptom search**: Finds diseases even when you don't use exact medical terms- **Multi-agent ReAct reasoning**: Dynamically selects the right tools for each query- **Conversation memory**: Remembers symptoms mentioned in previous messages- **Severity scoring**: Weighs each symptom by clinical importance (scale 1–6)- **Structured output**: Disease descriptions, precautions, and severity levels- **Edge case handling**: Graceful responses to unknown symptoms, empty input, or ambiguous queries## Data Sources- `dataset.csv` — 4,920 rows mapping 41 diseases to 17 symptoms each- `symptom_Description.csv` — Medical descriptions for 41 diseases- `Symptom-severity.csv` — Clinical severity weights for 133 symptoms- `symptom_precaution.csv` — Up to 4 precautions per disease## Setup (Local)```bash# Clone and installpip install -r requirements.txt# Set your OpenAI API keycp .env.example .env# Edit .env and add your key# Runpython app.py```## HuggingFace Spaces DeploymentSet `OPENAI_API_KEY` as a **Secret** in your Space settings. The FAISS index is built on first launch (takes ~30 seconds, then cached).---*MediBot Capstone · Interview Kickstart*
12345678"""Conversation memory using LangGraph's in-memory checkpointer."""from langgraph.checkpoint.memory import MemorySaver
DEFAULT_THREAD_ID = "medibot-session-1"
def create_memory() -> MemorySaver: return MemorySaver()12345678910111213141516171819202122232425262728293031"""Build the LangGraph ReAct agent for MediBot."""from langchain_openai import ChatOpenAIfrom langchain_core.messages import SystemMessagefrom langgraph.prebuilt import create_react_agentfrom langgraph.checkpoint.memory import MemorySaverfrom agents.tools import search_diseases, get_disease_details, calculate_severity, list_common_symptomsfrom prompts.templates import SYSTEM_PROMPTfrom config import CHAT_MODEL
TOOLS = [search_diseases, get_disease_details, calculate_severity, list_common_symptoms]
def build_agent(): """Return (graph, config). Call once at startup.
Usage: graph, config = build_agent() result = graph.invoke({"messages": [HumanMessage(content="I have fever")]}, config) reply = result["messages"][-1].content """ llm = ChatOpenAI(model=CHAT_MODEL, temperature=0.2) memory = MemorySaver()
graph = create_react_agent( model=llm, tools=TOOLS, prompt=SystemMessage(content=SYSTEM_PROMPT), checkpointer=memory, ) config = {"configurable": {"thread_id": "medibot-main"}} return graph, config123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Four LangChain tools for the MediBot ReAct agent."""from langchain_core.tools import toolfrom rag.retriever import ( search_diseases as _search, get_disease_details as _details, get_severity_map, get_all_symptoms,)from config import TOP_K_RESULTS
@tooldef search_diseases(symptoms: str) -> str: """Search the medical database for diseases that match the given symptoms. Input should be a comma-separated list of symptoms (e.g. 'fever, headache, chills'). Returns the top matching diseases with similarity scores.""" results = _search(symptoms, k=TOP_K_RESULTS) if not results: return "No matching diseases found. Please provide more specific symptoms." lines = [f"Top {len(results)} disease matches for: '{symptoms}'\n"] for i, r in enumerate(results, 1): lines.append(f"{i}. {r['disease']} (relevance: {r['score']:.2f})") return "\n".join(lines)
@tooldef get_disease_details(disease_name: str) -> str: """Get detailed information about a specific disease including description, symptoms, precautions, and severity level. Input should be the disease name.""" details = _details(disease_name) if not details: return f"Disease '{disease_name}' not found in the database." syms = ", ".join(details["symptoms"][:10]) precs = "; ".join(details["precautions"]) if details["precautions"] else "Consult a doctor" desc = details["description"][:300] + "..." if len(details["description"]) > 300 else details["description"] return ( f"**{details['disease']}**\n" f"Severity Level: {details['severity_label']} (score: {details['avg_severity']})\n\n" f"Description: {desc}\n\n" f"Common Symptoms: {syms}\n\n" f"Precautions: {precs}" )
@tooldef calculate_severity(symptoms: str) -> str: """Calculate the medical severity score for a list of symptoms based on clinical weights. Input should be a comma-separated list of symptoms. Returns a severity level: Mild, Moderate, Severe, or Critical.""" sev_map = get_severity_map() symptom_list = [s.strip().lower().replace(" ", "_") for s in symptoms.split(",")] matched = [] unmatched = [] total = 0 for sym in symptom_list: if sym in sev_map: w = sev_map[sym] matched.append(f"{sym} (weight: {w})") total += w elif sym: unmatched.append(sym)
if not matched: return ( f"None of the symptoms ({symptoms}) were found in the severity database. " "Try using underscore-separated symptom names (e.g. 'skin_rash' instead of 'skin rash')." )
from config import SEVERITY_THRESHOLDS level = "Unknown" for label, (lo, hi) in SEVERITY_THRESHOLDS.items(): if lo <= total < hi: level = label break
result = f"Severity Assessment for: {', '.join(symptom_list)}\n" result += f"Total severity score: {total}\n" result += f"Severity Level: **{level}**\n\n" result += "Matched symptoms:\n" + "\n".join(f" - {m}" for m in matched) if unmatched: result += f"\n\nUnrecognized symptoms (may be misspelled): {', '.join(unmatched)}" return result
@tooldef list_common_symptoms(category: str = "all") -> str: """List recognized medical symptoms from the database to help users identify what they have. Optionally filter by category keyword. Use 'all' to list everything.""" symptoms = get_all_symptoms() if category.lower() != "all": symptoms = [s for s in symptoms if category.lower() in s] if not symptoms: return f"No symptoms found matching '{category}'." grouped = {} for sym in symptoms: key = sym[0].upper() grouped.setdefault(key, []).append(sym.replace("_", " ")) lines = [f"Recognized symptoms ({len(symptoms)} total):\n"] for letter in sorted(grouped): lines.append(f"{letter}: {', '.join(grouped[letter])}") return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""MediBot — AI Medical Symptom Checker. Entry point for Gradio and HuggingFace Spaces."""import osimport sysimport uuidsys.path.insert(0, os.path.dirname(__file__))
import config # loads .env and sets KMP_DUPLICATE_LIB_OK
import gradio as grfrom langchain_core.messages import HumanMessagefrom agents.react_agent import build_agent
print("Initializing MediBot...")_graph, _ = build_agent()print("MediBot ready.")
DISCLAIMER = ( "**⚠️ Medical Disclaimer:** MediBot is an AI assistant for informational purposes only. " "It does NOT replace professional medical advice, diagnosis, or treatment. " "Always consult a licensed healthcare provider for medical concerns.")
EXAMPLES = [ "I have fever, headache and chills", "I feel itchy with skin rash", "Fatigue, weight loss and excessive thirst", "Chest pain and shortness of breath", "What are the precautions for malaria?", "How severe is vomiting as a symptom?",]
def respond(message: str, history: list, thread_id: str): if not message.strip(): return history, "", thread_id cfg = {"configurable": {"thread_id": thread_id}} try: result = _graph.invoke({"messages": [HumanMessage(content=message)]}, cfg) reply = result["messages"][-1].content except Exception as e: reply = f"Error: {str(e)[:200]}" history = history + [ {"role": "user", "content": message}, {"role": "assistant", "content": reply}, ] return history, "", thread_id
def new_conversation(): return [], "", str(uuid.uuid4())
with gr.Blocks(title="MediBot") as demo: thread_id_state = gr.State(str(uuid.uuid4()))
gr.Markdown("# 🏥 MediBot — AI Medical Symptom Checker") gr.Markdown(DISCLAIMER)
chatbot = gr.Chatbot(label="MediBot Chat", height=450)
msg_box = gr.Textbox( label="Your symptoms", placeholder="Describe your symptoms here...", lines=2, )
with gr.Row(): send_btn = gr.Button("Send", variant="primary") clear_btn = gr.Button("🆕 New Conversation", variant="secondary")
gr.Markdown("**Quick examples:**") with gr.Row(): ex_btns_row1 = [gr.Button(EXAMPLES[i], size="sm") for i in range(3)] with gr.Row(): ex_btns_row2 = [gr.Button(EXAMPLES[i], size="sm") for i in range(3, 6)]
gr.Markdown("---") gr.Markdown( "### How to Use\n" "1. Type your symptoms in the box above and click **Send**\n" "2. MediBot identifies possible diseases and gives precautions\n" "3. Ask follow-up questions — MediBot remembers the conversation\n" "4. Click **🆕 New Conversation** to clear history and start fresh\n\n" "*Built with LangGraph ReAct Agents · FAISS Vector Search · OpenAI GPT-4o-mini*" )
# Event wiring send_btn.click( respond, inputs=[msg_box, chatbot, thread_id_state], outputs=[chatbot, msg_box, thread_id_state], ) msg_box.submit( respond, inputs=[msg_box, chatbot, thread_id_state], outputs=[chatbot, msg_box, thread_id_state], ) clear_btn.click( new_conversation, inputs=[], outputs=[chatbot, msg_box, thread_id_state], )
all_ex_btns = ex_btns_row1 + ex_btns_row2 for btn, ex in zip(all_ex_btns, EXAMPLES): btn.click(fn=lambda e=ex: e, inputs=[], outputs=msg_box)
if __name__ == "__main__": demo.launch(server_port=7860, show_error=True)1234567891011121314151617181920212223242526272829303132"""Central configuration for MediBot."""import osfrom pathlib import Pathfrom dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env")
# Fixes a macOS OpenMP conflict when FAISS is imported alongside certain packagesos.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
ROOT = Path(__file__).parentDATA_DIR = ROOT / "datasets"
DATASET_PATH = DATA_DIR / "dataset.csv"DESCRIPTION_PATH = DATA_DIR / "symptom_Description.csv"SEVERITY_PATH = DATA_DIR / "Symptom-severity.csv"PRECAUTION_PATH = DATA_DIR / "symptom_precaution.csv"
FAISS_INDEX_PATH = ROOT / "faiss_index"
EMBEDDING_MODEL = "text-embedding-3-small"CHAT_MODEL = "gpt-4o-mini"
TOP_K_RESULTS = 3MEMORY_WINDOW = 10
SEVERITY_THRESHOLDS = { "Mild": (0, 10), "Moderate": (10, 20), "Severe": (20, 35), "Critical": (35, float("inf")),}1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Load and normalize the four MediBot CSV datasets."""import pandas as pdfrom config import DATASET_PATH, DESCRIPTION_PATH, SEVERITY_PATH, PRECAUTION_PATH
def load_dataset() -> pd.DataFrame: df = pd.read_csv(DATASET_PATH) df.columns = [c.strip() for c in df.columns] df["Disease"] = df["Disease"].str.strip() return df
def load_descriptions() -> pd.DataFrame: df = pd.read_csv(DESCRIPTION_PATH) df.columns = [c.strip() for c in df.columns] df["Disease"] = df["Disease"].str.strip() return df
def load_severity() -> pd.DataFrame: df = pd.read_csv(SEVERITY_PATH) df.columns = [c.strip() for c in df.columns] df["Symptom"] = df["Symptom"].str.strip().str.lower().str.replace(" ", "_") return df
def load_precautions() -> pd.DataFrame: df = pd.read_csv(PRECAUTION_PATH) df.columns = [c.strip() for c in df.columns] df["Disease"] = df["Disease"].str.strip() return df
def load_all(): return load_dataset(), load_descriptions(), load_severity(), load_precautions()
if __name__ == "__main__": ds, desc, sev, prec = load_all() print(f"Dataset: {len(ds)} rows, {ds['Disease'].nunique()} diseases") print(f"Descriptions: {len(desc)} diseases") print(f"Severity: {len(sev)} symptoms") print(f"Precautions: {len(prec)} diseases") print("Sample diseases:", ds["Disease"].unique()[:5].tolist())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Build disease knowledge documents and a merged lookup table."""import pandas as pdfrom data.loader import load_allfrom config import SEVERITY_THRESHOLDS
def _symptom_cols(df: pd.DataFrame) -> list[str]: return [c for c in df.columns if c.lower().startswith("symptom")]
def _average_severity(symptoms: list[str], severity_df: pd.DataFrame) -> float: sev_map = dict(zip(severity_df["Symptom"], severity_df["weight"])) weights = [sev_map.get(s.strip().lower().replace(" ", "_"), 0) for s in symptoms if s] return round(sum(weights) / len(weights), 2) if weights else 0.0
def _severity_label(score: float) -> str: for label, (lo, hi) in SEVERITY_THRESHOLDS.items(): if lo <= score < hi: return label return "Unknown"
_ALIASES = { "dimorphic hemmorhoids(piles)": "dimorphic hemorrhoids(piles)",}
def _normalize_name(name: str) -> str: """Lowercase + collapse whitespace, then apply known spelling aliases.""" import re key = re.sub(r"\s+", " ", name.strip().lower()) return _ALIASES.get(key, key)
def build_knowledge_base() -> tuple[pd.DataFrame, list[str]]: """Return (merged_df, document_strings) for all 41 diseases.""" dataset_df, desc_df, sev_df, prec_df = load_all() sym_cols = _symptom_cols(dataset_df)
# Deduplicate: one row per disease with all unique symptoms combined def agg_symptoms(group): syms = set() for col in sym_cols: syms.update(group[col].dropna().str.strip().str.lower().str.replace(" ", "_").tolist()) syms.discard("") return sorted(syms)
disease_symptoms = ( dataset_df.groupby("Disease") .apply(agg_symptoms) .reset_index() .rename(columns={0: "symptoms"}) )
# Normalize names for merge so typo variants (hemmorhoids vs hemorrhoids) still join disease_symptoms["_key"] = disease_symptoms["Disease"].apply(_normalize_name) desc_df = desc_df.copy() desc_df["_key"] = desc_df["Disease"].apply(_normalize_name) prec_df = prec_df.copy() prec_df["_key"] = prec_df["Disease"].apply(_normalize_name)
# Merge descriptions and precautions on normalized key, keep canonical disease name merged = disease_symptoms.merge(desc_df.drop(columns=["Disease"]), on="_key", how="left") prec_cols = [c for c in prec_df.columns if c.lower().startswith("precaution")] merged = merged.merge(prec_df.drop(columns=["Disease"])[["_key"] + prec_cols], on="_key", how="left") merged = merged.drop(columns=["_key"])
# Compute severity merged["avg_severity"] = merged["symptoms"].apply( lambda s: _average_severity(s, sev_df) ) merged["severity_label"] = merged["avg_severity"].apply(_severity_label)
# Build document string per disease docs = [] for _, row in merged.iterrows(): syms_str = ", ".join(row["symptoms"]) precs = [str(row[c]) for c in prec_cols if pd.notna(row.get(c))] precs_str = "; ".join(precs) if precs else "Consult a doctor" desc = str(row.get("Description", "")).strip() or "No description available." doc = ( f"Disease: {row['Disease']}. " f"Symptoms: {syms_str}. " f"Description: {desc} " f"Precautions: {precs_str}. " f"Severity: {row['severity_label']} (avg weight: {row['avg_severity']})." ) docs.append(doc)
return merged, docs
if __name__ == "__main__": merged, docs = build_knowledge_base() print(f"Built {len(docs)} disease documents") print("\nSample document:") print(docs[0])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134Symptom,weightitching,1skin_rash,3nodal_skin_eruptions,4continuous_sneezing,4shivering,5chills,3joint_pain,3stomach_pain,5acidity,3ulcers_on_tongue,4muscle_wasting,3vomiting,5burning_micturition,6spotting_urination,6fatigue,4weight_gain,3anxiety,4cold_hands_and_feets,5mood_swings,3weight_loss,3restlessness,5lethargy,2patches_in_throat,6irregular_sugar_level,5cough,4high_fever,7sunken_eyes,3breathlessness,4sweating,3dehydration,4indigestion,5headache,3yellowish_skin,3dark_urine,4nausea,5loss_of_appetite,4pain_behind_the_eyes,4back_pain,3constipation,4abdominal_pain,4diarrhoea,6mild_fever,5yellow_urine,4yellowing_of_eyes,4acute_liver_failure,6fluid_overload,6swelling_of_stomach,7swelled_lymph_nodes,6malaise,6blurred_and_distorted_vision,5phlegm,5throat_irritation,4redness_of_eyes,5sinus_pressure,4runny_nose,5congestion,5chest_pain,7weakness_in_limbs,7fast_heart_rate,5pain_during_bowel_movements,5pain_in_anal_region,6bloody_stool,5irritation_in_anus,6neck_pain,5dizziness,4cramps,4bruising,4obesity,4swollen_legs,5swollen_blood_vessels,5puffy_face_and_eyes,5enlarged_thyroid,6brittle_nails,5swollen_extremeties,5excessive_hunger,4extra_marital_contacts,5drying_and_tingling_lips,4slurred_speech,4knee_pain,3hip_joint_pain,2muscle_weakness,2stiff_neck,4swelling_joints,5movement_stiffness,5spinning_movements,6loss_of_balance,4unsteadiness,4weakness_of_one_body_side,4loss_of_smell,3bladder_discomfort,4foul_smell_ofurine,5continuous_feel_of_urine,6passage_of_gases,5internal_itching,4toxic_look_(typhos),5depression,3irritability,2muscle_pain,2altered_sensorium,2red_spots_over_body,3belly_pain,4abnormal_menstruation,6dischromic_patches,6watering_from_eyes,4increased_appetite,5polyuria,4family_history,5mucoid_sputum,4rusty_sputum,4lack_of_concentration,3visual_disturbances,3receiving_blood_transfusion,5receiving_unsterile_injections,2coma,7stomach_bleeding,6distention_of_abdomen,4history_of_alcohol_consumption,5fluid_overload,4blood_in_sputum,5prominent_veins_on_calf,6palpitations,4painful_walking,2pus_filled_pimples,2blackheads,2scurring,2skin_peeling,3silver_like_dusting,2small_dents_in_nails,2inflammatory_nails,2blister,4red_sore_around_nose,2yellow_crust_ooze,3prognosis,5123456789101112131415161718192021222324252627282930313233343536373839404142Disease,DescriptionDrug Reaction,An adverse drug reaction (ADR) is an injury caused by taking medication. ADRs may occur following a single dose or prolonged administration of a drug or result from the combination of two or more drugs.Malaria,An infectious disease caused by protozoan parasites from the Plasmodium family that can be transmitted by the bite of the Anopheles mosquito or by a contaminated needle or transfusion. Falciparum malaria is the most deadly type.Allergy,"An allergy is an immune system response to a foreign substance that's not typically harmful to your body.They can include certain foods, pollen, or pet dander. Your immune system's job is to keep you healthy by fighting harmful pathogens."Hypothyroidism,"Hypothyroidism, also called underactive thyroid or low thyroid, is a disorder of the endocrine system in which the thyroid gland does not produce enough thyroid hormone."Psoriasis,"Psoriasis is a common skin disorder that forms thick, red, bumpy patches covered with silvery scales. They can pop up anywhere, but most appear on the scalp, elbows, knees, and lower back. Psoriasis can't be passed from person to person. It does sometimes happen in members of the same family."GERD,"Gastroesophageal reflux disease, or GERD, is a digestive disorder that affects the lower esophageal sphincter (LES), the ring of muscle between the esophagus and stomach. Many people, including pregnant women, suffer from heartburn or acid indigestion caused by GERD."Chronic cholestasis,"Chronic cholestatic diseases, whether occurring in infancy, childhood or adulthood, are characterized by defective bile acid transport from the liver to the intestine, which is caused by primary damage to the biliary epithelium in most cases"hepatitis A,Hepatitis A is a highly contagious liver infection caused by the hepatitis A virus. The virus is one of several types of hepatitis viruses that cause inflammation and affect your liver's ability to function.Osteoarthristis,"Osteoarthritis is the most common form of arthritis, affecting millions of people worldwide. It occurs when the protective cartilage that cushions the ends of your bones wears down over time."(vertigo) Paroymsal Positional Vertigo,Benign paroxysmal positional vertigo (BPPV) is one of the most common causes of vertigo — the sudden sensation that you're spinning or that the inside of your head is spinning. Benign paroxysmal positional vertigo causes brief episodes of mild to intense dizziness.Hypoglycemia, Hypoglycemia is a condition in which your blood sugar (glucose) level is lower than normal. Glucose is your body's main energy source. Hypoglycemia is often related to diabetes treatment. But other drugs and a variety of conditions — many rare — can cause low blood sugar in people who don't have diabetes.Acne,"Acne vulgaris is the formation of comedones, papules, pustules, nodules, and/or cysts as a result of obstruction and inflammation of pilosebaceous units (hair follicles and their accompanying sebaceous gland). Acne develops on the face and upper trunk. It most often affects adolescents."Diabetes,"Diabetes is a disease that occurs when your blood glucose, also called blood sugar, is too high. Blood glucose is your main source of energy and comes from the food you eat. Insulin, a hormone made by the pancreas, helps glucose from food get into your cells to be used for energy."Impetigo,"Impetigo (im-puh-TIE-go) is a common and highly contagious skin infection that mainly affects infants and children. Impetigo usually appears as red sores on the face, especially around a child's nose and mouth, and on hands and feet. The sores burst and develop honey-colored crusts."Hypertension,"Hypertension (HTN or HT), also known as high blood pressure (HBP), is a long-term medical condition in which the blood pressure in the arteries is persistently elevated. High blood pressure typically does not cause symptoms."Peptic ulcer diseae,"Peptic ulcer disease (PUD) is a break in the inner lining of the stomach, the first part of the small intestine, or sometimes the lower esophagus. An ulcer in the stomach is called a gastric ulcer, while one in the first part of the intestines is a duodenal ulcer."Dimorphic hemorrhoids(piles),"Hemorrhoids, also spelled haemorrhoids, are vascular structures in the anal canal. In their ... Other names, Haemorrhoids, piles, hemorrhoidal disease ."Common Cold,"The common cold is a viral infection of your nose and throat (upper respiratory tract). It's usually harmless, although it might not feel that way. Many types of viruses can cause a common cold."Chicken pox,"Chickenpox is a highly contagious disease caused by the varicella-zoster virus (VZV). It can cause an itchy, blister-like rash. The rash first appears on the chest, back, and face, and then spreads over the entire body, causing between 250 and 500 itchy blisters."Cervical spondylosis,"Cervical spondylosis is a general term for age-related wear and tear affecting the spinal disks in your neck. As the disks dehydrate and shrink, signs of osteoarthritis develop, including bony projections along the edges of bones (bone spurs)."Hyperthyroidism,"Hyperthyroidism (overactive thyroid) occurs when your thyroid gland produces too much of the hormone thyroxine. Hyperthyroidism can accelerate your body's metabolism, causing unintentional weight loss and a rapid or irregular heartbeat."Urinary tract infection,"Urinary tract infection: An infection of the kidney, ureter, bladder, or urethra. Abbreviated UTI. Not everyone with a UTI has symptoms, but common symptoms include a frequent urge to urinate and pain or burning when urinating."Varicose veins,"A vein that has enlarged and twisted, often appearing as a bulging, blue blood vessel that is clearly visible through the skin. Varicose veins are most common in older adults, particularly women, and occur especially on the legs."AIDS,"Acquired immunodeficiency syndrome (AIDS) is a chronic, potentially life-threatening condition caused by the human immunodeficiency virus (HIV). By damaging your immune system, HIV interferes with your body's ability to fight infection and disease."Paralysis (brain hemorrhage),"Intracerebral hemorrhage (ICH) is when blood suddenly bursts into brain tissue, causing damage to your brain. Symptoms usually appear suddenly during ICH. They include headache, weakness, confusion, and paralysis, particularly on one side of your body."Typhoid,"An acute illness characterized by fever caused by infection with the bacterium Salmonella typhi. Typhoid fever has an insidious onset, with fever, headache, constipation, malaise, chills, and muscle pain. Diarrhea is uncommon, and vomiting is not usually severe."Hepatitis B,"Hepatitis B is an infection of your liver. It can cause scarring of the organ, liver failure, and cancer. It can be fatal if it isn't treated. It's spread when people come in contact with the blood, open sores, or body fluids of someone who has the hepatitis B virus."Fungal infection,"In humans, fungal infections occur when an invading fungus takes over an area of the body and is too much for the immune system to handle. Fungi can live in the air, soil, water, and plants. There are also some fungi that live naturally in the human body. Like many microbes, there are helpful fungi and harmful fungi."Hepatitis C,"Inflammation of the liver due to the hepatitis C virus (HCV), which is usually spread via blood transfusion (rare), hemodialysis, and needle sticks. The damage hepatitis C does to the liver can lead to cirrhosis and its complications as well as cancer."Migraine,"A migraine can cause severe throbbing pain or a pulsing sensation, usually on one side of the head. It's often accompanied by nausea, vomiting, and extreme sensitivity to light and sound. Migraine attacks can last for hours to days, and the pain can be so severe that it interferes with your daily activities."Bronchial Asthma,"Bronchial asthma is a medical condition which causes the airway path of the lungs to swell and narrow. Due to this swelling, the air path produces excess mucus making it hard to breathe, which results in coughing, short breath, and wheezing. The disease is chronic and interferes with daily working."Alcoholic hepatitis,"Alcoholic hepatitis is a diseased, inflammatory condition of the liver caused by heavy alcohol consumption over an extended period of time. It's also aggravated by binge drinking and ongoing alcohol use. If you develop this condition, you must stop drinking alcohol"Jaundice,"Yellow staining of the skin and sclerae (the whites of the eyes) by abnormally high blood levels of the bile pigment bilirubin. The yellowing extends to other tissues and body fluids. Jaundice was once called the ""morbus regius"" (the regal disease) in the belief that only the touch of a king could cure it"Hepatitis E,A rare form of liver inflammation caused by infection with the hepatitis E virus (HEV). It is transmitted via food or drink handled by an infected person or through infected water supplies in areas where fecal matter may get into the water. Hepatitis E does not cause chronic liver disease.Dengue,"an acute infectious disease caused by a flavivirus (species Dengue virus of the genus Flavivirus), transmitted by aedes mosquitoes, and characterized by headache, severe joint pain, and a rash. — called also breakbone fever, dengue fever."Hepatitis D,"Hepatitis D, also known as the hepatitis delta virus, is an infection that causes the liver to become inflamed. This swelling can impair liver function and cause long-term liver problems, including liver scarring and cancer. The condition is caused by the hepatitis D virus (HDV)."Heart attack,"The death of heart muscle due to the loss of blood supply. The loss of blood supply is usually caused by a complete blockage of a coronary artery, one of the arteries that supplies blood to the heart muscle."Pneumonia,"Pneumonia is an infection in one or both lungs. Bacteria, viruses, and fungi cause it. The infection causes inflammation in the air sacs in your lungs, which are called alveoli. The alveoli fill with fluid or pus, making it difficult to breathe."Arthritis,"Arthritis is the swelling and tenderness of one or more of your joints. The main symptoms of arthritis are joint pain and stiffness, which typically worsen with age. The most common types of arthritis are osteoarthritis and rheumatoid arthritis."Gastroenteritis,"Gastroenteritis is an inflammation of the digestive tract, particularly the stomach, and large and small intestines. Viral and bacterial gastroenteritis are intestinal infections associated with symptoms of diarrhea , abdominal cramps, nausea , and vomiting ."Tuberculosis,"Tuberculosis (TB) is an infectious disease usually caused by Mycobacterium tuberculosis (MTB) bacteria. Tuberculosis generally affects the lungs, but can also affect other parts of the body. Most infections show no symptoms, in which case it is known as latent tuberculosis."123456789101112131415161718192021222324252627282930313233343536373839404142Disease,Precaution_1,Precaution_2,Precaution_3,Precaution_4Drug Reaction,stop irritation,consult nearest hospital,stop taking drug,follow upMalaria,Consult nearest hospital,avoid oily food,avoid non veg food,keep mosquitos outAllergy,apply calamine,cover area with bandage,,use ice to compress itchingHypothyroidism,reduce stress,exercise,eat healthy,get proper sleepPsoriasis,wash hands with warm soapy water,stop bleeding using pressure,consult doctor,salt bathsGERD,avoid fatty spicy food,avoid lying down after eating,maintain healthy weight,exerciseChronic cholestasis,cold baths,anti itch medicine,consult doctor,eat healthyhepatitis A,Consult nearest hospital,wash hands through,avoid fatty spicy food,medicationOsteoarthristis,acetaminophen,consult nearest hospital,follow up,salt baths(vertigo) Paroymsal Positional Vertigo,lie down,avoid sudden change in body,avoid abrupt head movment,relaxHypoglycemia,lie down on side,check in pulse,drink sugary drinks,consult doctorAcne,bath twice,avoid fatty spicy food,drink plenty of water,avoid too many productsDiabetes ,have balanced diet,exercise,consult doctor,follow upImpetigo,soak affected area in warm water,use antibiotics,remove scabs with wet compressed cloth,consult doctorHypertension ,meditation,salt baths,reduce stress,get proper sleepPeptic ulcer diseae,avoid fatty spicy food,consume probiotic food,eliminate milk,limit alcoholDimorphic hemmorhoids(piles),avoid fatty spicy food,consume witch hazel,warm bath with epsom salt,consume alovera juiceCommon Cold,drink vitamin c rich drinks,take vapour,avoid cold food,keep fever in checkChicken pox,use neem in bathing ,consume neem leaves,take vaccine,avoid public placesCervical spondylosis,use heating pad or cold pack,exercise,take otc pain reliver,consult doctorHyperthyroidism,eat healthy,massage,use lemon balm,take radioactive iodine treatmentUrinary tract infection,drink plenty of water,increase vitamin c intake,drink cranberry juice,take probioticsVaricose veins,lie down flat and raise the leg high,use oinments,use vein compression,dont stand still for longAIDS,avoid open cuts,wear ppe if possible,consult doctor,follow upParalysis (brain hemorrhage),massage,eat healthy,exercise,consult doctorTyphoid,eat high calorie vegitables,antiboitic therapy,consult doctor,medicationHepatitis B,consult nearest hospital,vaccination,eat healthy,medicationFungal infection,bath twice,use detol or neem in bathing water,keep infected area dry,use clean clothsHepatitis C,Consult nearest hospital,vaccination,eat healthy,medicationMigraine,meditation,reduce stress,use poloroid glasses in sun,consult doctorBronchial Asthma,switch to loose cloothing,take deep breaths,get away from trigger,seek helpAlcoholic hepatitis,stop alcohol consumption,consult doctor,medication,follow upJaundice,drink plenty of water,consume milk thistle,eat fruits and high fiberous food,medicationHepatitis E,stop alcohol consumption,rest,consult doctor,medicationDengue,drink papaya leaf juice,avoid fatty spicy food,keep mosquitos away,keep hydratedHepatitis D,consult doctor,medication,eat healthy,follow upHeart attack,call ambulance,chew or swallow asprin,keep calm,Pneumonia,consult doctor,medication,rest,follow upArthritis,exercise,use hot and cold therapy,try acupuncture,massageGastroenteritis,stop eating solid food for while,try taking small sips of water,rest,ease back into eatingTuberculosis,cover mouth,consult doctor,medication,rest123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""System prompt and ReAct prompt template for MediBot."""from langchain_core.prompts import PromptTemplate
SYSTEM_PROMPT = """You are MediBot, an AI-powered medical symptom checker. Your role is to help users understand their symptoms and identify possible conditions using the available medical database.
IMPORTANT GUIDELINES:- You are NOT a doctor and cannot provide an official diagnosis.- Always recommend consulting a licensed healthcare professional.- Be empathetic, clear, and structured in your responses.- If symptoms sound severe or life-threatening, urgently recommend emergency care.- Use the tools available to search for diseases, look up details, and calculate severity scores.- Ask clarifying follow-up questions when symptoms are ambiguous or when the user mentions fewer than 2 symptoms. Do not jump to conclusions — gather enough information first before searching for diseases.- Accumulate symptoms mentioned across the conversation before concluding.
When presenting results, always include:1. The most likely disease(s) based on symptoms2. A brief description of each disease3. Recommended precautions4. A severity assessment5. A reminder to see a real doctor"""
REACT_TEMPLATE = """You are MediBot, an empathetic AI medical assistant. Answer questions about symptoms and diseases using the tools provided.
{system_prompt}
You have access to the following tools:{tools}
Use this format:
Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [{tool_names}]Action Input: the input to the actionObservation: the result of the action... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input question
Previous conversation:{chat_history}
Question: {input}Thought: {agent_scratchpad}"""
REACT_PROMPT = PromptTemplate( input_variables=["input", "chat_history", "agent_scratchpad", "tools", "tool_names"], partial_variables={"system_prompt": SYSTEM_PROMPT}, template=REACT_TEMPLATE,)1234567891011121314151617181920212223242526272829303132"""Build, save, and load the FAISS vector index for disease documents."""from pathlib import Pathfrom langchain_openai import OpenAIEmbeddingsfrom langchain_community.vectorstores import FAISSfrom config import EMBEDDING_MODEL, FAISS_INDEX_PATH
def get_embeddings() -> OpenAIEmbeddings: return OpenAIEmbeddings(model=EMBEDDING_MODEL)
def build_and_save(docs: list[str], metadata: list[dict]) -> FAISS: embeddings = get_embeddings() store = FAISS.from_texts(docs, embeddings, metadatas=metadata) store.save_local(str(FAISS_INDEX_PATH)) return store
def load_index() -> FAISS: embeddings = get_embeddings() return FAISS.load_local( str(FAISS_INDEX_PATH), embeddings, allow_dangerous_deserialization=True, )
def get_or_build_index(docs: list[str], metadata: list[dict]) -> FAISS: index_file = Path(FAISS_INDEX_PATH) / "index.faiss" if index_file.exists(): return load_index() return build_and_save(docs, metadata)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""RAG retrieval: query FAISS and look up disease details from the merged DataFrame."""import pandas as pdfrom langchain_community.vectorstores import FAISSfrom config import TOP_K_RESULTSfrom data.preprocessor import build_knowledge_basefrom rag.faiss_index import get_or_build_index
_store: FAISS | None = None_merged_df: pd.DataFrame | None = None
def _init(): global _store, _merged_df if _store is None: _merged_df, docs = build_knowledge_base() metadata = [{"disease": row["Disease"]} for _, row in _merged_df.iterrows()] _store = get_or_build_index(docs, metadata)
def search_diseases(query: str, k: int = TOP_K_RESULTS) -> list[dict]: """Return top-k disease matches with similarity scores.""" _init() results = _store.similarity_search_with_relevance_scores(query, k=k) output = [] for doc, score in results: disease = doc.metadata.get("disease", "Unknown") output.append({"disease": disease, "score": round(score, 3), "content": doc.page_content}) return output
def get_disease_details(disease_name: str) -> dict | None: """Look up full details for a disease by name (case-insensitive).""" _init() row = _merged_df[_merged_df["Disease"].str.lower() == disease_name.strip().lower()] if row.empty: return None row = row.iloc[0] prec_cols = [c for c in _merged_df.columns if c.lower().startswith("precaution")] precautions = [str(row[c]) for c in prec_cols if pd.notna(row.get(c)) and str(row.get(c)) != "nan"] return { "disease": row["Disease"], "symptoms": row["symptoms"], "description": str(row.get("Description", "")).strip(), "precautions": precautions, "severity_label": row.get("severity_label", "Unknown"), "avg_severity": row.get("avg_severity", 0.0), }
def get_severity_map() -> dict[str, int]: """Return symptom -> weight mapping from the severity CSV.""" _init() from data.loader import load_severity sev_df = load_severity() return dict(zip(sev_df["Symptom"], sev_df["weight"]))
def get_all_symptoms() -> list[str]: """Return the full list of known symptoms.""" return sorted(get_severity_map().keys())
if __name__ == "__main__": print("Building index (first run embeds via OpenAI)...") results = search_diseases("fever and headache with chills") for r in results: print(f" {r['disease']} (score: {r['score']})") details = get_disease_details(results[0]["disease"]) print("\nTop disease details:") print(f" Description: {details['description'][:100]}...") print(f" Precautions: {details['precautions']}") print(f" Severity: {details['severity_label']}")1234567891011openai>=1.30.0langchain>=1.0.0langchain-openai>=0.3.0langchain-community>=0.4.0langchain-core>=0.3.0langgraph>=0.2.0faiss-cpu>=1.8.0gradio>=6.0.0pandas>=2.0.0numpy>=1.26.0python-dotenv>=1.0.0.gitignoreAdded+6
README.md+83-7
agents/__init__.pyAdded
agents/memory.pyAdded+8
agents/react_agent.pyAdded+31
agents/tools.pyAdded+101
app.pyAdded+110
config.pyAdded+32
data/__init__.pyAdded
data/loader.pyAdded+44
data/preprocessor.pyAdded+98
datasets/Symptom-severity.csvAdded+134
datasets/dataset.csvAdded
datasets/symptom_Description.csvAdded+42
datasets/symptom_precaution.csvAdded+42
prompts/__init__.pyAdded
prompts/templates.pyAdded+51
rag/__init__.pyAdded
rag/faiss_index.pyAdded+32
rag/retriever.pyAdded+73
requirements.txtAdded+11