Spaces:
Sleeping
Sleeping
Download app.py from bnewcomer/MediBot: direct link, hf CLI and curl.
- Browser
- Download file 66.1 kB
-
https://huggingface.co/spaces/bnewcomer/MediBot/resolve/main/app.py
- Command line
-
hf download hf://spaces/bnewcomer/MediBot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bnewcomer/MediBot/resolve/main/app.py
66.1 kB
"""
medical_chatbot_app.py
Multi-agent medical assistant with:
- ReAct-style LLM router
- FAISS-based diagnosis engine (in diagnosis_engine)
- Symptom severity scoring
- Disease description + precautions
- Logging & usage metrics
- Gradio UI
Requires:
pip install pandas numpy faiss-cpu scikit-learn gradio openai python-dotenv
"""
import os
import re
import json
import time
import logging
import hashlib
import html
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Any, Dict, List, Optional
import gradio as gr
import pandas as pd
from dotenv import load_dotenv
from openai import OpenAI
from diagnosis_engine import DiseaseDiagnosisAgent
from diagnosis_engine.vocabulary import map_to_known_symptoms, normalize_symptom
# ---------------------------------------------------------------------
# Environment
# ---------------------------------------------------------------------
# Load environment variables from likely .env locations relative to this file
BASE_DIR = Path(__file__).resolve().parent
ENV_CANDIDATES = [
BASE_DIR / ".env",
BASE_DIR.parent / ".env",
Path.cwd() / ".env",
]
for env_path in ENV_CANDIDATES:
if env_path.exists():
load_dotenv(env_path, override=False)
# Ensure OPENAI_API_KEY is set in the environment
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
searched = ", ".join(str(path) for path in ENV_CANDIDATES)
raise RuntimeError(
"OPENAI_API_KEY environment variable is not set. "
f"Add it to your environment or a .env file in one of these locations: {searched}"
)
# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)
# ---------------------------------------------------------------------
# Logging setup
# ---------------------------------------------------------------------
os.makedirs("logs", exist_ok=True)
# Set up a rotating file handler to keep logs manageable, and also log to console
handler = RotatingFileHandler("logs/app.log", maxBytes=2_000_000, backupCount=5)
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[handler, logging.StreamHandler()],
)
logger = logging.getLogger("medical_chatbot")
SAFE_ERROR_MESSAGE = (
"I couldn't complete your request. Please rephrase your symptoms, "
"ask for severity, or name a condition for description/precautions."
)
# ---------------------------------------------------------------------
# Metrics store
# ---------------------------------------------------------------------
# Track the number of calls to each agent and other relevant metrics for monitoring and analysis
METRICS = {
"diagnosis_calls": 0,
"severity_calls": 0,
"clarification_calls": 0,
"description_calls": 0,
"precaution_calls": 0,
}
# ---------------------------------------------------------------------
# ReAct prompt
# ---------------------------------------------------------------------
PLANNER_PROMPT = """
You are a medical triage planning assistant. Create a short execution plan using one or more of the available agents.
Available agents:
- clarification_agent -> {"user_symptoms": ["symptom_1", "symptom_2"]}
- disease_diagnosis -> {"user_symptoms": ["symptom_1", "symptom_2"]}
- symptom_severity -> {"user_symptoms": ["symptom_1", "symptom_2"]}
- disease_description -> {"disease": "disease_name"}
- precaution_advisor -> {"disease": "disease_name"}
Return JSON only with this exact schema:
{
"thought": "short planning rationale",
"steps": [
{
"agent": "clarification_agent | disease_diagnosis | symptom_severity | disease_description | precaution_advisor",
"reason": "why this step helps",
"input": {}
}
]
}
Rules:
- Include 1 to 3 steps.
- Use clarification_agent when symptoms are vague, too few, contradictory, or likely to need follow-up questions before diagnosis.
- Use symptom_severity when the user asks about urgency or symptoms sound clinically important.
- Use disease_diagnosis when the user provides symptoms and wants likely causes.
- Use disease_description and/or precaution_advisor when the user asks about a specific disease.
- For symptom-based questions, symptom lists must be arrays of strings.
- For disease-focused questions, disease must be a string.
- Never wrap the JSON in markdown fences.
"""
# ---------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------
DATA_DIR = BASE_DIR / "data"
# Paths to CSV dataset files
SYMPTOM_DISEASE_FILE = DATA_DIR / "dataset.csv"
SEVERITY_FILE = DATA_DIR / "Symptom-severity.csv"
DESCRIPTION_FILE = DATA_DIR / "symptom_Description.csv"
PRECAUTION_FILE = DATA_DIR / "symptom_precaution.csv"
# Verify that all required data files are present before starting the app
for path in [SYMPTOM_DISEASE_FILE, SEVERITY_FILE, DESCRIPTION_FILE, PRECAUTION_FILE]:
if not path.exists():
raise FileNotFoundError(f"Missing required data file: {path}")
# Set a threshold to identify urgent cases based on severity scores
SEVERITY_URGENT_THRESHOLD = 15
# Some symptoms should prompt an emergency message regardless of the overall score
EMERGENCY_SYMPTOMS = {
"chest_pain",
"breathlessness",
"shortness_of_breath",
}
# A standard message to show when urgent symptoms are detected
EMERGENCY_MESSAGE = (
"Urgent symptoms detected that could be a medical emergency. "
"Please seek immediate medical care now or call emergency services right away, especially "
"if symptoms are severe, worsening, or accompanied by sweating, fainting, confusion, or pain "
"spreading to the arm, back, jaw, or neck."
)
# Keywords that may indicate travel-related exposure, which can be relevant for certain diagnoses
TRAVEL_INDICATORS = [
"travel",
"traveled",
"abroad",
"trip",
"vacation",
"south africa",
"mosquito",
"exposure",
]
# Load the datasets
def load_datasets() -> Dict[str, pd.DataFrame]:
df_sd = pd.read_csv(SYMPTOM_DISEASE_FILE)
df_desc = pd.read_csv(DESCRIPTION_FILE)
df_prec = pd.read_csv(PRECAUTION_FILE)
df_sev = pd.read_csv(SEVERITY_FILE)
# Do preprocessing
df_sd["Disease"] = df_sd["Disease"].str.strip().str.lower()
df_desc["Disease"] = df_desc["Disease"].str.strip().str.lower()
df_prec["Disease"] = df_prec["Disease"].str.strip().str.lower()
df_sev["Symptom"] = df_sev["Symptom"].str.strip().str.lower()
# Return as a dictionary of DataFrames
return {
"symptom_disease": df_sd,
"description": df_desc,
"precaution": df_prec,
"severity": df_sev,
}
# Get a list of symptom columns (use on the symptom-disease dataset)
def extract_symptom_columns(df: pd.DataFrame) -> List[str]:
return [c for c in df.columns if c.lower() != "disease"]
# Normalize text by stripping whitespace and converting to lowercase, for consistent matching and logging
def normalize(text: str) -> str:
return re.sub(r"\s+", " ", text.strip().lower())
# Calculate a severity score by summing the weights of the user's symptoms based on the severity dataset
def severity_score(symptoms: List[str], df_sev: pd.DataFrame) -> int:
sev_map = dict(zip(df_sev["Symptom"], df_sev["weight"].astype(int)))
return sum(sev_map.get(s, 0) for s in symptoms)
# Redact text by hashing it and recording its length, to allow for logging without storing sensitive information
def redact_text(value: str) -> Dict[str, Any]:
normalized = (value or "").strip()
return {
"text_sha256": hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16],
"length": len(normalized),
}
# Extract a JSON object from text
def extract_json_object(text: str) -> Optional[Dict[str, Any]]:
if not text:
return None
# Normalize the text
stripped = text.strip()
if stripped.startswith("```"):
stripped = re.sub(r"^```(?:json)?\s*", "", stripped)
stripped = re.sub(r"\s*```$", "", stripped)
# First try to parse the entire text as JSON
try:
parsed = json.loads(stripped)
return parsed if isinstance(parsed, dict) else None
except Exception:
pass
# Identify the starting and ending braces of the JSON text
start = stripped.find("{")
end = stripped.rfind("}")
if start == -1 or end == -1 or end <= start:
return None
# Try to parse the substring that looks like JSON
try:
parsed = json.loads(stripped[start : end + 1])
return parsed if isinstance(parsed, dict) else None
except Exception:
return None
# Extract structured context from user input
def extract_structured_context(text: str, all_symptoms: List[str]) -> Dict[str, Any]:
lower = normalize(text)
context: Dict[str, Any] = {
"reported_symptoms": [],
"duration": None,
"progression": None,
"exposures": [],
}
# Get potential symptoms from the text by splitting on common delimiters and conjunctions
symptom_candidates = [
segment.strip()
for segment in re.split(r"[,\n]| and | but ", lower)
if segment.strip()
]
mapped = map_to_known_symptoms(symptom_candidates, all_symptoms)
# Also scan short n-grams from the whole sentence so symptoms embedded
# in natural phrasing like "I have fever and cough for 3 days" are captured.
tokens = re.findall(r"[a-z0-9]+", lower)
ngrams = []
for size in (1, 2, 3):
for idx in range(len(tokens) - size + 1):
ngrams.append(" ".join(tokens[idx : idx + size]))
# Get symptom matches using the ngrams
phrase_matches = map_to_known_symptoms(ngrams, all_symptoms)
# Combine and deduplicate symptoms from both matching lists
if phrase_matches:
mapped = list(dict.fromkeys(mapped + phrase_matches))
if mapped:
context["reported_symptoms"] = mapped
# Extract duration info using regex patterns - this will be used to give extra context to the diagnosis agent
duration_patterns = [
r"\bfor (\d+\s+(?:hour|hours|day|days|week|weeks|month|months))\b",
r"\bsince (yesterday|today|last night|this morning|\d+\s+(?:day|days|week|weeks|month|months)\s+ago)\b",
r"\bstarted (today|yesterday|last night|\d+\s+(?:hour|hours|day|days|week|weeks)\s+ago)\b",
]
# Check each pattern to see if it matches any duration information in the user's input
for pattern in duration_patterns:
match = re.search(pattern, lower)
if match:
context["duration"] = match.group(1)
break
# Extract symptom progression info - can help the diagnosis agent adjust symptom scores
progression_map = {
"worse": "worsening",
"worsening": "worsening",
"getting worse": "worsening",
"better": "improving",
"improving": "improving",
"same": "stable",
"unchanged": "stable",
"staying the same": "stable",
}
for phrase, label in progression_map.items():
if phrase in lower:
context["progression"] = label
break
# Extract exposure info based on keywords - helps the diagnosis agent consider rare diseases
# related to travel or specific exposures
exposure_keywords = {
"travel": ["travel", "traveled", "abroad", "trip", "vacation"],
"mosquito exposure": ["mosquito", "bug bites", "insect bites"],
"sick contacts": ["sick contact", "someone sick", "around sick people", "coworker was sick"],
"food exposure": ["new food", "undercooked", "restaurant", "takeout"],
"medication exposure": ["new medication", "started a medication", "antibiotic", "medicine"],
}
exposures = []
for label, keywords in exposure_keywords.items():
if any(keyword in lower for keyword in keywords):
exposures.append(label)
context["exposures"] = exposures
return context
# Merge structured context from multiple turns, give precedence to new info, but preserving all reported symptoms and exposure info
def merge_structured_context(existing: Optional[Dict[str, Any]], new: Optional[Dict[str, Any]]) -> Dict[str, Any]:
existing = existing or {}
new = new or {}
merged = {
"reported_symptoms": [],
"duration": new.get("duration") or existing.get("duration"),
"progression": new.get("progression") or existing.get("progression"),
"exposures": [],
}
# Combine and deduplicate symptoms
seen_symptoms = set()
for symptom in existing.get("reported_symptoms", []) + new.get("reported_symptoms", []):
if symptom not in seen_symptoms:
merged["reported_symptoms"].append(symptom)
seen_symptoms.add(symptom)
# Combine and deduplicate exposures
seen_exposures = set()
for exposure in existing.get("exposures", []) + new.get("exposures", []):
if exposure not in seen_exposures:
merged["exposures"].append(exposure)
seen_exposures.add(exposure)
return merged
# Format the structured context into a human-readable string to include in the LLM prompt
def format_structured_context_for_prompt(structured_context: Optional[Dict[str, Any]]) -> str:
context = structured_context or {}
lines = []
symptoms = context.get("reported_symptoms", [])
if symptoms:
lines.append("Known symptoms from prior turns: " + ", ".join(symptoms))
if context.get("duration"):
lines.append(f"Symptom duration: {context['duration']}")
if context.get("progression"):
lines.append(f"Symptom progression: {context['progression']}")
if context.get("exposures"):
lines.append("Relevant exposures: " + ", ".join(context["exposures"]))
return "\n".join(lines)
# ---------------------------------------------------------------------
# Agents
# ---------------------------------------------------------------------
# Symptom severity agent
class SymptomSeverityAgent:
name = "symptom_severity"
def __init__(self, df_sev: pd.DataFrame):
self.df = df_sev
def handle(self, user_symptoms: List[str], **kwargs) -> Dict[str, Any]:
# Increment the severity_calls metric each time this agent is invoked
METRICS["severity_calls"] += 1
# Calculate the severity score based on the user's symptoms and the severity dataset
score = severity_score(user_symptoms, self.df)
# Check for any red-flag symptoms that would indicate an urgent situation regardless of the overall score
matched_red_flags = sorted(set(user_symptoms).intersection(EMERGENCY_SYMPTOMS))
# Determine urgency based on the severity score and presence of red-flag symptoms
urgency = "urgent" if matched_red_flags or score >= SEVERITY_URGENT_THRESHOLD else "non-urgent"
return {
"severity_score": score,
"urgency": urgency,
"matched_red_flags": matched_red_flags,
}
# Clarification agent that asks follow-up questions when needed to improve diagnosis accuracy
class ClarificationAgent:
name = "clarification_agent"
# The clarification agent uses the diagnosis agent
def __init__(
self,
diagnosis_agent: DiseaseDiagnosisAgent,
symptom_df: pd.DataFrame,
symptom_cols: List[str],
):
self.diagnosis_agent = diagnosis_agent
self.df = symptom_df
self.symptom_cols = symptom_cols
# Get the list of symptoms associated with a candidate disease from the dataset
def _candidate_symptoms(self, disease: str) -> List[str]:
row = self.df[self.df["Disease"] == normalize(disease)]
if row.empty:
return []
first = row.iloc[0]
return [
str(first[col]).strip()
for col in self.symptom_cols
if pd.notna(first[col]) and str(first[col]).strip()
]
# Generate follow-up questions based on the top candidate diseases and their associated symptoms
def _follow_up_questions(
self,
user_symptoms: List[str],
candidates: List[Dict[str, Any]],
) -> List[str]:
symptom_set = set(user_symptoms)
symptom_counts: Dict[str, int] = {}
for candidate in candidates[:3]:
for symptom in self._candidate_symptoms(candidate["disease"]):
if symptom not in symptom_set:
symptom_counts[symptom] = symptom_counts.get(symptom, 0) + 1
ranked = sorted(
symptom_counts.items(),
key=lambda item: (item[1], len(item[0]), item[0]),
reverse=True,
)
questions = [
f"Are you also experiencing {symptom.replace('_', ' ')}?"
for symptom, _ in ranked[:4]
]
questions.extend(
[
"How long have these symptoms been present?",
"Have your symptoms been getting worse, staying the same, or improving?",
"Any recent travel, sick contacts, or new food or medication exposure?",
]
)
deduped = []
seen = set()
for question in questions:
if question not in seen:
deduped.append(question)
seen.add(question)
return deduped[:5]
# Rerank candidate diseases using the LLM when the initial scores are close or there is uncertainty
def handle(self, user_symptoms: List[str], **kwargs) -> Dict[str, Any]:
METRICS["clarification_calls"] += 1
# Extract structured context from the user's input to provide additional information to the diagnosis agent
structured_context = kwargs.get("structured_context") or {}
# Merge with any existing structured context to preserve information across turns
result = self.diagnosis_agent.handle(user_symptoms, travel_exposure=kwargs.get("travel_exposure", False))
candidates = result.get("diagnoses", [])
# Set the reason for whether or not clarification is needed
reason = "enough_signal"
needs_clarification = False
# We need at least 2 symptoms
if len(user_symptoms) < 2:
needs_clarification = True
reason = "too_few_symptoms"
# Check if we have any strong symptom matches
elif not candidates:
needs_clarification = True
reason = "no_strong_matches"
else:
# Get the score difference btw the top 2 candidates
top_score = candidates[0]["hybrid_score"]
second_score = candidates[1]["hybrid_score"] if len(candidates) > 1 else 0.0
score_gap = top_score - second_score
# If the top score is low or the score gap is small, request clarification
if top_score < 0.25:
needs_clarification = True
reason = "weak_match"
elif score_gap < 0.08:
needs_clarification = True
reason = "top_candidates_too_close"
# Give the LLM extra context (symptom duration, progression, exposures) to help determine if clarification is needed)
context_bonus = sum(
1
for value in [
structured_context.get("duration"),
structured_context.get("progression"),
bool(structured_context.get("exposures")),
]
if value
)
if needs_clarification and context_bonus >= 2 and len(user_symptoms) >= 2 and candidates:
if candidates[0]["hybrid_score"] >= 0.22:
needs_clarification = False
reason = "context_resolved"
return {
"needs_clarification": needs_clarification,
"reason": reason,
"questions": self._follow_up_questions(user_symptoms, candidates),
"candidate_preview": [
{
"disease": item["disease"],
"hybrid_score": item["hybrid_score"],
}
for item in candidates[:3]
],
}
# Disease description agent
class DiseaseDescriptionAgent:
name = "disease_description"
def __init__(self, df_desc: pd.DataFrame):
self.df = df_desc
def handle(self, disease: str) -> Dict[str, Any]:
# Increment the description_calls metric each time this agent is invoked
METRICS["description_calls"] += 1
# Look up the disease in the description dataset and return its description, or a default message if not found
row = self.df[self.df["Disease"] == normalize(disease)]
if row.empty:
return {"description": "No description found."}
return {"description": row["Description"].iloc[0]}
# Precaution advisor agent
class PrecautionAdvisorAgent:
name = "precaution_advisor"
def __init__(self, df_prec: pd.DataFrame):
self.df = df_prec
def handle(self, disease: str) -> Dict[str, Any]:
# Increment the precaution_calls metric each time this agent is invoked
METRICS["precaution_calls"] += 1
# Look up the disease in the precaution dataset and return a list of precautions, or an empty list if not found
row = self.df[self.df["Disease"] == normalize(disease)]
if row.empty:
return {"precautions": []}
# Extract all columns that start with "precaution" and have non-empty values, and return them as a list
first = row.iloc[0]
precautions = [
str(first[c]).strip()
for c in first.index
if c.lower().startswith("precaution")
and pd.notna(first[c])
and str(first[c]).strip()
]
return {"precautions": precautions}
# ---------------------------------------------------------------------
# ReAct Router
# ---------------------------------------------------------------------
# The ReActRouter class takes the user's input and conversation history, constructs a prompt for the LLM,
# and parses the LLM's response to determine which agent to call and with what payload. It also includes logic to handle
# symptom normalization and mapping, as well as special handling for travel-related symptoms in the diagnosis agent.
class ReActRouter:
def __init__(self, agents: Dict[str, Any], all_symptoms: List[str]):
self.agents = agents
self.all_symptoms = all_symptoms
# Build the messages for the LLM by taking the recent conversation history and appending the user's current input,
# while ensuring that only relevant roles and content are included.
def _build_messages(
self,
user_input: str,
history: List[Dict[str, str]],
structured_context: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, str]]:
recent_history = history[-6:] if history else []
messages = [{"role": "system", "content": PLANNER_PROMPT}]
context_note = format_structured_context_for_prompt(structured_context)
if context_note:
messages.append(
{
"role": "system",
"content": "Structured context from earlier turns:\n" + context_note,
}
)
for item in recent_history:
role = item.get("role")
content = item.get("content", "")
if role in {"user", "assistant"} and content:
messages.append({"role": role, "content": content})
messages.append({"role": "user", "content": user_input})
return messages
# Call the LLM to get a plan
def llm_plan(
self,
user_input: str,
history: List[Dict[str, str]],
structured_context: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
# Log the input to the router
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=self._build_messages(user_input, history, structured_context),
temperature=0,
)
text = resp.choices[0].message.content or ""
# Log the raw output from the LLM, with redactions
logger.info(json.dumps({
"event": "router_llm_output",
"output_hash": redact_text(text),
}))
parsed = extract_json_object(text)
if not parsed:
logger.error(f"Router could not parse structured JSON. Raw output:\n{text}")
return self._fallback_plan(user_input, structured_context)
steps = parsed.get("steps", [])
if not isinstance(steps, list) or not steps:
logger.error("Planner steps were missing or invalid.")
return self._fallback_plan(user_input, structured_context)
# Normalize and validate the steps to ensure they conform to the expected schema, and log any issues
normalized_steps = []
for step in steps[:3]:
if not isinstance(step, dict):
continue
agent_name = str(step.get("agent", "")).strip()
payload = step.get("input", {})
reason = str(step.get("reason", "")).strip()
if not agent_name or not isinstance(payload, dict):
continue
normalized_steps.append(
{"agent": agent_name, "payload": payload, "reason": reason}
)
if not normalized_steps:
logger.error("Planner returned no valid steps.")
return self._fallback_plan(user_input, structured_context)
logger.info(json.dumps({
"event": "planner_parsed",
"step_count": len(normalized_steps),
"agents": [step["agent"] for step in normalized_steps],
}))
return {"steps": normalized_steps}
# If the LLM fails to produce a valid plan, use heuristic rules to create a fallback plan based on symptom keywords and disease mentions
def _fallback_plan(
self,
user_input: str,
structured_context: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
lower = user_input.lower()
# Split the input into parts, normalize them
normalized_tokens = [normalize_symptom(part) for part in re.split(r"[,\n]| and ", lower) if part.strip()]
mapped = map_to_known_symptoms(normalized_tokens, self.all_symptoms)
structured_context = structured_context or {}
# If no symptoms were mapped, check the context for previous symptoms from earlier turns
if not mapped and structured_context.get("reported_symptoms"):
mapped = structured_context["reported_symptoms"]
# Look for disease mentions in the input to trigger description or precaution agents
disease_match = re.search(r"(?:what is|describe|tell me about|precautions for)\s+([a-zA-Z\s\-]+)", lower)
steps: List[Dict[str, Any]] = []
# Check if the user is asking about symptoms urgency or severity
if any(term in lower for term in ["how urgent", "severity", "serious", "emergency"]):
# If we have mapped symptoms, call the symptom severity agent to evaluate
if mapped:
return {"steps": [{"agent": "symptom_severity", "payload": {"user_symptoms": mapped}, "reason": "Assess clinical urgency."}]}
return {"error": SAFE_ERROR_MESSAGE}
# If we have mapped symptoms, add steps for clarification, severity, and diagnosis agents to the plan
if mapped:
steps.append(
{"agent": "clarification_agent", "payload": {"user_symptoms": mapped}, "reason": "Check whether follow-up questions are needed before diagnosis."}
)
steps.append(
{"agent": "symptom_severity", "payload": {"user_symptoms": mapped}, "reason": "Assess urgency for the same symptom set."}
)
steps.append(
{"agent": "disease_diagnosis", "payload": {"user_symptoms": mapped}, "reason": "Find likely conditions from symptoms if the evidence is specific enough."}
)
return {"steps": steps[:3]}
if disease_match:
# Normalize the disease match info
disease = normalize(disease_match.group(1))
# If the user asked about precautions, call the precaution advisor agent
if "precaution" in lower:
steps.append(
{"agent": "precaution_advisor", "payload": {"disease": disease}, "reason": "Provide basic safety guidance."}
)
else:
# Add steps to call the disease description and precaution agents
steps.append(
{"agent": "disease_description", "payload": {"disease": disease}, "reason": "Explain the named condition."}
)
steps.append(
{"agent": "precaution_advisor", "payload": {"disease": disease}, "reason": "Provide basic safety guidance."}
)
return {"steps": steps}
return {"error": SAFE_ERROR_MESSAGE}
# The main method for generating a plan to produce a response to user input
def plan(
self,
user_input: str,
history: List[Dict[str, str]],
structured_context: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
parsed = self.llm_plan(user_input, history, structured_context)
if "error" in parsed:
return parsed
structured_context = structured_context or {}
# Set a flag to indicate if the user has mentioned travel or exposure that could make certain diseases more likely
travel_exposure_flag = (
any(token in user_input.lower() for token in TRAVEL_INDICATORS)
or any("travel" in exposure or "mosquito" in exposure for exposure in structured_context.get("exposures", []))
)
executable_steps = []
# Iterate through the steps
for step in parsed["steps"]:
agent_name = step["agent"]
payload = dict(step["payload"])
if agent_name not in self.agents:
logger.error(f"Unknown agent in plan: {agent_name}")
continue
# Extract any symptoms in the payload and map to known symptoms
if "user_symptoms" in payload:
raw_symptoms = payload["user_symptoms"]
if not isinstance(raw_symptoms, list):
continue
normalized = [normalize_symptom(s) for s in raw_symptoms]
mapped = map_to_known_symptoms(normalized, self.all_symptoms)
logger.info(json.dumps({
"event": "planner_mapped_symptoms",
"agent": agent_name,
"mapped_count": len(mapped),
}))
if not mapped:
continue
payload["user_symptoms"] = mapped
# Pass in payload data to help with diagnosis and clarification
if agent_name == "disease_diagnosis":
payload["travel_exposure"] = travel_exposure_flag
if agent_name == "clarification_agent":
payload["structured_context"] = structured_context
executable_steps.append(
{"agent": agent_name, "payload": payload, "reason": step.get("reason", "")}
)
# If no steps were added, return an appropriate message to the user
if not executable_steps:
if travel_exposure_flag:
return {
"diagnoses": [],
"message": "It looks like you mentioned travel or exposure but did not describe symptoms. Please specify symptoms such as fever, rash, or cough.",
}
return {
"diagnoses": [],
"message": "No recognizable symptoms were detected. Please describe your symptoms in more detail, such as fever, headache, or cough.",
}
return {"steps": executable_steps}
# ---------------------------------------------------------------------
# App
# ---------------------------------------------------------------------
# The MedicalChatbotApp class initializes the agents, loads the datasets, and sets up the Gradio interface.
class MedicalChatbotApp:
def __init__(self):
self.client = OpenAI(api_key=OPENAI_API_KEY)
self.data = load_datasets()
self.symptom_cols = extract_symptom_columns(self.data["symptom_disease"])
# Define the diagnosis agent
diagnosis_agent = DiseaseDiagnosisAgent(
df=self.data["symptom_disease"], # Symptom-disease dataset
client=self.client,
llm_model="gpt-4o-mini", # Use a smaller model to reduce latency
top_k_faiss=10, # Pulling top 10 is reasonable given the total disease count of 41 in the dataset
)
self.all_symptoms = diagnosis_agent.all_symptoms
# Create a disease description lookup dict using the description dataset (makes later lookups faster)
self.disease_description_lookup = {
row["Disease"]: row["Description"]
for _, row in self.data["description"].drop_duplicates(subset=["Disease"]).iterrows()
}
# Create a disease precaution lookup dict using the precaution dataset (makes later lookups faster)
self.disease_precaution_lookup = {}
for _, row in self.data["precaution"].drop_duplicates(subset=["Disease"]).iterrows():
disease = row["Disease"]
precautions = [
str(row[col]).strip()
for col in row.index
if col.lower().startswith("precaution")
and pd.notna(row[col])
and str(row[col]).strip()
]
self.disease_precaution_lookup[disease] = precautions
# Create a disease symptom lookup dict using the symptom-disease dataset (makes later lookups faster)
self.disease_symptom_lookup = {}
for _, row in self.data["symptom_disease"].iterrows():
disease = row["Disease"]
self.disease_symptom_lookup[disease] = [
str(row[col]).strip()
for col in self.symptom_cols
if pd.notna(row[col]) and str(row[col]).strip()
]
# Initialize the agents and the router
self.agents = {
"clarification_agent": ClarificationAgent(
diagnosis_agent=diagnosis_agent,
symptom_df=self.data["symptom_disease"],
symptom_cols=self.symptom_cols,
),
"disease_diagnosis": diagnosis_agent,
"symptom_severity": SymptomSeverityAgent(self.data["severity"]),
"disease_description": DiseaseDescriptionAgent(self.data["description"]),
"precaution_advisor": PrecautionAdvisorAgent(self.data["precaution"]),
}
self.router = ReActRouter(self.agents, self.all_symptoms)
# Build a log payload
def _build_log_payload(self, user_input: str, routed: Dict[str, Any], latency: int) -> Dict[str, Any]:
return {
"timestamp": time.time(),
"user_input": redact_text(user_input),
"response_shape": sorted(routed.keys()),
"routed_agent": routed.get("agent"),
"planned_agents": [step["agent"] for step in routed.get("steps", [])] if isinstance(routed.get("steps"), list) else None,
"metrics": {
"diagnosis_calls": METRICS["diagnosis_calls"],
"severity_calls": METRICS["severity_calls"],
"clarification_calls": METRICS["clarification_calls"],
"description_calls": METRICS["description_calls"],
"precaution_calls": METRICS["precaution_calls"],
},
"latency_ms": latency,
}
# Format the severity assessment answer based on the severity score, urgency level, and any matched
# red-flag symptoms
def _format_severity_answer(
self,
score: Optional[int],
urgency: Optional[str],
matched_red_flags: Optional[List[str]] = None,
) -> str:
severity_level = urgency.upper() if isinstance(urgency, str) else urgency
recommendation = "recommended" if urgency == "urgent" else "not required urgently"
red_flag_note = ""
# If red flags were found, generate a note listing the red-flag symptoms
if matched_red_flags:
pretty_flags = ", ".join(symptom.replace("_", " ") for symptom in matched_red_flags)
red_flag_note = f"\nRed-flag symptoms detected: {pretty_flags}."
return (
"Clinical urgency assessment:\n"
f"- Severity score: {score} (threshold: {SEVERITY_URGENT_THRESHOLD})\n"
f"- Triage level: {severity_level}\n"
"Based on your symptoms, this indicates that immediate medical attention is "
f"{recommendation}.{red_flag_note}\n"
"Please consult a healthcare provider for evaluation and next steps."
)
# Format the diagnosis answer
def _format_diagnosis_answer(
self,
diagnosis_input: List[str],
result: Dict[str, Any],
severity_result: Optional[Dict[str, Any]] = None,
) -> str:
if not result.get("diagnoses"):
return result.get("message", "No recognizable symptoms were detected.")
# Get the top hybrid score from the diagnoses
top_score = result["diagnoses"][0]["hybrid_score"]
# Set a minimum score threshold to filter the diagnoses (0.10),
# but ensure that at least one diagnosis is included even if the scores are low
min_score = max(0.10, 0.5 * top_score)
filtered_diagnoses = [item for item in result["diagnoses"] if item["hybrid_score"] >= min_score]
if not filtered_diagnoses:
filtered_diagnoses = [result["diagnoses"][0]]
# Get the result from the symptom severity agent
severity_result = severity_result or self.agents["symptom_severity"].handle(diagnosis_input)
text = (
"## Clinical Summary\n"
f"- Symptom set: {', '.join(s.replace('_', ' ') for s in diagnosis_input)}\n"
f"- Severity score: {severity_result['severity_score']} (threshold: {SEVERITY_URGENT_THRESHOLD})\n"
f"- Triage level: {severity_result['urgency'].upper()}\n\n"
)
# If the top score is below a certain threshold, include a note that the matches are weak and
# that additional symptoms could help narrow down the possibilities. This helps set expectations
# for the user about the confidence of the diagnosis and encourages them to provide more information if possible.
if top_score < 0.25:
text += "We found possible matches based on your symptoms, but none are strong matches.\n\n"
text += "## Top Matching Conditions\n\n"
# For each filtered diagnosis, look up its description and precautions, and also determine which
# symptoms matched between the user's input and the symptoms associated with that disease in the dataset.
for rank, item in enumerate(filtered_diagnoses, start=1):
disease = item["disease"]
description = self.disease_description_lookup.get(disease, "No description found.")
precautions_list = self.disease_precaution_lookup.get(disease, [])
precautions = ", ".join(precautions_list) if precautions_list else "No specific precautions listed."
# Look up the symptoms associated with this disease in the symptom-disease dataset,
# and determine which of those symptoms match the user's input.
disease_symptoms = self.disease_symptom_lookup.get(disease, [])
if disease_symptoms:
matched = set(diagnosis_input).intersection(set(disease_symptoms))
matched_text = ", ".join(s.replace("_", " ") for s in sorted(matched)) if matched else "No direct matches"
else:
matched_text = "No symptom data available"
text += f"### {rank}. {disease.title()}\n"
text += f"- Match strength: {item['hybrid_score']:.2f}\n"
text += f"- Matched symptoms: {matched_text}\n"
text += f"- Description: {description}\n"
text += f"- Precautions: {precautions}\n\n"
# Give the user a message based on the urgency of the symptoms
if severity_result["urgency"] == "urgent":
text += "Given the urgent severity, please seek immediate medical attention.\n\n"
else:
text += "Please consult a healthcare professional for accurate diagnosis and appropriate treatment.\n\n"
# Give a special message if the user mentioned travel or exposure
if result.get("tropical_diseases_present", False):
text += (
"**Important Note**: One or more listed conditions are typically linked to international travel. "
"If you have not traveled recently, those options are much less likely.\n\n"
)
# If the confidence of the matches is low, prompt for more symptoms
if top_score < 0.25:
text += (
"Additional symptoms (i.e. body ache, sore throat, nausea, or shortness of breath) "
"could help narrow down the possibilities."
)
return text.strip()
# Format the clarification questions into a readable format for the user
def _render_session_summary(
self,
symptom_context: List[str],
last_diagnoses: List[Dict[str, Any]],
structured_context: Optional[Dict[str, Any]] = None,
) -> str:
structured_context = structured_context or {}
# If there are no symptoms or diagnoses or structured context yet, show a blank, default summary
if not symptom_context and not last_diagnoses and not format_structured_context_for_prompt(structured_context):
return (
"## Session Summary\n"
"- Symptoms tracked: none yet\n"
"- Latest matches: none yet\n"
"- Structured context: none yet"
)
# Format symptoms, diagnoses, and context for presentation to the user
symptom_text = ", ".join(s.replace("_", " ") for s in symptom_context) if symptom_context else "none yet"
diagnosis_text = ", ".join(item["disease"].title() for item in last_diagnoses[:3]) if last_diagnoses else "none yet"
context_parts = []
if structured_context.get("duration"):
context_parts.append(f"duration {structured_context['duration']}")
if structured_context.get("progression"):
context_parts.append(f"progression {structured_context['progression']}")
if structured_context.get("exposures"):
context_parts.append("exposures " + ", ".join(structured_context["exposures"]))
context_text = "; ".join(context_parts) if context_parts else "none yet"
return (
"## Session Summary\n"
f"- Symptoms tracked: {symptom_text}\n"
f"- Latest matches: {diagnosis_text}\n"
f"- Structured context: {context_text}"
)
# Render a clinical summary card - this gives a comprehensive overview of the session for the user
def _render_result_card(
self,
symptom_context: List[str],
last_diagnoses: List[Dict[str, Any]],
severity_result: Optional[Dict[str, Any]],
plan_trace: List[Dict[str, str]],
clarification_result: Optional[Dict[str, Any]],
structured_context: Optional[Dict[str, Any]],
) -> str:
structured_context = structured_context or {}
# Format symptoms for display in the card
symptoms_html = "".join(
f"<span class='chip'>{html.escape(symptom.replace('_', ' '))}</span>"
for symptom in symptom_context[:8]
) or "<span class='muted'>No symptoms tracked yet.</span>"
# Format severity for disply in the card
severity_html = "<span class='muted'>No severity assessment yet.</span>"
if severity_result:
badge_class = "badge urgent" if severity_result.get("urgency") == "urgent" else "badge nonurgent"
severity_html = (
f"<div class='{badge_class}'>{html.escape(severity_result.get('urgency', 'unknown').upper())}</div>"
f"<p>Severity score: <strong>{severity_result.get('severity_score', 'n/a')}</strong></p>"
)
# Format diseases diagnoses for display in the card
diagnosis_items = ""
for item in last_diagnoses[:3]:
diagnosis_items += (
"<div class='result-item'>"
f"<div class='result-title'>{html.escape(item['disease'].title())}</div>"
f"<div class='result-meta'>Match strength: {item['hybrid_score']:.2f}</div>"
"</div>"
)
if not diagnosis_items:
diagnosis_items = "<div class='muted'>No diagnosis results yet.</div>"
# Format the structured context for display in the card
structured_context_html = []
if structured_context.get("duration"):
structured_context_html.append(f"<div class='result-meta'>Duration: {html.escape(structured_context['duration'])}</div>")
if structured_context.get("progression"):
structured_context_html.append(f"<div class='result-meta'>Progression: {html.escape(structured_context['progression'])}</div>")
if structured_context.get("exposures"):
structured_context_html.append(
f"<div class='result-meta'>Exposures: {html.escape(', '.join(structured_context['exposures']))}</div>"
)
context_html = "".join(structured_context_html) or "<div class='muted'>No structured context captured yet.</div>"
# Format clarification/additional questions for disply in the card
clarification_html = "<div class='muted'>No follow-up questions pending.</div>"
if clarification_result and clarification_result.get("needs_clarification"):
question_items = "".join(
f"<li>{html.escape(question)}</li>"
for question in clarification_result.get("questions", [])
)
clarification_html = (
f"<div class='result-meta'>Reason: {html.escape(clarification_result.get('reason', 'needs more detail'))}</div>"
f"<ul class='plan-list'>{question_items}</ul>"
)
# Format the planner trace for display in the card
plan_items = "".join(
"<li>"
f"<strong>{html.escape(step['agent'])}</strong>: {html.escape(step.get('reason', ''))}"
"</li>"
for step in plan_trace
) or "<li>No planner steps yet.</li>"
return (
"<div class='clinical-card'>"
"<div class='card-section'>"
"<div class='card-title'>Tracked Symptoms</div>"
f"<div class='chip-row'>{symptoms_html}</div>"
"</div>"
"<div class='card-section'>"
"<div class='card-title'>Urgency</div>"
f"{severity_html}"
"</div>"
"<div class='card-section'>"
"<div class='card-title'>Top Matches</div>"
f"{diagnosis_items}"
"</div>"
"<div class='card-section'>"
"<div class='card-title'>Structured Context</div>"
f"{context_html}"
"</div>"
"<div class='card-section'>"
"<div class='card-title'>Follow-Up Questions</div>"
f"{clarification_html}"
"</div>"
"<div class='card-section'>"
"<div class='card-title'>Planner Trace</div>"
f"<ol class='plan-list'>{plan_items}</ol>"
"</div>"
"</div>"
)
# Format the emergency answer
def _format_emergency_answer(self, matched_red_flags: List[str]) -> str:
pretty_flags = ", ".join(symptom.replace("_", " ") for symptom in matched_red_flags)
return (
f"{EMERGENCY_MESSAGE}\n\n"
f"Detected red-flag symptoms: {pretty_flags}.\n"
"This app should not be used to rule out serious causes of these symptoms."
)
# Format the clarification answer
def _format_clarification_answer(self, clarification_result: Dict[str, Any]) -> str:
reason_map = {
"too_few_symptoms": "I need a bit more detail before ranking possible conditions.",
"no_strong_matches": "Your current symptom list does not map strongly to the dataset yet.",
"weak_match": "The current matches are too weak to present confidently.",
"top_candidates_too_close": "Several conditions are currently too close to separate confidently.",
}
intro = reason_map.get(
clarification_result.get("reason"),
"I need a bit more detail before I can narrow this down reliably.",
)
questions = clarification_result.get("questions", [])
lines = "\n".join(f"- {question}" for question in questions[:5])
return (
"## Follow-Up Questions\n"
f"{intro}\n\n"
"Please answer a few of these:\n"
f"{lines}\n\n"
"Once you answer, I can refine the urgency assessment and possible matches."
)
# Execute the plan
def _execute_plan(
self,
planned: Dict[str, Any],
symptom_context: List[str],
structured_context: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
structured_context = structured_context or {}
if "error" in planned:
return {"error": planned["error"], "symptom_context": symptom_context, "structured_context": structured_context, "plan_trace": [], "last_diagnoses": [], "severity_result": None}
if "diagnoses" in planned and "message" in planned:
return {
"answer": planned["message"],
"symptom_context": symptom_context,
"structured_context": structured_context,
"plan_trace": [],
"last_diagnoses": [],
"severity_result": None,
}
diagnosis_result = None
severity_result = None
clarification_result = None
disease_details: Dict[str, Dict[str, Any]] = {}
plan_trace: List[Dict[str, str]] = []
# Iterate through the planned steps
for step in planned.get("steps", []):
agent_name = step["agent"]
payload = dict(step["payload"])
plan_trace.append({"agent": agent_name, "reason": step.get("reason", "")})
if (
agent_name == "disease_diagnosis"
and clarification_result
and clarification_result.get("needs_clarification")
):
continue
if agent_name in {"clarification_agent", "disease_diagnosis", "symptom_severity"}:
step_symptoms = payload.get("user_symptoms", [])
if step_symptoms:
symptom_context = sorted(set(symptom_context).union(step_symptoms))
payload["user_symptoms"] = symptom_context
if agent_name == "disease_diagnosis":
payload["structured_context"] = structured_context
result = self.agents[agent_name].handle(**payload)
if agent_name == "clarification_agent":
clarification_result = result
elif agent_name == "disease_diagnosis":
diagnosis_result = result
elif agent_name == "symptom_severity":
severity_result = result
else:
disease_key = normalize(payload.get("disease", ""))
disease_details.setdefault(disease_key, {}).update(result)
if (
agent_name == "symptom_severity"
and severity_result
and severity_result.get("matched_red_flags")
):
break
if severity_result and severity_result.get("matched_red_flags"):
return {
"answer": self._format_emergency_answer(severity_result["matched_red_flags"]),
"symptom_context": symptom_context,
"structured_context": structured_context,
"plan_trace": plan_trace,
"last_diagnoses": [],
"severity_result": severity_result,
"clarification_result": clarification_result,
}
if clarification_result and clarification_result.get("needs_clarification"):
return {
"answer": self._format_clarification_answer(clarification_result),
"symptom_context": symptom_context,
"structured_context": structured_context,
"plan_trace": plan_trace,
"last_diagnoses": [],
"severity_result": severity_result,
"clarification_result": clarification_result,
}
if diagnosis_result:
answer = self._format_diagnosis_answer(symptom_context, diagnosis_result, severity_result)
return {
"answer": answer,
"symptom_context": symptom_context,
"structured_context": structured_context,
"plan_trace": plan_trace,
"last_diagnoses": diagnosis_result.get("diagnoses", []),
"severity_result": severity_result,
"clarification_result": clarification_result,
}
if severity_result:
answer = self._format_severity_answer(
severity_result.get("severity_score"),
severity_result.get("urgency"),
severity_result.get("matched_red_flags"),
)
return {
"answer": answer,
"symptom_context": symptom_context,
"structured_context": structured_context,
"plan_trace": plan_trace,
"last_diagnoses": [],
"severity_result": severity_result,
"clarification_result": clarification_result,
}
if disease_details:
disease_name = next(iter(disease_details))
detail = disease_details[disease_name]
description = detail.get("description", "No description found.")
precautions = detail.get("precautions", [])
precaution_text = ", ".join(precautions) if precautions else "No specific precautions listed."
answer = (
f"## Condition Overview\n"
f"- Disease: {disease_name.title()}\n"
f"- Description: {description}\n"
f"- Precautions: {precaution_text}\n\n"
"Please consult a healthcare professional for diagnosis and treatment."
)
return {
"answer": answer,
"symptom_context": symptom_context,
"structured_context": structured_context,
"plan_trace": plan_trace,
"last_diagnoses": [],
"severity_result": None,
"clarification_result": clarification_result,
}
return {
"error": SAFE_ERROR_MESSAGE,
"symptom_context": symptom_context,
"structured_context": structured_context,
"plan_trace": plan_trace,
"last_diagnoses": [],
"severity_result": severity_result,
"clarification_result": clarification_result,
}
# The main chat method
def chat(self, user_input: str, session_state: Optional[Dict[str, Any]] = None):
try:
session_state = session_state or {}
history = session_state.get("messages", [])
symptom_context = session_state.get("symptom_context", [])
last_diagnoses = session_state.get("last_diagnoses", [])
last_severity = session_state.get("last_severity")
last_plan_trace = session_state.get("last_plan_trace", [])
last_clarification = session_state.get("last_clarification")
structured_context = session_state.get("structured_context", {})
turn_context = extract_structured_context(user_input, self.all_symptoms)
structured_context = merge_structured_context(structured_context, turn_context)
if turn_context.get("reported_symptoms"):
symptom_context = sorted(set(symptom_context).union(turn_context["reported_symptoms"]))
# Record the start time
start = time.time()
planned = self.router.plan(user_input, history, structured_context)
latency = int((time.time() - start) * 1000)
logger.info(json.dumps(self._build_log_payload(user_input, planned, latency)))
executed = self._execute_plan(planned, symptom_context, structured_context)
answer = executed.get("answer") or executed.get("error", SAFE_ERROR_MESSAGE)
symptom_context = executed.get("symptom_context", symptom_context)
structured_context = executed.get("structured_context", structured_context)
last_diagnoses = executed.get("last_diagnoses", last_diagnoses)
last_severity = executed.get("severity_result", last_severity)
last_plan_trace = executed.get("plan_trace", last_plan_trace)
last_clarification = executed.get("clarification_result", last_clarification)
history = history + [
{"role": "user", "content": user_input},
{"role": "assistant", "content": answer},
]
updated_state = {
"messages": history,
"symptom_context": symptom_context,
"last_diagnoses": last_diagnoses,
"last_severity": last_severity,
"last_plan_trace": last_plan_trace,
"last_clarification": last_clarification,
"structured_context": structured_context,
}
summary = self._render_session_summary(symptom_context, last_diagnoses, structured_context)
# Get the HTML formatted result card to give a comprehensive overview of the session for the user
card_html = self._render_result_card(
symptom_context,
last_diagnoses,
last_severity,
last_plan_trace,
last_clarification,
structured_context,
)
return history, updated_state, summary, card_html
# Catch any unexpected exceptions, log the error, and return an error message to the user
except Exception as exc:
logger.error(f"Error in chat: {exc}")
error_msg = (
"I hit an internal error while processing that request. "
"Please try again with a short symptom list like `fever, cough, fatigue`."
)
session_state = session_state or {}
history = session_state.get("messages", [])
history = history + [
{"role": "user", "content": user_input},
{"role": "assistant", "content": error_msg},
]
updated_state = {
"messages": history,
"symptom_context": session_state.get("symptom_context", []),
"last_diagnoses": session_state.get("last_diagnoses", []),
"last_severity": session_state.get("last_severity"),
"last_plan_trace": session_state.get("last_plan_trace", []),
"last_clarification": session_state.get("last_clarification"),
"structured_context": session_state.get("structured_context", {}),
}
summary = self._render_session_summary(
updated_state["symptom_context"],
updated_state["last_diagnoses"],
updated_state.get("structured_context", {}),
)
card_html = self._render_result_card(
updated_state["symptom_context"],
updated_state["last_diagnoses"],
updated_state.get("last_severity"),
updated_state.get("last_plan_trace", []),
updated_state.get("last_clarification"),
updated_state.get("structured_context", {}),
)
return history, updated_state, summary, card_html
# Launch the Gradio interface
def launch(self):
custom_css = """
.app-shell {max-width: 1280px; margin: 0 auto;}
.hero {padding: 18px 20px; border-radius: 18px; background: linear-gradient(135deg, #f6f1df, #dceef5); border: 1px solid #d9d1b5;}
.clinical-card {background: #fffdf7; border: 1px solid #d8d1bf; border-radius: 18px; padding: 18px; box-shadow: 0 10px 30px rgba(60, 52, 33, 0.08);}
.card-section {margin-bottom: 16px;}
.card-title {font-size: 0.85rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: #7a6440; margin-bottom: 8px;}
.chip-row {display: flex; flex-wrap: wrap; gap: 8px;}
.chip {display: inline-block; background: #efe6cf; color: #4f4027; padding: 6px 10px; border-radius: 999px; font-size: 0.92rem;}
.badge {display: inline-block; padding: 7px 12px; border-radius: 999px; font-weight: 700; margin-bottom: 10px;}
.badge.urgent {background: #f6d2c9; color: #8a2410;}
.badge.nonurgent {background: #dcefdc; color: #1f6134;}
.result-item {padding: 10px 0; border-top: 1px solid #ece4d1;}
.result-item:first-child {border-top: 0;}
.result-title {font-weight: 700; color: #2d2418;}
.result-meta, .muted {color: #6d6559;}
.plan-list {margin: 0; padding-left: 18px;}
"""
with gr.Blocks(title="MediBot - Disease & Symptom Assistant") as demo:
gr.Markdown(
"""
<div class="app-shell">
<div class="hero">
<h1>MediBot - Disease & Symptom Assistant</h1>
<p>Describe symptoms in plain language, ask about urgency, or request condition details. Results are educational and should be confirmed by a healthcare professional.</p>
</div>
</div>
"""
)
with gr.Row():
with gr.Column(scale=7):
chatbot = gr.Chatbot(height=520)
user_box = gr.Textbox(
label="Tell me your symptoms",
placeholder="e.g., fever, headache, chills, fatigue",
scale=8,
)
with gr.Column(scale=5):
summary = gr.Markdown(self._render_session_summary([], [], {}))
result_card = gr.HTML(self._render_result_card([], [], None, [], None, {}))
state = gr.State(
{
"messages": [],
"symptom_context": [],
"last_diagnoses": [],
"last_severity": None,
"last_plan_trace": [],
"last_clarification": None,
"structured_context": {},
}
)
# Handle user input from the chat
def respond(msg, st):
hist, next_state, summary_text, card_html = self.chat(msg, st)
return "", hist, next_state, summary_text, card_html
# Start a new chat and clear out all session tracking objects
def new_chat():
empty_state = {
"messages": [],
"symptom_context": [],
"last_diagnoses": [],
"last_severity": None,
"last_plan_trace": [],
"last_clarification": None,
"structured_context": {},
}
return [], empty_state, self._render_session_summary([], [], {}), self._render_result_card([], [], None, [], None, {})
# Submit the user's input
user_box.submit(respond, [user_box, state], [user_box, chatbot, state, summary, result_card])
send_button = gr.Button("Send")
send_button.click(respond, [user_box, state], [user_box, chatbot, state, summary, result_card])
# Add example buttons for quick testing of different symptom scenarios
gr.Examples(
examples=[
"I have fever, headache, chills, and fatigue. What could it be?",
"I also have nausea and joint pain.",
"Sore throat, runny nose, mild cough for 2 days.",
"Chest pain and shortness of breath.",
],
inputs=user_box,
)
# Add a button to start a new chat, which clears the conversation history and symptom context
new_chat_button = gr.Button("New Chat")
new_chat_button.click(new_chat, outputs=[chatbot, state, summary, result_card])
# Add a disclaimer
gr.Markdown(
"*Disclaimer: This app is for educational purposes only and is not a replacement for professional medical advice. Please consult a healthcare professional for medical concerns.*"
)
demo.launch(css=custom_css)
# Run the app
if __name__ == "__main__":
MedicalChatbotApp().launch()
"""
medical_chatbot_app.py
Multi-agent medical assistant with:
- ReAct-style LLM router
- FAISS-based diagnosis engine (in diagnosis_engine)
- Symptom severity scoring
- Disease description + precautions
- Logging & usage metrics
- Gradio UI
Requires:
pip install pandas numpy faiss-cpu scikit-learn gradio openai python-dotenv
"""
import os
import re
import json
import time
import logging
import hashlib
import html
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Any, Dict, List, Optional
import gradio as gr
import pandas as pd
from dotenv import load_dotenv
from openai import OpenAI
from diagnosis_engine import DiseaseDiagnosisAgent
from diagnosis_engine.vocabulary import map_to_known_symptoms, normalize_symptom
# ---------------------------------------------------------------------
# Environment
# ---------------------------------------------------------------------
# Load environment variables from likely .env locations relative to this file
BASE_DIR = Path(__file__).resolve().parent
ENV_CANDIDATES = [
BASE_DIR / ".env",
BASE_DIR.parent / ".env",
Path.cwd() / ".env",
]
for env_path in ENV_CANDIDATES:
if env_path.exists():
load_dotenv(env_path, override=False)
# Ensure OPENAI_API_KEY is set in the environment
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
searched = ", ".join(str(path) for path in ENV_CANDIDATES)
raise RuntimeError(
"OPENAI_API_KEY environment variable is not set. "
f"Add it to your environment or a .env file in one of these locations: {searched}"
)
# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)
# ---------------------------------------------------------------------
# Logging setup
# ---------------------------------------------------------------------
os.makedirs("logs", exist_ok=True)
# Set up a rotating file handler to keep logs manageable, and also log to console
handler = RotatingFileHandler("logs/app.log", maxBytes=2_000_000, backupCount=5)
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[handler, logging.StreamHandler()],
)
logger = logging.getLogger("medical_chatbot")
SAFE_ERROR_MESSAGE = (
"I couldn't complete your request. Please rephrase your symptoms, "
"ask for severity, or name a condition for description/precautions."
)
# ---------------------------------------------------------------------
# Metrics store
# ---------------------------------------------------------------------
# Track the number of calls to each agent and other relevant metrics for monitoring and analysis
METRICS = {
"diagnosis_calls": 0,
"severity_calls": 0,
"clarification_calls": 0,
"description_calls": 0,
"precaution_calls": 0,
}
# ---------------------------------------------------------------------
# ReAct prompt
# ---------------------------------------------------------------------
PLANNER_PROMPT = """
You are a medical triage planning assistant. Create a short execution plan using one or more of the available agents.